PHP Membership Provider

I came across a post made a little while ago by Steven Benner on PHP’s notable lack of a consistent Membership Provider as in ASP.Net. All good points, but I think the hard bit isn’t so much session management since there are a million examples out there on how to provide a login interface.

The tough part seems to be a consistent method of accessing, creating and maintaining users in a database. Also a lot of those examples tend to be MySQL specific so if you need something easily customized for something else, like say PostgreSQL, you’re pretty much stuck customizing to no end, at which point you might as well write your own.

And that seems to be what an overwhelming majority of people are doing if they’re not getting an off-the-shelf CMS to start with. Of the few frameworks for membership management that are available out there, most are a bit over complicated and have licenses, fees and other strings attached.

So most people are stuck writing a user management system from scratch or getting a CMS off the shelf with its own unique (and usually incompatible) user management system.

I got home from work early on Friday and have this weekend off for a pretty good rest, so early this morning, I thought I’d write up a Membership Provider for PHP that anyone can use with no strings attached (and hopefully doesn’t suck too much). The idea is to have a simple drop-in user management interface.

Keep in mind that I haven’t actually tested any of this and it all may in fact blow up spectacularly (since I didn’t do any testing, everything is as-is and I’m not a professional PHP programmer). It’s a bit late for Steven’s post, but better late than never eh? ;)

AND YOU NEED TO VALIDATE ALL INPUTS BEFORE SENDING THEM… ahem.

I didn’t want to mimic everything in the Membership Provider for ASP.Net in that there are a lot of things that I don’t like, some features that could be improved and others that are completely missing.

Notably, I don’t see the need for password questions and answers since resetting by email is often a better solution than lowering the security barrier by introducing (essentially) a weaker password in the form of an answer to a known question. Also, people often forget the answers to questions too or repeat the same questions and answers on different sites, which defeats the purpose of a strong password anyway.

I’d also like to have a way to find and delete users by either Id, Name or Email and easily lock/unlock, approve/unapprove users and provide strong passwords with Blowfish. For this last option, I downloaded the Portable PHP password hashing framework, which I think is the best implementation for PHP I’ve found so far.

Now I need a table…

Although this example table is in MySQL, you could modify this for any other database. In the queries, I avoided any MySQL specific commands like sql_calc_found_rows and the like and because I’m using PDO the code itself should work with no modifications on PostgreSQL and SQLite provided it’s the same table structure.

CREATE TABLE `users` (
  `userId` int(20) unsigned NOT NULL AUTO_INCREMENT,
  `username` varchar(50) NOT NULL,
  `hash` varchar(10) NOT NULL,
  `password` varchar(200) NOT NULL,
  `passwordSalt` varchar(100) NOT NULL,
  `email` varchar(100) NOT NULL,
  `avatar` varchar(200) DEFAULT NULL,
  `createdDate` datetime NOT NULL,
  `modifiedDate` datetime NOT NULL,
  `lastActivity` datetime NOT NULL,
  `bio` text DEFAULT NULL,
  `isApproved` tinyint(1) NOT NULL DEFAULT '1',
  `isLocked` tinyint(1) NOT NULL DEFAULT '0',

  PRIMARY KEY (`userId`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='Users' AUTO_INCREMENT=1 ;

Pretty typical for most websites. The “hash” there is just a unique key made by combining the username and email in a hash that will set apart users even with similar looking usernames. Think of it as a very primitive Tripcode shown alongside a username.

Configuration

If there’s one thing that makes configuring an ASP.Net web page consistent is the web.config file. It’s only appropriate then to put all the configuation stuff into one file, say a .ini, like so :

;*** Website configuration file ***
;
; All comments start with a semicolon (;), and this file can be something other than config.ini
; as long as the new file name is specified in index.php .

;*** Globally accessible settings ***

[Database]
dsn = "mysql:host=localhost;dbname=testdb"
username = "testuser"
password = "BKjSheQubKEufqHC"

[Tables]
usersTable = "users"
rolesTable = "roles"
tablePrefix = ""

;*** Membership specific settings ***

[MembershipProvider]
minRequiredPasswordLength = 5
maxInvalidPasswordAttempts = 3
passwordAttemptWindow = 10
userIsOnlineTimeWindow = 20
autoApproveUsers = "true"

Of course, for this example, we won’t be using all of that, but I just created a file called config.ini and put all that in there. Now how do we load all of this? First we need an index.php file.

index.php

<?php
ini_set( "display_errors", true );

// Set the application configuration file. You may store this outside the web root
// if your web host allows it.
define('INI', 'config.ini');


/*******************************

	End editing

********************************/


define('BASE_PATH', dirname(__FILE__));

// Platform specific include path separator
if ( strtolower(substr(PHP_OS, 0, 3)) === 'win') 
	define('SEP', ';');
else
	define('SEP', ':');

// There must be an /app folder in root with all the class files
define('CLASS_DIR', BASE_PATH . DIRECTORY_SEPARATOR . 'app' . DIRECTORY_SEPARATOR);

// Optionally there should also be a /mod folder in root where you can include modules/plugins in the future
define('MODULE_DIR', BASE_PATH . DIRECTORY_SEPARATOR . 'mod' . DIRECTORY_SEPARATOR);

// Modify include path
set_include_path( CLASS_DIR  . SEP . MODULE_DIR );


spl_autoload_extensions(".php");
spl_autoload_register();

?>

The down side to this approach is that all your file names must be lowercase, but it should be slightly faster than any other autoload implementation and I’m reasonably confident it should run on a *nix platform with no hiccups as well as on Windows.

For now, that autoload would force the application to look in the /app folder where all the magic happens and optionally in /mod for any future modules. And for that magic we’ll create a base class that all “action” classes would inherit from. This is basically to provide dynamic class properties.

<?php

/**
 * Base class provides dynamic class property functionality
 *
 * @package Base
 */
class Base {
	
	
	/**
	 * @var array Config properties storage
	 */
	protected $props = array();
	
	
	/**
	 * Get class accessible settings
	 */
	protected function __get( $key ) {
		return array_key_exists( $key, $this->props ) ? 
			$this->props[$key] : null;
	}
	
	
	/**
	 * Set class accessible settings
	 */
	protected function __set( $key, $value ) {
		$this->props[$key] = $value;
	}
	
	
	/**
	 * Checks whether accessible setting is available
	 */
	protected function __isset( $key ) {
		return isset( $this->props[$key] );
	}
}
?>

Now we need a configuration class that will load the settings from the defined .ini file into itself and make the settings accessible to all classes calling it.

<?php

/**
 * Application configuration file.
 * All settings are imported from the .ini file defined in index.php
 *
 * @package Config
 */

class Config extends Base {
	
	
	/**
	 * Class instance
	 */
	private static $instance;
	
	
	private function __construct() {
		$this->props = parse_ini_file(INI, true);
	}
	
	
	public static function getInstance() {
		if(!self::$instance)
			self::$instance = new Config();
		
		return self::$instance;
	}
}
?>

This is starting to get a bit long so onward to the next page

LINQ to SQL Membership Provider

It’s been a long time since I posted something programming related here, but luckily, I found some precious little spare time this weekend.

I used to run a portal a while back and a portion of it (namely the login system) was converted to the Provider Model back in the early 2000’s. And that’s where it stood for the better part of a decade. Even after the portal became defunct, I thought about dusting off the old code and reusing it in something. Yesterday, I decided to rewrite the Membership Provider into a LINQ to SQL model.

The following is the end result of an afternoon of conversions. It still hasn’t been fully tested and may contain bugs, errors or other terrible things. And of course, there is plenty of room for improvement.

The LINQ to SQL Dbml follows the following schema :

Database Schema part

As you can see there are parts that are missing, but the protions that pertain to the code below are included.

The MemberContentPrivilege class is based on individual privilege flags and there’s a matching GroupContentPrivilege class as well (not pictured). I created my CMS (called Osiris) originally with ASP in mind. But then with the arrival ASP.Net 2.0, I had the chance to use the existing role based authentication. With updates to the provider model, I kept changing the database until each role and a small number of users had a set of privilege flags with matching content IDs. It was far more granular for my purposes than the default RBAC in the Provider Model.

You can, of course, delete those role specific code sections. I’ve marked them with a link to this post.

WARNING:
I’m still not too comfortable with the WordPress source code formatter, so I’d be careful when copying.

Update

Well that was quick. ;)
I decided to scrap the global DataContext object and went with the “using” method instead. I think this will prevent memory issues.

/**
 * THIS SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Web.Mvc;
using System.Web.Security;
using System.Web.Configuration;
using System.Security.Cryptography;
using System.Configuration;
using System.Configuration.Provider;
using System.Text;
using Osiris.Models;

namespace Osiris.Providers
{
	public sealed class OsirisMembershipProvider : MembershipProvider
	{
		private MachineKeySection machineKey;

		/*************************************************************************
		 * General settings
		 *************************************************************************/

		private string _applicationName;
		public override string ApplicationName
		{
			get { return _applicationName; }
			set { _applicationName = value; }
		}

		private bool _requiresUniqeEmail;
		public override bool RequiresUniqueEmail
		{
			get { return _requiresUniqeEmail; }
		}


		/*************************************************************************
		 * Private settings
		 *************************************************************************/

		private string _providerName;
		public string ProviderName
		{
			get { return _providerName; }
		}

		private TimeSpan _userIsOnlineTimeWindow;
		public TimeSpan UserIsOnlineTimeWindow
		{
			get { return _userIsOnlineTimeWindow; }
		}



		/*************************************************************************
		 * Password settings
		 *************************************************************************/

		private int _minRequiredNonAlphanumericCharacters;
		public override int MinRequiredNonAlphanumericCharacters
		{
			get { return _minRequiredNonAlphanumericCharacters; }
		}

		private int _minRequiredPasswordLength;
		public override int MinRequiredPasswordLength
		{
			get { return _minRequiredPasswordLength; }
		}

		private bool _enablePasswordReset;
		public override bool EnablePasswordReset
		{
			get { return _enablePasswordReset; }
		}

		private bool _enablePasswordRetrieval;
		public override bool EnablePasswordRetrieval
		{
			get { return _enablePasswordRetrieval; }
		}

		private int _passwordAttemptWindow;
		public override int PasswordAttemptWindow
		{
			get { return _passwordAttemptWindow; }
		}

		private string _passwordStrengthRegularExpression;
		public override string PasswordStrengthRegularExpression
		{
			get { return _passwordStrengthRegularExpression; }
		}

		private MembershipPasswordFormat _passwordFormat;
		public override MembershipPasswordFormat PasswordFormat
		{
			get { return _passwordFormat; }
		}

		private int _maxInvalidPasswordAttempts;
		public override int MaxInvalidPasswordAttempts
		{
			get { return _maxInvalidPasswordAttempts; }
		}

		private bool _requiresQuestionAndAnswer;
		public override bool RequiresQuestionAndAnswer
		{
			get { return _requiresQuestionAndAnswer; }
		}


		/*************************************************************************
		 * User related methods : create, update, unlock, delete methods.
		 *************************************************************************/

		/// <summary>
		/// Creates a new user with a given set of default values
		/// </summary>
		public override MembershipUser CreateUser(string username, string password, string email,
			string passwordQuestion, string passwordAnswer, bool isApproved, object providerUserKey,
			out MembershipCreateStatus status)
		{
			ValidatePasswordEventArgs args = new ValidatePasswordEventArgs(username, password, true);

			OnValidatingPassword(args);

			if (args.Cancel)
			{
				status = MembershipCreateStatus.InvalidPassword;
				return null;
			}

			if (RequiresUniqueEmail && GetUserNameByEmail(email) != "")
			{
				status = MembershipCreateStatus.DuplicateEmail;
				return null;
			}

			// If no user with this name already exists
			if (GetUser(username, false) == null)
			{
				DateTime createdDate = DateTime.Now;

				string salt = "";
				if (PasswordFormat == MembershipPasswordFormat.Hashed)
				{
					salt = GenerateSalt();
					password = password + salt;
				}

				Member m = new Member();
				m.Username = username;
				m.Password = EncodePassword(password);
				m.PasswordSalt = salt;
				m.Email = email;

				// Set the password retrieval question and answer if they are required
				if (RequiresQuestionAndAnswer)
				{
					m.PasswordQuestion = passwordQuestion;
					m.PasswordAnswer = EncodePassword(passwordAnswer);
				}

				m.IsApproved = isApproved;
				m.IsLockedOut = false;
				m.Comment = "";
				m.CreatedDate = createdDate;
				m.LastLockoutDate = createdDate;
				m.LastLoginDate = createdDate;
				m.LastActivityDate = createdDate;
				m.LastPasswordChangedDate = createdDate;
				m.FailedPasswordAttemptCount = 0;
				m.FailedPasswordAttemptWindowStart = createdDate;
				m.FailedPasswordAnswerAttemptCount = 0;
				m.FailedPasswordAnswerAttemptWindowStart = createdDate;

				try
				{
					using (OsirisDataContext db = new OsirisDataContext())
					{
						// Add the new user to the database
						db.Members.InsertOnSubmit(m);

						// Add the user to a the signup group
						// See the blog post for more details : 
						// https://eksith.wordpress.com/2010/04/04/linq-to-sql-membership
						Group g = (from groups in db.Groups
								   where groups.Signup == true
								   select groups).Single();

						if (g != null)
						{
							MembersInGroup mg = new MembersInGroup();
							mg.Group = g;
							mg.Member = m;
							db.MembersInGroups.InsertOnSubmit(mg);
						}

						// Save changes
						db.SubmitChanges();
					}

					// User creation was a success
					status = MembershipCreateStatus.Success;

					// Return the newly craeted user
					return GetUserFromMember(m);
				}
				catch
				{
					// Something was wrong and the user was rejected
					status = MembershipCreateStatus.UserRejected;
				}
			}
			else
			{
				// There is already a user with this name
				status = MembershipCreateStatus.DuplicateUserName;
			}

			// Something went wrong if we got this far without some sort of status or retun
			if (status != MembershipCreateStatus.UserRejected && status != MembershipCreateStatus.DuplicateUserName)
				status = MembershipCreateStatus.ProviderError;
				
			return null;
		}

		/// <summary>
		/// Updates an existing user with new settings
		/// </summary>
		/// <param name="user">MembershipUser object to modify</param>
		public override void UpdateUser(MembershipUser user)
		{
			using (OsirisDataContext db = new OsirisDataContext())
			{
				Member m = (from members in db.Members
							where members.Username == user.UserName
							select members).Single();

				m.Comment = user.Comment;
				m.Email = user.Email;
				m.IsApproved = user.IsApproved;

				db.SubmitChanges();
			}
		}

		/// <summary>
		/// Unlocks a user (after too many login attempts perhaps)
		/// </summary>
		/// <param name="userName">Username to unlock</param>
		/// <returns>True if successful. Defaults to false.</returns>
		public override bool UnlockUser(string userName)
		{
			// Return status defaults to false
			bool ret = false;
			try
			{
				using (OsirisDataContext db = new OsirisDataContext())
				{
					Member m = (from members in db.Members
								where members.Username == userName
								select members).Single();

					m.IsLockedOut = false;

					// Save changes in the database
					db.SubmitChanges();
				}

				// A user was found and nothing was thrown
				ret = true;
			}
			catch
			{
				// Couldn't find the user or there was an error
				ret = false;
			}

			return ret;
		}

		/// <summary>
		/// Permanently deletes a user from the database
		/// </summary>
		/// <param name="username">Username to delete</param>
		/// <param name="deleteAllRelatedData">Should or shouldn't delete related user data</param>
		/// <returns>True if successful. Defaults to false.</returns>
		public override bool DeleteUser(string username, bool deleteAllRelatedData)
		{
			// Return status defaults to false.
			// When in doubt, always say "NO".
			bool ret = false;

			try
			{
				using (OsirisDataContext db = new OsirisDataContext())
				{
					Member m = (from members in db.Members
								where members.Username == username
								select members).Single();

					db.Members.DeleteOnSubmit(m);

					// Delete all releated group/role/profile data
					// See the blog post for more details : 
					// https://eksith.wordpress.com/2010/04/04/linq-to-sql-membership
					if (deleteAllRelatedData)
					{
						List<MembersInGroup> g = (from mg in db.MembersInGroups
												  where mg.Member.Username == username
												  select mg).ToList();

						List<MemberContentPrivilege> mc = (from mp in db.MemberContentPrivileges
														   where mp.Member.Username == username
														   select mp).ToList();

						db.MembersInGroups.DeleteAllOnSubmit(g);
						db.MemberContentPrivileges.DeleteAllOnSubmit(mc);
					}

					// Save changes in the database
					db.SubmitChanges();
				}
				// Nothing was thrown, so go ahead and return true
				ret = true;
			}
			catch
			{
				// Couldn't find the user or was not able to delete
				ret = false;
			}

			return ret;
		}

		/*************************************************************************
		 * User authentication methods
		 *************************************************************************/

		/// <summary>
		/// Authenticates a user with the given username and password
		/// </summary>
		/// <param name="password">The login username</param>
		/// <param name="username">Login password</param>
		/// <returns>True if successful. Defaults to false.</returns>
		public override bool ValidateUser(string username, string password)
		{
			// Return status defaults to false.
			bool ret = false;

			try
			{
				using (OsirisDataContext db = new OsirisDataContext())
				{
					Member m = (from members in db.Members
								where members.Username == username
								select members).Single();

					// We found a user by the username
					if (m != null)
					{
						// A user cannot login if not approved or locked out
						if ((!m.IsApproved) || m.IsLockedOut)
						{
							ret = false;
						}
						else
						{
							// Trigger period
							DateTime dt = DateTime.Now;

							// Check the given password and the one stored (and salt, if it exists)
							if (CheckPassword(password, m.Password, m.PasswordSalt))
							{
								m.LastLoginDate = dt;
								m.LastActivityDate = dt;

								// Reset past failures
								ResetAuthenticationFailures(ref m, dt);

								ret = true;
							}
							else
							{
								// The login failed... Increment the login attempt count
								m.FailedPasswordAttemptCount = (int)m.FailedPasswordAttemptCount + 1;

								if (m.FailedPasswordAttemptCount >= MaxInvalidPasswordAttempts)
									m.IsLockedOut = true;

								m.FailedPasswordAttemptWindowStart = dt;

							}
						}

						// Save changes
						db.SubmitChanges();
					}
				}
			}
			catch
			{
				// Nothing was thrown, so go ahead and return true
				ret = false;
			}

			return ret;
		}

		/// <summary>
		/// Gets the current password of a user (provided it isn't hashed)
		/// </summary>
		/// <param name="username">User the password is being retrieved for</param>
		/// <param name="answer">Password retrieval answer</param>
		/// <returns>User's passsword</returns>
		public override string GetPassword(string username, string answer)
		{
			// Default password is empty
			string password = String.Empty;

			if (PasswordFormat == MembershipPasswordFormat.Hashed)
			{
				throw new ProviderException("Hashed passwords cannot be retrieved. They must be reset.");
			}
			else
			{
				try
				{
					using (OsirisDataContext db = new OsirisDataContext())
					{
						Member m = (from members in db.Members
									where members.Username == username
									select members).Single();

						password = UnEncodePassword(m.Password);
					}
				}
				catch { }
			}
			return password;
		}

		/// <summary>
		/// Resets the passwords with a generated value
		/// </summary>
		/// <param name="username">User the password is being reset for</param>
		/// <param name="answer">Password retrieval answer</param>
		/// <returns>Newly generated password</returns>
		public override string ResetPassword(string username, string answer)
		{
			// Default password is empty
			string pass = String.Empty;

			try
			{
				using (OsirisDataContext db = new OsirisDataContext())
				{
					Member m = (from members in db.Members
								where members.Username == username
								select members).Single();

					// We found a user by that name
					if (m != null)
					{
						// Check if the returned password answer matches
						if (EncodePassword(answer) == m.PasswordAnswer)
						{
							// Create a new password with the minimum number of characters
							pass = GeneratePassword(MinRequiredPasswordLength);

							// If the password format is hashed, there must be a salt added
							string salt = "";
							if (PasswordFormat == MembershipPasswordFormat.Hashed)
							{
								salt = GenerateSalt();
								pass = pass + salt;
							}

							m.Password = EncodePassword(pass);
							m.PasswordSalt = salt;

							// Reset everyting
							ResetAuthenticationFailures(ref m, DateTime.Now);

							db.SubmitChanges();
						}
					}
				}
			}
			catch
			{
			}
			return pass;
		}

		/// <summary>
		/// Change the current password for a new one. Note: Both are required.
		/// </summary>
		/// <param name="username">Username the password is being changed for</param>
		/// <param name="oldPassword">Old password to verify owner</param>
		/// <param name="newPassword">New password</param>
		/// <returns>True if successful. Defaults to false.</returns>
		public override bool ChangePassword(string username, string oldPassword, string newPassword)
		{
			if (!ValidateUser(username, oldPassword))
				return false;

			ValidatePasswordEventArgs args = new ValidatePasswordEventArgs(username, newPassword, false);

			OnValidatingPassword(args);

			if (args.Cancel)
				if (args.FailureInformation != null)
					throw args.FailureInformation;
				else
					throw new MembershipPasswordException("Password change has been cancelled due to a validation failure.");

			bool ret = false;
			try
			{
				using (OsirisDataContext db = new OsirisDataContext())
				{
					Member m = (from members in db.Members
								where members.Username == username
								select members).Single();

					string salt = "";
					if (PasswordFormat == MembershipPasswordFormat.Hashed)
					{
						salt = GenerateSalt();
						newPassword = newPassword + salt;
					}

					m.Password = EncodePassword(newPassword);
					m.PasswordSalt = salt;

					// Reset everything
					ResetAuthenticationFailures(ref m, DateTime.Now);

					db.SubmitChanges();
				}
				ret = true;
			}
			catch
			{
				ret = false;
			}

			return ret;
		}

		/// <summary>
		/// Change the password retreival/reset question and answer pair
		/// </summary>
		/// <param name="username">Username the question and answer are being changed for</param>
		/// <param name="password">Current password</param>
		/// <param name="newPasswordQuestion">New password question</param>
		/// <param name="newPasswordAnswer">New password answer (will also be encrypted)</param>
		/// <returns>True if successful. Defaults to false.</returns>
		public override bool ChangePasswordQuestionAndAnswer(string username, string password,
			string newPasswordQuestion, string newPasswordAnswer)
		{
			if (!ValidateUser(username, password))
				return false;

			bool ret = false;
			try
			{
				using (OsirisDataContext db = new OsirisDataContext())
				{
					Member m = (from members in db.Members
								where members.Username == username
								select members).Single();

					m.PasswordQuestion = newPasswordQuestion;
					m.PasswordAnswer = EncodePassword(newPasswordAnswer);

					db.SubmitChanges();
				}
				ret = true;
			}
			catch
			{
				ret = false;
			}
			return ret;
		}


		/*************************************************************************
		 * User information retreival methods
		 *************************************************************************/

		/// <summary>
		/// Gets the username by a given matching email address
		/// </summary>
		public override string GetUserNameByEmail(string email)
		{
			string username = String.Empty;

			try
			{
				using (OsirisDataContext db = new OsirisDataContext())
				{
					username = (from members in db.Members
								where members.Email == email
								select members.Username).Single();
				}
			}
			catch
			{
			}
			return username;
		}

		/// <summary>
		/// Gets a MembershipUser object with a given key
		/// </summary>
		public override MembershipUser GetUser(object providerUserKey, bool userIsOnline)
		{
			MembershipUser u = null;
			try
			{
				using (OsirisDataContext db = new OsirisDataContext())
				{
					Member m = (from members in db.Members
								where members.MemberId == Convert.ToInt32(providerUserKey)
								select members).Single();

					if (m != null)
						u = GetUserFromMember(m);
				}
			}
			catch
			{ }

			return u;
		}

		/// <summary>
		/// Gets a MembershipUser object with a given username
		/// </summary>
		public override MembershipUser GetUser(string username, bool userIsOnline)
		{
			MembershipUser u = null;

			try
			{
				using (OsirisDataContext db = new OsirisDataContext())
				{
					Member m = (from members in db.Members
								where members.Username == username
								select members).Single();

					if (m != null)
						u = GetUserFromMember(m);
				}
			}
			catch
			{ }

			return u;
		}

		/// <summary>
		/// Gets all the users in the database
		/// </summary>
		/// <param name="pageIndex">Current page index</param>
		/// <param name="pageSize">Number of results per page</param>
		/// <param name="totalRecords">Total number of users returned</param>
		/// <returns>MembershpUserCollection object with a list of users on the page</returns>
		public override MembershipUserCollection GetAllUsers(int pageIndex, int pageSize,
			out int totalRecords)
		{
			MembershipUserCollection users = new MembershipUserCollection();
			totalRecords = 0;

			try
			{
				int start = pageSize * pageIndex;
				int end = start + pageSize;

				using (OsirisDataContext db = new OsirisDataContext())
				{
					totalRecords = (from members in db.Members
									select members).Count();

					List<Member> mlist = (from members in db.Members
										  select members).Skip(start).Take(pageSize).ToList();

					foreach (Member m in mlist)
						users.Add(GetUserFromMember(m));
				}
			}
			catch { }

			return users;
		}

		/// <summary>
		/// Gets the total number of users that are currently online.
		/// </summary>
		/// <returns>Returns user count (within UserIsOnlineTimeWindow minutes)</returns>
		public override int GetNumberOfUsersOnline()
		{
			int c = 0;
			try
			{
				using (OsirisDataContext db = new OsirisDataContext())
				{
					c = (from members in db.Members
						 where members.LastActivityDate.Add(UserIsOnlineTimeWindow) >= DateTime.Now
						 select members).Count();
				}
			}
			catch { }

			return c;
		}

		/// <summary>
		/// Finds a list of users with a matching email address
		/// </summary>
		/// <param name="emailToMatch">Given email to search</param>
		/// <param name="pageIndex">Current page index</param>
		/// <param name="pageSize">Number of results per page</param>
		/// <param name="totalRecords">Total number of users returned</param>
		/// <returns>MembershpUserCollection object with a list of users on the page</returns>
		public override MembershipUserCollection FindUsersByEmail(string emailToMatch,
			int pageIndex, int pageSize, out int totalRecords)
		{
			MembershipUserCollection users = new MembershipUserCollection();
			totalRecords = 0;

			try
			{
				int start = pageSize * pageIndex;
				int end = start + pageSize;

				using (OsirisDataContext db = new OsirisDataContext())
				{
					totalRecords = (from members in db.Members
									where members.Email.Contains(emailToMatch)
									select members).Count();

					List<Member> mlist = (from members in db.Members
										  where members.Email.Contains(emailToMatch)
										  select members).Skip(start).Take(pageSize).ToList();

					foreach (Member m in mlist)
						users.Add(GetUserFromMember(m));
				}
			}
			catch { }

			return users;
		}

		/// <summary>
		/// Gets a list of users with a matching username
		/// </summary>
		/// <param name="usernameToMatch">Username to search for</param>
		/// <param name="pageIndex">Current page index</param>
		/// <param name="pageSize">Number of results per page</param>
		/// <param name="totalRecords">Total number of users returned</param>
		/// <returns>MembershpUserCollection object with a list of users on the page</returns>
		public override MembershipUserCollection FindUsersByName(string usernameToMatch,
			int pageIndex, int pageSize, out int totalRecords)
		{
			MembershipUserCollection users = new MembershipUserCollection();
			totalRecords = 0;

			try
			{
				int start = pageSize * pageIndex;
				int end = start + pageSize;

				using (OsirisDataContext db = new OsirisDataContext())
				{
					totalRecords = (from members in db.Members
									select members).Count();

					List<Member> mlist = (from members in db.Members
										  where members.Username.Contains(usernameToMatch)
										  select members).Skip(start).Take(pageSize).ToList();

					foreach (Member m in mlist)
						users.Add(GetUserFromMember(m));
				}
			}
			catch { }

			return users;
		}


		/*************************************************************************
		 * Class initialization
		 *************************************************************************/

		public override void Initialize(string name, System.Collections.Specialized.NameValueCollection config)
		{
			if (config == null)
				throw new ArgumentNullException("config");


			if (name == null || name.Length == 0)
				name = "OsirisMembershipProvider";

			if (String.IsNullOrEmpty(config["description"]))
			{
				config.Remove("description");
				config.Add("description", "Osiris Membership Provider");
			}

			// Initialize base class
			base.Initialize(name, config);

			_applicationName = GetConfigValue(config["applicationName"],
				System.Web.Hosting.HostingEnvironment.ApplicationVirtualPath);

			// This is a non-standard helper setting.
			_providerName = GetConfigValue(config["providerName"], name);
			
			
			// Sets the default parameters for all the Membership Provider settings

			_requiresUniqeEmail = Convert.ToBoolean(GetConfigValue(config["requiresUniqueEmail"], "true"));
			_requiresQuestionAndAnswer = Convert.ToBoolean(GetConfigValue(config["requiresQuestionAndAnswer"], "true"));
			_minRequiredPasswordLength = Convert.ToInt32(GetConfigValue(config["minRequiredPasswordLength"], "5"));
			_minRequiredNonAlphanumericCharacters = Convert.ToInt32(GetConfigValue(config["minRequiredNonAlphanumericCharacters"],
				"0"));
			_enablePasswordReset = Convert.ToBoolean(GetConfigValue(config["enablePasswordReset"], "true"));
			_enablePasswordRetrieval = Convert.ToBoolean(GetConfigValue(config["enablePasswordRetrieval"], "false"));
			_passwordAttemptWindow = Convert.ToInt32(GetConfigValue(config["passwordAttemptWindow"], "10"));
			_passwordStrengthRegularExpression = GetConfigValue(config["passwordStrengthRegularExpression"], "");
			_maxInvalidPasswordAttempts = Convert.ToInt32(GetConfigValue(config["maxInvalidPasswordAttempts"],

				"5"));

			string passFormat = config["passwordFormat"];

			// If no format is specified, the default format will be hashed.
			if (passFormat == null)
				passFormat = "hashed";

			switch (passFormat.ToLower())
			{
				case "hashed":
					_passwordFormat = MembershipPasswordFormat.Hashed;
					break;
				case "encrypted":
					_passwordFormat = MembershipPasswordFormat.Hashed;
					break;
				case "clear":
					_passwordFormat = MembershipPasswordFormat.Clear;
					break;
				default:
					throw new ProviderException("Password format '" + passFormat + "' is not supported. Check your web.config file.");
			}

			Configuration cfg = WebConfigurationManager.OpenWebConfiguration(
				System.Web.Hosting.HostingEnvironment.ApplicationVirtualPath);

			machineKey = (MachineKeySection)cfg.GetSection("system.web/machineKey");

			if (machineKey.ValidationKey.Contains("AutoGenerate"))
				if (PasswordFormat != MembershipPasswordFormat.Clear)
					throw new ProviderException("Hashed or Encrypted passwords cannot be used with auto-generated keys.");

			MembershipSection membership = (MembershipSection)cfg.GetSection("system.web/membership");
			_userIsOnlineTimeWindow = membership.UserIsOnlineTimeWindow;
		}


		/*************************************************************************
		 * Private password helper methods
		 *************************************************************************/
		
		/// <summary>
		/// Compares a given password with one stored in the database and an optional salt
		/// </summary>
		private bool CheckPassword(string password, string dbpassword, string dbsalt)
		{
			string pass1 = password;
			string pass2 = dbpassword;
			bool ret = false;

			switch (PasswordFormat)
			{
				case MembershipPasswordFormat.Encrypted:
					pass2 = UnEncodePassword(dbpassword);
					break;
				case MembershipPasswordFormat.Hashed:
					pass1 = EncodePassword(password + dbsalt);
					break;
				default:
					break;
			}

			if (pass1 == pass2)
				ret = true;

			return ret;
		}

		/// <summary>
		/// Encodes a given password using the default MembershipPasswordFormat setting
		/// </summary>
		/// <param name="password">Password (plus salt as per above functions if necessary)</param>
		/// <returns>Clear form, Encrypted or Hashed password.</returns>
		private string EncodePassword(string password)
		{
			string encodedPassword = password;

			switch (PasswordFormat)
			{
				case MembershipPasswordFormat.Clear:
					break;
				case MembershipPasswordFormat.Encrypted:
					encodedPassword =
					  Convert.ToBase64String(EncryptPassword(Encoding.Unicode.GetBytes(password)));
					break;
				case MembershipPasswordFormat.Hashed:
					HMACSHA1 hash = new HMACSHA1();
					hash.Key = HexToByte(machineKey.ValidationKey);
					encodedPassword =
					  Convert.ToBase64String(hash.ComputeHash(Encoding.Unicode.GetBytes(password)));
					break;
				default:
					throw new ProviderException("Unsupported password format.");
			}

			return encodedPassword;
		}

		/// <summary>
		/// Decodes a given stored password into a cleartype or unencrypted form. Provided it isn't hashed.
		/// </summary>
		/// <param name="encodedPassword">Stored, encrypted password</param>
		/// <returns>Unecncrypted password</returns>
		private string UnEncodePassword(string encodedPassword)
		{
			string password = encodedPassword;

			switch (PasswordFormat)
			{
				case MembershipPasswordFormat.Clear:
					break;
				case MembershipPasswordFormat.Encrypted:
					password =
					  Encoding.Unicode.GetString(DecryptPassword(Convert.FromBase64String(password)));
					break;
				case MembershipPasswordFormat.Hashed:
					throw new ProviderException("Cannot decode hashed passwords.");
				default:
					throw new ProviderException("Unsupported password format.");
			}

			return password;
		}

		/// <summary>
		/// Converts a string into a byte array
		/// </summary>
		private byte[] HexToByte(string hexString)
		{
			byte[] returnBytes = new byte[hexString.Length / 2];
			for (int i = 0; i < returnBytes.Length; i++)
				returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
			return returnBytes;
		}

		/// <summary>
		/// Salt generation helper (this is essentially the same as the one in SqlMembershipProviders
		/// </summary>
		private string GenerateSalt()
		{
			byte[] buf = new byte[16];
			(new RNGCryptoServiceProvider()).GetBytes(buf);
			return Convert.ToBase64String(buf);
		}

		/// <summary>
		/// Generates a random password of given length (MinRequiredPasswordLength)
		/// </summary>
		private string GeneratePassword(int passLength)
		{
			string _range = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
			Byte[] _bytes = new Byte[passLength];
			char[] _chars = new char[passLength];

			RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();

			rng.GetBytes(_bytes);

			for (int i = 0; i < passLength; i++)
				_chars[i] = _range[_bytes[i] % _range.Length];

			return new string(_chars);
		}

		/*************************************************************************
		 * Private helper methods
		 *************************************************************************/

		/// <summary>
		/// Used in the initializtion, key in web.config or the default setting if null.
		/// </summary>
		private string GetConfigValue(string configValue, string defaultValue)
		{
			if (String.IsNullOrEmpty(configValue))
				return defaultValue;

			return configValue;
		}

		/// <summary>
		/// Upon a successful login or password reset, this changes all the previous failure markers to defaults.
		/// </summary>
		private static void ResetAuthenticationFailures(ref Member m, DateTime dt)
		{
			m.LastPasswordChangedDate = dt;
			m.FailedPasswordAttemptCount = 0;
			m.FailedPasswordAttemptWindowStart = dt;
			m.FailedPasswordAnswerAttemptCount = 0;
			m.FailedPasswordAnswerAttemptWindowStart = dt;
		}

		/// <summary>
		/// Converts a Member object into a MembershipUser object using its assigned settings
		/// </summary>
		private MembershipUser GetUserFromMember(Member m)
		{
			return new MembershipUser(this.ProviderName,
						m.Username,
						m.MemberId,
						m.Email,
						m.PasswordQuestion,
						m.Comment,
						m.IsApproved,
						m.IsLockedOut,
						m.CreatedDate,
						m.LastLoginDate,
						m.LastLoginDate,
						m.LastPasswordChangedDate,
						m.LastLockoutDate);
		}
	}
}

Enjoy!