在网上找了一个SqlMembershipProvider 的例子,今天在这里给大家贴出来
下面可以说是非常有用,把每个 membershipProvider 的方法都重载了.
//SqlMembershipProvider.cs
using System;
using System.Collections.Specialized;
using System.Data;
using System.Data.SqlClient;
using System.Security.Cryptography;
using System.Text.RegularExpressions;
using System.Configuration;
using System.Configuration.Provider;
using System.Text;
using System.Web.Security;
using System.Web;
namespace CustomComponents
...{
/**//// <summary>
/// Specifically designed to store user information in and to retrieve
/// user information from aspnetdb database
/// </summary>
public class SqlMembershipProvider : MembershipProvider
...{
Non-overridable Methods#region Non-overridable Methods
private bool UpdateUserInfo(string username, bool isPasswordCorrect, bool updateLastLoginActivityDate,
DateTime lastLoginDate, DateTime lastActivityDate)
...{
SqlParameter[] parameters = new SqlParameter[9];
parameters[0] = CreateSqlParameter("@ApplicationName", SqlDbType.NVarChar, this.ApplicationName);
parameters[1] = CreateSqlParameter("@UserName", SqlDbType.NVarChar, username);
parameters[2] = CreateSqlParameter("@IsPasswordCorrect", SqlDbType.Bit, isPasswordCorrect);
parameters[3] = CreateSqlParameter("@UpdateLastLoginActivityDate", SqlDbType.Bit, updateLastLoginActivityDate);
parameters[4] = CreateSqlParameter("@MaxInvalidPasswordAttempts", SqlDbType.Int, this.MaxInvalidPasswordAttempts);
parameters[5] = CreateSqlParameter("@PasswordAttemptWindow", SqlDbType.Int, this.PasswordAttemptWindow);
parameters[6] = CreateSqlParameter("@CurrentTimeUtc", SqlDbType.DateTime, DateTime.UtcNow);
parameters[7] = CreateSqlParameter("@LastLoginDate", SqlDbType.DateTime, isPasswordCorrect ? DateTime.UtcNow : lastLoginDate);
parameters[8] = CreateSqlParameter("@LastActivityDate", SqlDbType.DateTime, isPasswordCorrect ? DateTime.UtcNow : lastActivityDate);
return Update("aspnet_Membership_UpdateUserInfo", parameters);
}
private bool ValidateUserInfo(string username, string password, bool updateLastLoginActivityDate,
bool failIfNotApproved, out string passwordSalt, out int passwordFormat)
...{
string dbEncodedPassword = null;
passwordFormat = 0;
passwordSalt = null;
int failedPasswordAttemptCount = 0;
int failedPasswordAnswerAttemptCount = 0;
bool isApproved = false;
DateTime lastLoginDate = DateTime.UtcNow;
DateTime lastActivityDate = DateTime.UtcNow;
SqlParameter[] parameters = new SqlParameter[4];
parameters[0] = CreateSqlParameter("@ApplicationName", SqlDbType.NVarChar, this.ApplicationName);
parameters[1] = CreateSqlParameter("@UserName", SqlDbType.NVarChar, username);
parameters[2] = CreateSqlParameter("@UpdateLastLoginActivityDate", SqlDbType.Bit, updateLastLoginActivityDate);
parameters[3] = CreateSqlParameter("@CurrentTimeUtc", SqlDbType.DateTime, DateTime.UtcNow);
SqlDataReader reader = Select("aspnet_Membership_GetPasswordWithFormat", parameters);
if (reader.Read())
...{
dbEncodedPassword = reader.GetString(0);
passwordFormat = reader.GetInt32(1);
passwordSalt = reader.GetString(2);
failedPasswordAttemptCount = reader.GetInt32(3);
failedPasswordAnswerAttemptCount = reader.GetInt32(4);
isApproved = reader.GetBoolean(5);
lastLoginDate = reader.GetDateTime(6);
lastActivityDate = reader.GetDateTime(7);
}
reader.Close();
if (!isApproved && failIfNotApproved)
return false;
string encodedPassword = GetEncodedPassword(password, passwordFormat, passwordSalt);
bool isPasswordCorrect = dbEncodedPassword.Equals(encodedPassword);
if ((isPasswordCorrect && (failedPasswordAttemptCount == 0)) && (failedPasswordAnswerAttemptCount == 0))
return true;
return UpdateUserInfo(username, isPasswordCorrect, updateLastLoginActivityDate,
lastLoginDate, lastActivityDate);
}
private bool ValidateUserInfo(string username, string password, bool updateLastLoginActivityDate, bool failIfNotApproved)
...{
string salt;
int format;
return ValidateUserInfo(username, password, updateLastLoginActivityDate, failIfNotApproved, out salt, out format);
}
private byte[] GetSaltedPassword(string password, string salt)
...{
byte[] passwordBuff = Encoding.Unicode.GetBytes(password);
byte[] saltBuff = Convert.FromBase64String(salt);
byte[] saltedPassword = new byte[saltBuff.Length + passwordBuff.Length];
Buffer.BlockCopy(saltBuff, 0, saltedPassword, 0, saltBuff.Length);
Buffer.BlockCopy(passwordBuff, 0, saltedPassword, saltBuff.Length, passwordBuff.Length);
return saltedPassword;
}
private string GetEncodedPassword(string password, int passwordFormat, string passwordSalt)
...{
string encodedPassword;
byte[] buff;
byte[] saltedPassword;
switch (passwordFormat)
...{
case 0:
encodedPassword = password;
break;
case 1:
saltedPassword = GetSaltedPassword(password, passwordSalt);
HashAlgorithm hashAlgorithm = HashAlgorithm.Create(Membership.HashAlgorithmType);
buff = hashAlgorithm.ComputeHash(saltedPassword);
encodedPassword = Convert.ToBase64String(buff);
break;
default:
saltedPassword = GetSaltedPassword(password, passwordSalt);
buff = EncryptPassword(saltedPassword);
encodedPassword = Convert.ToBase64String(buff);
break;
}
return encodedPassword;
}
private SqlParameter CreateSqlParameter(string name, SqlDbType type, object value)
...{
SqlParameter parameter = new SqlParameter(name, type);
if (value == null)
...{
parameter.IsNullable = true;
parameter.Value = DBNull.Value;
}
else
parameter.Value = value;
return parameter;
}
private SqlDataReader Select(string storedProcedureName, SqlParameter[] parameters)
...{
SqlConnection con = new SqlConnection(connectionString);
SqlCommand com = new SqlCommand(storedProcedureName, con);
com.CommandType = CommandType.StoredProcedure;
com.Parameters.AddRange(parameters);
con.Open();
return com.ExecuteReader(CommandBehavior.CloseConnection);
}
private bool Update(string storedProcedureName, SqlParameter[] parameters)
...{
SqlConnection con = new SqlConnection(connectionString);
SqlCommand com = new SqlCommand(storedProcedureName, con);
com.CommandType = CommandType.StoredProcedure;
com.Parameters.AddRange(parameters);
bool success = true;
int rowsAffected = -1;
con.Open();
try
...{
rowsAffected = com.ExecuteNonQuery();
success = (rowsAffected > 0);
}
catch (Exception ex)
...{
success = false;
}
finally
...{
con.Close();
}
return success;
}
#endregion
Overridable Properties#region Overridable Properties
private string applicationName;
/**//// <summary>
/// Application name under which the user information is stored
/// </summary>
public override string ApplicationName
...{
get ...{ return applicationName; }
set ...{ applicationName = value; }
}
private bool enablePasswordReset;
/**//// <summary>
/// Specifies whether users can reset their passwords
/// </summary>
public override bool EnablePasswordReset
...{
get ...{ return enablePasswordReset; }
}
private bool enablePasswordRetrieval;
/**//// <summary>
/// Specifies whether users can retrieve their passwords
/// </summary>
public override bool EnablePasswordRetrieval
...{
get ...{ return enablePasswordRetrieval; }
}
private int maxInvalidPasswordAttempts;
/**//// <summary>
/// Maximum number of failed password attempts before the user is locked out
/// </summary>
public override int MaxInvalidPasswordAttempts
...{
get ...{ return maxInvalidPasswordAttempts; }
}
private int minRequiredNonAlphanumericCharacters;
/**//// <summary>
/// Minimum number of non-alphanumeric characters that a password must contain
/// </summary>
public override int MinRequiredNonAlphanumericCharacters
...{
get ...{ return minRequiredNonAlphanumericCharacters; }
}
private int minRequiredPasswordLength;
/**//// <summary>
/// Minimum length of a valid password
/// </summary>
public override int MinRequiredPasswordLength
...{
get ...{ return minRequiredPasswordLength; }
}
private int passwordAttemptWindow;
/**//// <summary>
///
/// </summary>
public override int PasswordAttemptWindow
...{
get ...{ return passwordAttemptWindow; }
}
private MembershipPasswordFormat passwordFormat;
/**//// <summary>
/// Format in which the passwords are stored in the database
/// </summary>
public override MembershipPasswordFormat PasswordFormat
...{
get ...{ return passwordFormat; }
}
private string passwordStrengthRegularExpression;
/**//// <summary>
/// Regular expression pattern that a valid password must match
/// </summary>
public override string PasswordStrengthRegularExpression
...{
get ...{ return passwordStrengthRegularExpression; }
}
private bool requiresQuestionAndAnswer;
/**//// <summary>
/// Specifies whether users must answer a predefined question before they can
/// reset, change, or retrieve their passwords
/// </summary>
public override bool RequiresQuestionAndAnswer
...{
get ...{ return requiresQuestionAndAnswer; }
}
private bool requiresUniqueEmail;
/**//// <summary>
/// Specifies whether the password should be unique
/// </summary>
public override bool RequiresUniqueEmail
...{
get ...{ return requiresUniqueEmail; }
}
private string connectionString;
#endregion
Overridable Methods#region Overridable Methods
/**//// <summary>
/// Changes a specified user's password
/// </summary>
/// <param name="username">
/// User's username
/// </param>
/// <param name="oldPassword">
/// User's old password
/// </param>
/// <param name="newPassword">
/// User's new password
/// </param>
/// <returns></returns>
public override bool ChangePassword(string username, string oldPassword, string newPassword)
...{
int passwordFormat;
string passwordSalt = null;
if (!this.ValidateUserInfo(username, oldPassword, false, false, out passwordSalt, out passwordFormat))
return false;
if (newPassword.Length < this.MinRequiredPasswordLength)
throw new ArgumentException("Password is too short!");
int nonAlphanumericCharactersCount = 0;
for (int cnt = 0; cnt < newPassword.Length; cnt++)
...{
if (!char.IsLetterOrDigit(newPassword, cnt))
nonAlphanumericCharactersCount++;
}
if (nonAlphanumericCharactersCount < MinRequiredNonAlphanumericCharacters)
throw new ArgumentException("Password requires more non aplphanumeric characters");
if ((PasswordStrengthRegularExpression.Length > 0) && !Regex.IsMatch(newPassword, PasswordStrengthRegularExpression))
throw new ArgumentException("Password does not match regular expression");
string encodedPassword = GetEncodedPassword(newPassword, passwordFormat, passwordSalt);
ValidatePasswordEventArgs args = new ValidatePasswordEventArgs(username, newPassword, false);
this.OnValidatingPassword(args);
if (args.Cancel)
...{
if (args.FailureInformation != null)
throw args.FailureInformation;
throw new ArgumentException("Application-specific password validation failed!");
}
SqlParameter[] parameters = new SqlParameter[6];
parameters[0] = CreateSqlParameter("@ApplicationName", SqlDbType.NVarChar, ApplicationName);
parameters[1] = CreateSqlParameter("@UserName", SqlDbType.NVarChar, username);
parameters[2] = CreateSqlParameter("@NewPassword", SqlDbType.NVarChar, encodedPassword);
parameters[3] = CreateSqlParameter("@PasswordSalt", SqlDbType.NVarChar, passwordSalt);
parameters[4] = CreateSqlParameter("@PasswordFormat", SqlDbType.Int, passwordFormat);
parameters[5] = CreateSqlParameter("@CurrentTimeUtc", SqlDbType.DateTime, DateTime.UtcNow);
return Update("aspnet_Membership_SetPassword", parameters);
}
/**//// <summary>
/// Changes the password question and answer
/// </summary>
/// <param name="username">
/// User's username
/// </param>
/// <param name="password">
/// User's password
/// </param>
/// <param name="newPasswordQuestion">
/// User's new password question
/// </param>
/// <param name="newPasswordAnswer">
/// User's new password answer
/// </param>
/// <returns></returns>
public override bool ChangePasswordQuestionAndAnswer(string username, string password, string newPasswordQuestion, string newPasswordAnswer)
...{
string encodedNewPasswordAnswer;
int passwordFormat;
string passwordSalt = null;
if (!this.ValidateUserInfo(username, password, false, false, out passwordSalt, out passwordFormat))
return false;
if (newPasswordAnswer != null)
newPasswordAnswer = newPasswordAnswer.Trim();
if (!string.IsNullOrEmpty(newPasswordAnswer))
encodedNewPasswordAnswer = GetEncodedPassword(newPasswordAnswer.ToLower(), passwordFormat, passwordSalt);
else
encodedNewPasswordAnswer = newPasswordAnswer;
SqlParameter[] parameters = new SqlParameter[4];
parameters[0] = CreateSqlParameter("@ApplicationName", SqlDbType.NVarChar, this.ApplicationName);
parameters[1] = CreateSqlParameter("@UserName", SqlDbType.NVarChar, username);
parameters[2] = CreateSqlParameter("@NewPasswordQuestion", SqlDbType.NVarChar, newPasswordQuestion);
parameters[3] = CreateSqlParameter("@NewPasswordAnswer", SqlDbType.NVarChar, encodedNewPasswordAnswer);
return Update("aspnet_Membership_ChangePasswordQuestionAndAnswer", parameters);
}
/**//// <summary>
/// Creates a new user record
/// </summary>
/// <param name="username">
/// User's username
/// </param>
/// <param name="password">
/// User's password
/// </param>
/// <param name="email">
/// User's email
/// </param>
/// <param name="passwordQuestion">
/// User's password question
/// </param>
/// <param name="passwordAnswer">
/// User's password answer
/// </param>
/// <param name="isApproved">
/// Specifies wether the user is approved
/// </param>
/// <param name="providerUserKey">
/// Specifies the key that uniquely identifies the user record among other records
/// </param>
/// <param name="status"></param>
/// <returns>
/// MembershipUser that represents the newly created user
/// </returns>
public override MembershipUser CreateUser(string username, string password, string email,
string passwordQuestion, string passwordAnswer, bool isApproved,
object providerUserKey, out MembershipCreateStatus status)
...{
string encodedPasswordAnswer;
byte[] randomNumber = new byte[1];
RNGCryptoServiceProvider gen = new RNGCryptoServiceProvider();
gen.GetBytes(randomNumber);
string passwordSalt = Convert.ToBase64String(randomNumber);
string encodedPassword = GetEncodedPassword(password, (int)passwordFormat, passwordSalt);
if (passwordAnswer != null)
passwordAnswer = passwordAnswer.Trim();
if (!string.IsNullOrEmpty(passwordAnswer))
encodedPasswordAnswer = GetEncodedPassword(passwordAnswer.ToLower(), (int)this.passwordFormat, passwordSalt);
else
encodedPasswordAnswer = passwordAnswer;
if ((providerUserKey != null) && !(providerUserKey is Guid))
...{
status = MembershipCreateStatus.InvalidProviderUserKey;
return null;
}
if (password.Length < MinRequiredPasswordLength)
...{
status = MembershipCreateStatus.InvalidPassword;
return null;
}
int nonAlphanumericCharactersCount = 0;
for (int cnt = 0; cnt < password.Length; cnt++)
...{
if (!char.IsLetterOrDigit(password, cnt))
nonAlphanumericCharactersCount++;
}
if (nonAlphanumericCharactersCount < MinRequiredNonAlphanumericCharacters)
...{
status = MembershipCreateStatus.InvalidPassword;
return null;
}
if ((PasswordStrengthRegularExpression.Length > 0) && !Regex.IsMatch(password, PasswordStrengthRegularExpression))
...{
status = MembershipCreateStatus.InvalidPassword;
return null;
}
ValidatePasswordEventArgs args = new ValidatePasswordEventArgs(username, password, true);
this.OnValidatingPassword(args);
if (args.Cancel)
...{
status = MembershipCreateStatus.InvalidPassword;
return null;
}
SqlParameter[] parameters = new SqlParameter[13];
parameters[0] = CreateSqlParameter("@ApplicationName", SqlDbType.NVarChar, ApplicationName);
parameters[1] = CreateSqlParameter("@UserName", SqlDbType.NVarChar, username);
parameters[2] = CreateSqlParameter("@Password", SqlDbType.NVarChar, encodedPassword);
parameters[3] = CreateSqlParameter("@PasswordSalt", SqlDbType.NVarChar, passwordSalt);
parameters[4] = CreateSqlParameter("@Email", SqlDbType.NVarChar, email);
parameters[5] = CreateSqlParameter("@PasswordQuestion", SqlDbType.NVarChar, passwordQuestion);
parameters[6] = CreateSqlParameter("@PasswordAnswer", SqlDbType.NVarChar, encodedPasswordAnswer);
parameters[7] = CreateSqlParameter("@IsApproved", SqlDbType.Bit, isApproved);
parameters[8] = CreateSqlParameter("@UniqueEmail", SqlDbType.Int, RequiresUniqueEmail ? 1 : 0);
parameters[9] = CreateSqlParameter("@PasswordFormat", SqlDbType.Int, (int)PasswordFormat);
parameters[10] = CreateSqlParameter("@CurrentTimeUtc", SqlDbType.DateTime, DateTime.UtcNow);
parameters[11] = CreateSqlParameter("@CreateDate", SqlDbType.DateTime, DateTime.Now);
parameters[12] = CreateSqlParameter("@UserId", SqlDbType.UniqueIdentifier, providerUserKey);
parameters[12].Direction = ParameterDirection.Output;
if (!Update("aspnet_Membership_CreateUser", parameters))
...{
status = MembershipCreateStatus.UserRejected;
return null;
}
status = MembershipCreateStatus.Success;
providerUserKey = new Guid(parameters[12].Value.ToString());
DateTime localTime = DateTime.UtcNow.ToLocalTime();
return new MembershipUser(Name, username, providerUserKey, email, passwordQuestion, null,
isApproved, false, localTime, localTime, localTime, localTime, localTime);
}
/**//// <summary>
/// Deletes a specified user record
/// </summary>
/// <param name="username">
/// Username of the user whose record is being deleted
/// </param>
/// <param name="deleteAllRelatedData">
/// Indicates whether all related records of the user should be deleted as well
/// </param>
/// <returns></returns>
public override bool DeleteUser(string username, bool deleteAllRelatedData)
...{
SqlParameter[] parameters = new SqlParameter[4];
parameters[0] = CreateSqlParameter("@ApplicationName", SqlDbType.NVarChar, ApplicationName);
parameters[1] = CreateSqlParameter("@UserName", SqlDbType.NVarChar, username);
if (deleteAllRelatedData)
parameters[2] = CreateSqlParameter("@TablesToDeleteFrom", SqlDbType.Int, 15);
else
parameters[2] = CreateSqlParameter("@TablesToDeleteFrom", SqlDbType.Int, 1);
parameters[3] = new SqlParameter("@NumTablesDeletedFrom", SqlDbType.Int);
parameters[3].Direction = ParameterDirection.Output;
return Update("aspnet_Users_DeleteUser", parameters);
}
/**//// <summary>
/// Finds users whose email matches a specified email
/// </summary>
/// <param name="emailToMatch">
/// Email to match
/// </param>
/// <param name="pageIndex">
/// Index of the page of user records to be retrieved
/// </param>
/// <param name="pageSize">
/// Maximum number of user records to be retrieved
/// </param>
/// <param name="totalRecords">
/// Total user records
/// </param>
/// <returns>
/// Collection of MembershipUser objects where each object represents a user record
/// </returns>
public override MembershipUserCollection FindUsersByEmail(string emailToMatch, int pageIndex, int pageSize,
out int totalRecords)
...{
if (pageIndex < 0)
throw new ArgumentException("Page index cannot be negative!");
if (pageSize < 1)
throw new ArgumentException("Page size cannot be less than one!");
SqlParameter[] parameters = new SqlParameter[5];
MembershipUserCollection collection = null;
totalRecords = 0;
parameters[0] = CreateSqlParameter("@ApplicationName", SqlDbType.NVarChar, ApplicationName);
parameters[1] = CreateSqlParameter("@EmailToMatch", SqlDbType.NVarChar, emailToMatch);
parameters[2] = CreateSqlParameter("@PageIndex", SqlDbType.Int, pageIndex);
parameters[3] = CreateSqlParameter("@PageSize", SqlDbType.Int, pageSize);
parameters[4] = new SqlParameter("@ReturnValue", SqlDbType.Int);
parameters[4].Direction = ParameterDirection.ReturnValue;
SqlDataReader reader = Select("aspnet_Membership_FindUsersByEmail", parameters);
collection = new MembershipUserCollection();
while (reader.Read())
...{
string text1 = !reader.IsDBNull(0) ? reader.GetString(0) : null;
string text2 = !reader.IsDBNull(1) ? reader.GetString(1) : null;
string text3 = !reader.IsDBNull(2) ? reader.GetString(2) : null;
string text4 = !reader.IsDBNull(3) ? reader.GetString(3) : null;
bool flag1 = reader.GetBoolean(4);
DateTime time6 = reader.GetDateTime(5);
DateTime time1 = time6.ToLocalTime();
DateTime time7 = reader.GetDateTime(6);
DateTime time2 = time7.ToLocalTime();
DateTime time8 = reader.GetDateTime(7);
DateTime time3 = time8.ToLocalTime();
DateTime time9 = reader.GetDateTime(8);
DateTime time4 = time9.ToLocalTime();
Guid guid1 = reader.GetGuid(9);
bool flag2 = reader.GetBoolean(10);
DateTime time10 = reader.GetDateTime(11);
DateTime time5 = time10.ToLocalTime();
collection.Add(new MembershipUser(Name, text1, guid1, text2, text3,
text4, flag1, flag2, time1, time2, time3, time4, time5));
}
reader.Close();
if ((parameters[4].Value != null) && (parameters[4].Value is int))
totalRecords = (int)parameters[5].Value;
return collection;
}
/**//// <summary>
/// Retrieves user records whose username matches a specfied pattern
/// </summary>
/// <param name="usernameToMatch">
/// User name pattern to match
/// </param>
/// <param name="pageIndex">
/// Index of the page of user records to be retrieved
/// </param>
/// <param name="pageSize">
/// Maximum number of user records to be retrieved
/// </param>
/// <param name="totalRecords"></param>
/// <returns>
/// Collection of MembershipUser objects where each object represets a user record
/// </returns>
public override MembershipUserCollection FindUsersByName(string usernameToMatch, int pageIndex,
int pageSize, out int totalRecords)
...{
if (pageIndex < 0)
throw new ArgumentException("Page index cannot be negative!");
if (pageSize < 1)
throw new ArgumentException("Page size cannot be less than one!");
SqlParameter[] parameters = new SqlParameter[5];
MembershipUserCollection collection = null;
totalRecords = 0;
parameters[0] = CreateSqlParameter("@ApplicationName", SqlDbType.NVarChar, ApplicationName);
parameters[1] = CreateSqlParameter("@UserNameToMatch", SqlDbType.NVarChar, usernameToMatch);
parameters[2] = CreateSqlParameter("@PageIndex", SqlDbType.Int, pageIndex);
parameters[3] = CreateSqlParameter("@PageSize", SqlDbType.Int, pageSize);
parameters[4] = new SqlParameter("@ReturnValue", SqlDbType.Int);
parameters[4].Direction = ParameterDirection.ReturnValue;
SqlDataReader reader = Select("aspnet_Membership_FindUsersByName", parameters);
collection = new MembershipUserCollection();
while (reader.Read())
...{
string text1 = !reader.IsDBNull(0) ? reader.GetString(0) : null;
string text2 = !reader.IsDBNull(1) ? reader.GetString(1) : null;
string text3 = !reader.IsDBNull(2) ? reader.GetString(2) : null;
string text4 = !reader.IsDBNull(3) ? reader.GetString(3) : null;
bool flag1 = reader.GetBoolean(4);
DateTime time6 = reader.GetDateTime(5);
DateTime time1 = time6.ToLocalTime();
DateTime time7 = reader.GetDateTime(6);
DateTime time2 = time7.ToLocalTime();
DateTime time8 = reader.GetDateTime(7);
DateTime time3 = time8.ToLocalTime();
DateTime time9 = reader.GetDateTime(8);
DateTime time4 = time9.ToLocalTime();
Guid guid1 = reader.GetGuid(9);
bool flag2 = reader.GetBoolean(10);
DateTime time10 = reader.GetDateTime(11);
DateTime time5 = time10.ToLocalTime();
collection.Add(new MembershipUser(Name, text1, guid1, text2, text3, text4,
flag1, flag2, time1, time2, time3, time4, time5));
}
reader.Close();
if ((parameters[4].Value != null) && (parameters[4].Value is int))
totalRecords = (int)parameters[4].Value;
return collection;
}
/**//// <summary>
/// Retrieves all users of a specified application
/// </summary>
/// <param name="pageIndex">
/// Index of the page of user records to be retrieved
/// </param>
/// <param name="pageSize">
/// Maximum number of user records to be retrieved
/// </param>
/// <param name="totalRecords"></param>
/// <returns>
/// Collection of MembershipUser objects where each object represents a user
/// </returns>
public override MembershipUserCollection GetAllUsers(int pageIndex, int pageSize, out int totalRecords)
...{
if (pageIndex < 0)
throw new ArgumentException("Page index cannot be negative!");
if (pageSize < 1)
throw new ArgumentException("Page size cannot be less than one!");
SqlParameter[] parameters = new SqlParameter[4];
MembershipUserCollection collection = null;
totalRecords = 0;
parameters[0] = CreateSqlParameter("@ApplicationName", SqlDbType.NVarChar, ApplicationName);
parameters[1] = CreateSqlParameter("@PageIndex", SqlDbType.Int, pageIndex);
parameters[2] = CreateSqlParameter("@PageSize", SqlDbType.Int, pageSize);
parameters[3] = new SqlParameter("@ReturnValue", SqlDbType.Int);
parameters[3].Direction = ParameterDirection.ReturnValue;
SqlDataReader reader = Select("aspnet_Membership_GetAllUsers", parameters);
collection = new MembershipUserCollection();
while (reader.Read())
...{
string text1 = !reader.IsDBNull(0) ? reader.GetString(0) : null;
string text2 = !reader.IsDBNull(1) ? reader.GetString(1) : null;
string text3 = !reader.IsDBNull(2) ? reader.GetString(2) : null;
string text4 = !reader.IsDBNull(3) ? reader.GetString(3) : null;
bool flag1 = reader.GetBoolean(4);
DateTime time6 = reader.GetDateTime(5);
DateTime time1 = time6.ToLocalTime();
DateTime time7 = reader.GetDateTime(6);
DateTime time2 = time7.ToLocalTime();
DateTime time8 = reader.GetDateTime(7);
DateTime time3 = time8.ToLocalTime();
DateTime time9 = reader.GetDateTime(8);
DateTime time4 = time9.ToLocalTime();
Guid guid1 = reader.GetGuid(9);
bool flag2 = reader.GetBoolean(10);
DateTime time10 = reader.GetDateTime(11);
DateTime time5 = time10.ToLocalTime();
collection.Add(new MembershipUser(this.Name, text1, guid1, text2, text3, text4, flag1, flag2, time1, time2, time3, time4, time5));
}
reader.Close();
if ((parameters[3].Value != null) && (parameters[3].Value is int))
totalRecords = (int)parameters[3].Value;
return collection;
}
/**//// <summary>
/// Retrieves the number of users online
/// </summary>
/// <returns></returns>
public override int GetNumberOfUsersOnline()
...{
SqlParameter[] parameters = new SqlParameter[4];
parameters[0] = CreateSqlParameter("@ApplicationName", SqlDbType.NVarChar, ApplicationName);
parameters[1] = CreateSqlParameter("@MinutesSinceLastInActive", SqlDbType.Int, Membership.UserIsOnlineTimeWindow);
parameters[2] = CreateSqlParameter("@CurrentTimeUtc", SqlDbType.DateTime, DateTime.UtcNow);
parameters[3] = new SqlParameter("@ReturnValue", SqlDbType.Int);
parameters[3].Direction = ParameterDirection.ReturnValue;
Select("aspnet_Membership_GetNumberOfUsersOnline", parameters);
return ((parameters[3].Value != null) ? ((int)parameters[3].Value) : -1);
}
/**//// <summary>
/// Retrieves the password of a specfied user
/// </summary>
/// <param name="username">
/// Username of the user whose password is being retrieved
/// </param>
/// <param name="passwordAnswer">
/// Password answer of the user
/// </param>
/// <returns>
/// String value that contains the user's password
/// </returns>
public override string GetPassword(string username, string passwordAnswer)
...{
if (!EnablePasswordRetrieval)
throw new NotSupportedException("Password cannot be retrieved!");
if (string.IsNullOrEmpty(passwordAnswer))
return passwordAnswer;
int format = 0;
string salt = null;
SqlParameter[] parameters;
SqlDataReader reader;
string encodedPasswordAnswer = null;
if (RequiresQuestionAndAnswer)
...{
parameters = new SqlParameter[4];
parameters[0] = CreateSqlParameter("@ApplicationName", SqlDbType.NVarChar, this.ApplicationName);
parameters[1] = CreateSqlParameter("@UserName", SqlDbType.NVarChar, username);
parameters[2] = CreateSqlParameter("@UpdateLastLoginActivityDate", SqlDbType.Bit, false);
parameters[3] = CreateSqlParameter("@CurrentTimeUtc", SqlDbType.DateTime, DateTime.UtcNow);
reader = Select("aspnet_Membership_GetPasswordWithFormat", parameters);
if (reader.Read())
...{
format = reader.GetInt32(1);
salt = reader.GetString(2);
}
reader.Close();
encodedPasswordAnswer = GetEncodedPassword(passwordAnswer.ToLower(), format, salt);
}
if (RequiresQuestionAndAnswer)
parameters = new SqlParameter[6];
else
parameters = new SqlParameter[5];
parameters[0] = CreateSqlParameter("@ApplicationName", SqlDbType.NVarChar, ApplicationName);
parameters[1] = CreateSqlParameter("@UserName", SqlDbType.NVarChar, username);
parameters[2] = CreateSqlParameter("@MaxInvalidPasswordAttempts", SqlDbType.Int, MaxInvalidPasswordAttempts);
parameters[3] = CreateSqlParameter("@PasswordAttemptWindow", SqlDbType.Int, PasswordAttemptWindow);
parameters[4] = CreateSqlParameter("@CurrentTimeUtc", SqlDbType.DateTime, DateTime.UtcNow);
if (requiresQuestionAndAnswer)
parameters[5] = CreateSqlParameter("@PasswordAnswer", SqlDbType.NVarChar, encodedPasswordAnswer);
reader = Select("aspnet_Membership_GetPassword", parameters);
string password = null;
if (reader.Read())
...{
password = reader.GetString(0);
format = reader.GetInt32(1);
}
reader.Close();
if (password != null && format == 2)
...{
byte[] decodedPassword = Convert.FromBase64String(password);
byte[] decryptedPassword = this.DecryptPassword(decodedPassword);
if (decryptedPassword == null)
password = null;
else
password = Encoding.Unicode.GetString(decryptedPassword);
//password = Encoding.Unicode.GetString(decryptedPassword, 0x10, decryptedPassword.Length - 0x10);
}
return password;
}
/**//// <summary>
/// Retrieves the user record of a specified user
/// </summary>
/// <param name="providerUserKey">
/// Key that uniquely identifies the user record
/// </param>
/// <param name="userIsOnline">
/// Indicates whether the user is online
/// </param>
/// <returns>
/// MembershipUser that represents the user record
/// </returns>
public override MembershipUser GetUser(object providerUserKey, bool userIsOnline)
...{
MembershipUser user = null;
if (providerUserKey == null)
throw new ArgumentNullException("providerUserKey cannot be null!");
if (!(providerUserKey is Guid))
throw new ArgumentException("providerUserKey is not of type Guid!");
SqlParameter[] parameters = new SqlParameter[3];
parameters[0] = CreateSqlParameter("@UserId", SqlDbType.UniqueIdentifier, providerUserKey);
parameters[1] = CreateSqlParameter("@UpdateLastActivity", SqlDbType.Bit, userIsOnline);
parameters[2] = CreateSqlParameter("@CurrentTimeUtc", SqlDbType.DateTime, DateTime.UtcNow);
SqlDataReader reader = Select("aspnet_Membership_GetUserByUserId", parameters);
if (reader.Read())
...{
string text1 = !reader.IsDBNull(0) ? reader.GetString(0) : null;
string text2 = !reader.IsDBNull(1) ? reader.GetString(1) : null;
string text3 = !reader.IsDBNull(2) ? reader.GetString(2) : null;
bool flag1 = reader.GetBoolean(3);
DateTime time6 = reader.GetDateTime(4);
DateTime time1 = time6.ToLocalTime();
DateTime time7 = reader.GetDateTime(5);
DateTime time2 = time7.ToLocalTime();
DateTime time8 = reader.GetDateTime(6);
DateTime time3 = time8.ToLocalTime();
DateTime time9 = reader.GetDateTime(7);
DateTime time4 = time9.ToLocalTime();
string text4 = !reader.IsDBNull(8) ? reader.GetString(8) : null;
bool flag2 = reader.GetBoolean(9);
DateTime time10 = reader.GetDateTime(10);
DateTime time5 = time10.ToLocalTime();
user = new MembershipUser(this.Name, text4, providerUserKey, text1, text2, text3, flag1, flag2, time1, time2, time3, time4, time5);
}
reader.Close();
return user;
}
/**//// <summary>
/// Retrieves the user record of the user with a specified username
/// </summary>
/// <param name="username">
/// Username of the user whose record is being retrieved
/// </param>
/// <param name="userIsOnline">
/// Indicates whether the user is currently online
/// </param>
/// <returns>
/// MembershipUser that represents the retrieved user record
/// </returns>
public override MembershipUser GetUser(string username, bool userIsOnline)
...{
MembershipUser user = null;
SqlParameter[] parameters = new SqlParameter[4];
parameters[0] = CreateSqlParameter("@ApplicationName", SqlDbType.NVarChar, ApplicationName);
parameters[1] = CreateSqlParameter("@UserName", SqlDbType.NVarChar, username);
parameters[2] = CreateSqlParameter("@UpdateLastActivity", SqlDbType.Bit, userIsOnline);
parameters[3] = CreateSqlParameter("@CurrentTimeUtc", SqlDbType.DateTime, DateTime.UtcNow);
SqlDataReader reader = Select("aspnet_Membership_GetUserByName", parameters);
if (reader.Read())
...{
string text1 = !reader.IsDBNull(0) ? reader.GetString(0) : null;
string text2 = !reader.IsDBNull(1) ? reader.GetString(1) : null;
string text3 = !reader.IsDBNull(2) ? reader.GetString(2) : null;
bool flag1 = reader.GetBoolean(3);
DateTime time6 = reader.GetDateTime(4);
DateTime time1 = time6.ToLocalTime();
DateTime time7 = reader.GetDateTime(5);
DateTime time2 = time7.ToLocalTime();
DateTime time8 = reader.GetDateTime(6);
DateTime time3 = time8.ToLocalTime();
DateTime time9 = reader.GetDateTime(7);
DateTime time4 = time9.ToLocalTime();
Guid guid1 = reader.GetGuid(8);
bool flag2 = reader.GetBoolean(9);
DateTime time10 = reader.GetDateTime(10);
DateTime time5 = time10.ToLocalTime();
user = new MembershipUser(Name, username, guid1, text1, text2, text3, flag1, flag2,
time1, time2, time3, time4, time5);
}
reader.Close();
return user;
}
/**//// <summary>
/// Retrieves the username of a user with the specified email
/// </summary>
/// <param name="email">
/// Email of the user record being retrieved
/// </param>
/// <returns>
/// String value that contains the username
/// </returns>
public override string GetUserNameByEmail(string email)
...{
SqlParameter[] parameters = new SqlParameter[2];
parameters[0] = CreateSqlParameter("@ApplicationName", SqlDbType.NVarChar, ApplicationName);
parameters[1] = CreateSqlParameter("@Email", SqlDbType.NVarChar, email);
SqlDataReader reader = Select("aspnet_Membership_GetUserByEmail", parameters);
string text = null;
if (reader.Read())
text = !reader.IsDBNull(0) ? reader.GetString(0) : null;
reader.Close();
return text;
}
/**//// <summary>
/// Initializes the SqlMembershipProvider
/// </summary>
/// <param name="name">
/// Friendly name of the provider
/// </param>
/// <param name="config">
/// NameValueCollection that contains the values used to initialize the
/// provider's properties and fields
/// </param>
public override void Initialize(string name, NameValueCollection config)
...{
if (config == null)
throw new ArgumentNullException("config");
if (string.IsNullOrEmpty(name))
name = "SqlMembershipProvider";
if (string.IsNullOrEmpty(config["description"]))
...{
config.Remove("description");
config.Add("description", "Stores membership information in SQL Server database");
}
base.Initialize(name, config);
enablePasswordRetrieval = (config["enablePasswordRetrieval"] != null) ? bool.Parse(config["enablePasswordRetrieval"]) : false;
config.Remove("enablePasswordRetrieval");
enablePasswordReset = (config["enablePasswordReset"] != null) ? bool.Parse(config["enablePasswordReset"]) : true;
config.Remove("enablePasswordReset");
requiresQuestionAndAnswer = (config["requiresQuestionAndAnswer"] != null) ? bool.Parse(config["requiresQuestionAndAnswer"]) : true;
config.Remove("requiresQuestionAndAnswer");
requiresUniqueEmail = (config["requiresUniqueEmail"] != null) ? bool.Parse(config["requiresUniqueEmail"]) : true;
config.Remove("requiresUniqueEmail");
maxInvalidPasswordAttempts = config["passwordAttemptWindow"] != null ? int.Parse(config["passwordAttemptWindow"]) : 5;
config.Remove("maxInvalidPasswordAttempts");
passwordAttemptWindow = config["passwordAttemptWindow"] != null ? int.Parse(config["passwordAttemptWindow"]) : 10;
config.Remove("passwordAttemptWindow");
minRequiredPasswordLength = config["minRequiredPasswordLength"] != null ? int.Parse(config["minRequiredPasswordLength"]) : 7;
config.Remove("minRequiredPasswordLength");
minRequiredNonAlphanumericCharacters = config["minRequiredNonalphanumericCharacters"] != null ? int.Parse(config["minRequiredNonalphanumericCharacters"]) : 1;
config.Remove("minRequiredNonalphanumericCharacters");
passwordStrengthRegularExpression = config["passwordStrengthRegularExpression"];
config.Remove("passwordStrengthRegularExpression");
if (minRequiredNonAlphanumericCharacters > minRequiredPasswordLength)
throw new HttpException();
applicationName = config["applicationName"];
if (string.IsNullOrEmpty(applicationName))
applicationName = "/";
config.Remove("applicationName");
string strTemp = config["passwordFormat"];
if (string.IsNullOrEmpty(strTemp))
strTemp = "Hashed";
switch (strTemp)
...{
case "Clear":
passwordFormat = MembershipPasswordFormat.Clear;
break;
case "Encrypted":
passwordFormat = MembershipPasswordFormat.Encrypted;
break;
case "Hashed":
passwordFormat = MembershipPasswordFormat.Hashed;
break;
default:
throw new ProviderException("Bad password format");
}
if ((PasswordFormat == MembershipPasswordFormat.Hashed) && EnablePasswordRetrieval)
throw new ProviderException();
config.Remove("passwordFormat");
ConnectionStringSettings settings = ConfigurationManager.ConnectionStrings[config["connectionStringName"]];
connectionString = settings.ConnectionString;
if (string.IsNullOrEmpty(connectionString))
throw new ProviderException("Invalid connection string name");
config.Remove("connectionStringName");
if (config.Count > 0)
...{
string key = config.GetKey(0);
if (!string.IsNullOrEmpty(key))
throw new ProviderException("Unrecognized attribute");
}
}
/**//// <summary>
/// Resets the password of the user with the specified username and password answer
/// </summary>
/// <param name="username">
/// Username of the user whose password is being reset
/// </param>
/// <param name="passwordAnswer">
/// Password answer of the user whose password is being reset
/// </param>
/// <returns>
/// New password of the user
/// </returns>
public override string ResetPassword(string username, string passwordAnswer)
...{
if (!this.EnablePasswordReset)
throw new NotSupportedException();
int format = 0;
string salt = null;
SqlParameter[] parameters;
SqlDataReader reader;
string encodedPasswordAnswer = null;
parameters = new SqlParameter[4];
parameters[0] = CreateSqlParameter("@ApplicationName", SqlDbType.NVarChar, this.ApplicationName);
parameters[1] = CreateSqlParameter("@UserName", SqlDbType.NVarChar, username);
parameters[2] = CreateSqlParameter("@UpdateLastLoginActivityDate", SqlDbType.Bit, false);
parameters[3] = CreateSqlParameter("@CurrentTimeUtc", SqlDbType.DateTime, DateTime.UtcNow);
reader = Select("aspnet_Membership_GetPasswordWithFormat", parameters);
if (reader.Read())
...{
format = reader.GetInt32(1);
salt = reader.GetString(2);
}
reader.Close();
if (!string.IsNullOrEmpty(passwordAnswer))
encodedPasswordAnswer = GetEncodedPassword(passwordAnswer.ToLower(), format, salt);
else
encodedPasswordAnswer = passwordAnswer;
string generatedPassword = Membership.GeneratePassword((MinRequiredPasswordLength < 14) ? 14 : MinRequiredPasswordLength, MinRequiredNonAlphanumericCharacters);
ValidatePasswordEventArgs args = new ValidatePasswordEventArgs(username, generatedPassword, false);
this.OnValidatingPassword(args);
if (args.Cancel)
...{
if (args.FailureInformation != null)
throw args.FailureInformation;
//throw new ProviderException();
}
if (this.RequiresQuestionAndAnswer)
parameters = new SqlParameter[9];
else
parameters = new SqlParameter[8];
parameters[0] = CreateSqlParameter("@ApplicationName", SqlDbType.NVarChar, ApplicationName);
parameters[1] = CreateSqlParameter("@UserName", SqlDbType.NVarChar, username);
parameters[2] = CreateSqlParameter("@NewPassword", SqlDbType.NVarChar, GetEncodedPassword(generatedPassword, format, salt));
parameters[3] = CreateSqlParameter("@MaxInvalidPasswordAttempts", SqlDbType.Int, MaxInvalidPasswordAttempts);
parameters[4] = CreateSqlParameter("@PasswordAttemptWindow", SqlDbType.Int, PasswordAttemptWindow);
parameters[5] = CreateSqlParameter("@PasswordSalt", SqlDbType.NVarChar, salt);
parameters[6] = CreateSqlParameter("@PasswordFormat", SqlDbType.Int, format);
parameters[7] = CreateSqlParameter("@CurrentTimeUtc", SqlDbType.DateTime, DateTime.UtcNow);
if (this.RequiresQuestionAndAnswer)
parameters[8] = CreateSqlParameter("@PasswordAnswer", SqlDbType.NVarChar, encodedPasswordAnswer);
Update("aspnet_Membership_ResetPassword", parameters);
return generatedPassword;
}
/**//// <summary>
/// Unlocks the user with a specified username
/// </summary>
/// <param name="username">
/// Username of the user being unlocked
/// </param>
/// <returns></returns>
public override bool UnlockUser(string username)
...{
SqlParameter[] parameters = new SqlParameter[2];
parameters[0] = CreateSqlParameter("@ApplicationName", SqlDbType.NVarChar, ApplicationName);
parameters[1] = CreateSqlParameter("@UserName", SqlDbType.NVarChar, username);
return Update("aspnet_Membership_UnlockUser", parameters);
}
/**//// <summary>
/// Updates the record of the user with a specfied MembershipUser
/// </summary>
/// <param name="user">
/// MembershipUser object that contains the new information about the user
/// </param>
public override void UpdateUser(MembershipUser user)
...{
if (user == null)
throw new ArgumentNullException();
SqlParameter[] parameters = new SqlParameter[9];
parameters[0] = CreateSqlParameter("@ApplicationName", SqlDbType.NVarChar, ApplicationName);
parameters[1] = CreateSqlParameter("@UserName", SqlDbType.NVarChar, user.UserName);
parameters[2] = CreateSqlParameter("@Email", SqlDbType.NVarChar, user.Email);
parameters[3] = CreateSqlParameter("@Comment", SqlDbType.NText, user.Comment);
parameters[4] = CreateSqlParameter("@IsApproved", SqlDbType.Bit, user.IsApproved ? 1 : 0);
parameters[5] = CreateSqlParameter("@LastLoginDate", SqlDbType.DateTime, user.LastLoginDate.ToUniversalTime());
parameters[6] = CreateSqlParameter("@LastActivityDate", SqlDbType.DateTime, user.LastActivityDate.ToUniversalTime());
parameters[7] = CreateSqlParameter("@UniqueEmail", SqlDbType.Int, this.RequiresUniqueEmail ? 1 : 0);
parameters[8] = CreateSqlParameter("@CurrentTimeUtc", SqlDbType.DateTime, DateTime.UtcNow);
Update("aspnet_Membership_UpdateUser", parameters);
}
/**//// <summary>
/// Validates user credentials against the database
/// </summary>
/// <param name="username">
/// Username of the user being validated
/// </param>
/// <param name="password">
/// Password of the user being validated
/// </param>
/// <returns></returns>
public override bool ValidateUser(string username, string password)
...{
return ValidateUserInfo(username, password, true, true);
}
#endregion
}
}
using System;
using System.Collections.Specialized;
using System.Data;
using System.Data.SqlClient;
using System.Security.Cryptography;
using System.Text.RegularExpressions;
using System.Configuration;
using System.Configuration.Provider;
using System.Text;
using System.Web.Security;
using System.Web;
namespace CustomComponents
...{
/**//// <summary>
/// Specifically designed to store user information in and to retrieve
/// user information from aspnetdb database
/// </summary>
public class SqlMembershipProvider : MembershipProvider
...{
Non-overridable Methods#region Non-overridable Methods
private bool UpdateUserInfo(string username, bool isPasswordCorrect, bool updateLastLoginActivityDate,
DateTime lastLoginDate, DateTime lastActivityDate)
...{
SqlParameter[] parameters = new SqlParameter[9];
parameters[0] = CreateSqlParameter("@ApplicationName", SqlDbType.NVarChar, this.ApplicationName);
parameters[1] = CreateSqlParameter("@UserName", SqlDbType.NVarChar, username);
parameters[2] = CreateSqlParameter("@IsPasswordCorrect", SqlDbType.Bit, isPasswordCorrect);
parameters[3] = CreateSqlParameter("@UpdateLastLoginActivityDate", SqlDbType.Bit, updateLastLoginActivityDate);
parameters[4] = CreateSqlParameter("@MaxInvalidPasswordAttempts", SqlDbType.Int, this.MaxInvalidPasswordAttempts);
parameters[5] = CreateSqlParameter("@PasswordAttemptWindow", SqlDbType.Int, this.PasswordAttemptWindow);
parameters[6] = CreateSqlParameter("@CurrentTimeUtc", SqlDbType.DateTime, DateTime.UtcNow);
parameters[7] = CreateSqlParameter("@LastLoginDate", SqlDbType.DateTime, isPasswordCorrect ? DateTime.UtcNow : lastLoginDate);
parameters[8] = CreateSqlParameter("@LastActivityDate", SqlDbType.DateTime, isPasswordCorrect ? DateTime.UtcNow : lastActivityDate);
return Update("aspnet_Membership_UpdateUserInfo", parameters);
}
private bool ValidateUserInfo(string username, string password, bool updateLastLoginActivityDate,
bool failIfNotApproved, out string passwordSalt, out int passwordFormat)
...{
string dbEncodedPassword = null;
passwordFormat = 0;
passwordSalt = null;
int failedPasswordAttemptCount = 0;
int failedPasswordAnswerAttemptCount = 0;
bool isApproved = false;
DateTime lastLoginDate = DateTime.UtcNow;
DateTime lastActivityDate = DateTime.UtcNow;
SqlParameter[] parameters = new SqlParameter[4];
parameters[0] = CreateSqlParameter("@ApplicationName", SqlDbType.NVarChar, this.ApplicationName);
parameters[1] = CreateSqlParameter("@UserName", SqlDbType.NVarChar, username);
parameters[2] = CreateSqlParameter("@UpdateLastLoginActivityDate", SqlDbType.Bit, updateLastLoginActivityDate);
parameters[3] = CreateSqlParameter("@CurrentTimeUtc", SqlDbType.DateTime, DateTime.UtcNow);
SqlDataReader reader = Select("aspnet_Membership_GetPasswordWithFormat", parameters);
if (reader.Read())
...{
dbEncodedPassword = reader.GetString(0);
passwordFormat = reader.GetInt32(1);
passwordSalt = reader.GetString(2);
failedPasswordAttemptCount = reader.GetInt32(3);
failedPasswordAnswerAttemptCount = reader.GetInt32(4);
isApproved = reader.GetBoolean(5);
lastLoginDate = reader.GetDateTime(6);
lastActivityDate = reader.GetDateTime(7);
}
reader.Close();
if (!isApproved && failIfNotApproved)
return false;
string encodedPassword = GetEncodedPassword(password, passwordFormat, passwordSalt);
bool isPasswordCorrect = dbEncodedPassword.Equals(encodedPassword);
if ((isPasswordCorrect && (failedPasswordAttemptCount == 0)) && (failedPasswordAnswerAttemptCount == 0))
return true;
return UpdateUserInfo(username, isPasswordCorrect, updateLastLoginActivityDate,
lastLoginDate, lastActivityDate);
}
private bool ValidateUserInfo(string username, string password, bool updateLastLoginActivityDate, bool failIfNotApproved)
...{
string salt;
int format;
return ValidateUserInfo(username, password, updateLastLoginActivityDate, failIfNotApproved, out salt, out format);
}
private byte[] GetSaltedPassword(string password, string salt)
...{
byte[] passwordBuff = Encoding.Unicode.GetBytes(password);
byte[] saltBuff = Convert.FromBase64String(salt);
byte[] saltedPassword = new byte[saltBuff.Length + passwordBuff.Length];
Buffer.BlockCopy(saltBuff, 0, saltedPassword, 0, saltBuff.Length);
Buffer.BlockCopy(passwordBuff, 0, saltedPassword, saltBuff.Length, passwordBuff.Length);
return saltedPassword;
}
private string GetEncodedPassword(string password, int passwordFormat, string passwordSalt)
...{
string encodedPassword;
byte[] buff;
byte[] saltedPassword;
switch (passwordFormat)
...{
case 0:
encodedPassword = password;
break;
case 1:
saltedPassword = GetSaltedPassword(password, passwordSalt);
HashAlgorithm hashAlgorithm = HashAlgorithm.Create(Membership.HashAlgorithmType);
buff = hashAlgorithm.ComputeHash(saltedPassword);
encodedPassword = Convert.ToBase64String(buff);
break;
default:
saltedPassword = GetSaltedPassword(password, passwordSalt);
buff = EncryptPassword(saltedPassword);
encodedPassword = Convert.ToBase64String(buff);
break;
}
return encodedPassword;
}
private SqlParameter CreateSqlParameter(string name, SqlDbType type, object value)
...{
SqlParameter parameter = new SqlParameter(name, type);
if (value == null)
...{
parameter.IsNullable = true;
parameter.Value = DBNull.Value;
}
else
parameter.Value = value;
return parameter;
}
private SqlDataReader Select(string storedProcedureName, SqlParameter[] parameters)
...{
SqlConnection con = new SqlConnection(connectionString);
SqlCommand com = new SqlCommand(storedProcedureName, con);
com.CommandType = CommandType.StoredProcedure;
com.Parameters.AddRange(parameters);
con.Open();
return com.ExecuteReader(CommandBehavior.CloseConnection);
}
private bool Update(string storedProcedureName, SqlParameter[] parameters)
...{
SqlConnection con = new SqlConnection(connectionString);
SqlCommand com = new SqlCommand(storedProcedureName, con);
com.CommandType = CommandType.StoredProcedure;
com.Parameters.AddRange(parameters);
bool success = true;
int rowsAffected = -1;
con.Open();
try
...{
rowsAffected = com.ExecuteNonQuery();
success = (rowsAffected > 0);
}
catch (Exception ex)
...{
success = false;
}
finally
...{
con.Close();
}
return success;
}
#endregion
Overridable Properties#region Overridable Properties
private string applicationName;
/**//// <summary>
/// Application name under which the user information is stored
/// </summary>
public override string ApplicationName
...{
get ...{ return applicationName; }
set ...{ applicationName = value; }
}
private bool enablePasswordReset;
/**//// <summary>
/// Specifies whether users can reset their passwords
/// </summary>
public override bool EnablePasswordReset
...{
get ...{ return enablePasswordReset; }
}
private bool enablePasswordRetrieval;
/**//// <summary>
/// Specifies whether users can retrieve their passwords
/// </summary>
public override bool EnablePasswordRetrieval
...{
get ...{ return enablePasswordRetrieval; }
}
private int maxInvalidPasswordAttempts;
/**//// <summary>
/// Maximum number of failed password attempts before the user is locked out
/// </summary>
public override int MaxInvalidPasswordAttempts
...{
get ...{ return maxInvalidPasswordAttempts; }
}
private int minRequiredNonAlphanumericCharacters;
/**//// <summary>
/// Minimum number of non-alphanumeric characters that a password must contain
/// </summary>
public override int MinRequiredNonAlphanumericCharacters
...{
get ...{ return minRequiredNonAlphanumericCharacters; }
}
private int minRequiredPasswordLength;
/**//// <summary>
/// Minimum length of a valid password
/// </summary>
public override int MinRequiredPasswordLength
...{
get ...{ return minRequiredPasswordLength; }
}
private int passwordAttemptWindow;
/**//// <summary>
///
/// </summary>
public override int PasswordAttemptWindow
...{
get ...{ return passwordAttemptWindow; }
}
private MembershipPasswordFormat passwordFormat;
/**//// <summary>
/// Format in which the passwords are stored in the database
/// </summary>
public override MembershipPasswordFormat PasswordFormat
...{
get ...{ return passwordFormat; }
}
private string passwordStrengthRegularExpression;
/**//// <summary>
/// Regular expression pattern that a valid password must match
/// </summary>
public override string PasswordStrengthRegularExpression
...{
get ...{ return passwordStrengthRegularExpression; }
}
private bool requiresQuestionAndAnswer;
/**//// <summary>
/// Specifies whether users must answer a predefined question before they can
/// reset, change, or retrieve their passwords
/// </summary>
public override bool RequiresQuestionAndAnswer
...{
get ...{ return requiresQuestionAndAnswer; }
}
private bool requiresUniqueEmail;
/**//// <summary>
/// Specifies whether the password should be unique
/// </summary>
public override bool RequiresUniqueEmail
...{
get ...{ return requiresUniqueEmail; }
}
private string connectionString;
#endregion
Overridable Methods#region Overridable Methods
/**//// <summary>
/// Changes a specified user's password
/// </summary>
/// <param name="username">
/// User's username
/// </param>
/// <param name="oldPassword">
/// User's old password
/// </param>
/// <param name="newPassword">
/// User's new password
/// </param>
/// <returns></returns>
public override bool ChangePassword(string username, string oldPassword, string newPassword)
...{
int passwordFormat;
string passwordSalt = null;
if (!this.ValidateUserInfo(username, oldPassword, false, false, out passwordSalt, out passwordFormat))
return false;
if (newPassword.Length < this.MinRequiredPasswordLength)
throw new ArgumentException("Password is too short!");
int nonAlphanumericCharactersCount = 0;
for (int cnt = 0; cnt < newPassword.Length; cnt++)
...{
if (!char.IsLetterOrDigit(newPassword, cnt))
nonAlphanumericCharactersCount++;
}
if (nonAlphanumericCharactersCount < MinRequiredNonAlphanumericCharacters)
throw new ArgumentException("Password requires more non aplphanumeric characters");
if ((PasswordStrengthRegularExpression.Length > 0) && !Regex.IsMatch(newPassword, PasswordStrengthRegularExpression))
throw new ArgumentException("Password does not match regular expression");
string encodedPassword = GetEncodedPassword(newPassword, passwordFormat, passwordSalt);
ValidatePasswordEventArgs args = new ValidatePasswordEventArgs(username, newPassword, false);
this.OnValidatingPassword(args);
if (args.Cancel)
...{
if (args.FailureInformation != null)
throw args.FailureInformation;
throw new ArgumentException("Application-specific password validation failed!");
}
SqlParameter[] parameters = new SqlParameter[6];
parameters[0] = CreateSqlParameter("@ApplicationName", SqlDbType.NVarChar, ApplicationName);
parameters[1] = CreateSqlParameter("@UserName", SqlDbType.NVarChar, username);
parameters[2] = CreateSqlParameter("@NewPassword", SqlDbType.NVarChar, encodedPassword);
parameters[3] = CreateSqlParameter("@PasswordSalt", SqlDbType.NVarChar, passwordSalt);
parameters[4] = CreateSqlParameter("@PasswordFormat", SqlDbType.Int, passwordFormat);
parameters[5] = CreateSqlParameter("@CurrentTimeUtc", SqlDbType.DateTime, DateTime.UtcNow);
return Update("aspnet_Membership_SetPassword", parameters);
}
/**//// <summary>
/// Changes the password question and answer
/// </summary>
/// <param name="username">
/// User's username
/// </param>
/// <param name="password">
/// User's password
/// </param>
/// <param name="newPasswordQuestion">
/// User's new password question
/// </param>
/// <param name="newPasswordAnswer">
/// User's new password answer
/// </param>
/// <returns></returns>
public override bool ChangePasswordQuestionAndAnswer(string username, string password, string newPasswordQuestion, string newPasswordAnswer)
...{
string encodedNewPasswordAnswer;
int passwordFormat;
string passwordSalt = null;
if (!this.ValidateUserInfo(username, password, false, false, out passwordSalt, out passwordFormat))
return false;
if (newPasswordAnswer != null)
newPasswordAnswer = newPasswordAnswer.Trim();
if (!string.IsNullOrEmpty(newPasswordAnswer))
encodedNewPasswordAnswer = GetEncodedPassword(newPasswordAnswer.ToLower(), passwordFormat, passwordSalt);
else
encodedNewPasswordAnswer = newPasswordAnswer;
SqlParameter[] parameters = new SqlParameter[4];
parameters[0] = CreateSqlParameter("@ApplicationName", SqlDbType.NVarChar, this.ApplicationName);
parameters[1] = CreateSqlParameter("@UserName", SqlDbType.NVarChar, username);
parameters[2] = CreateSqlParameter("@NewPasswordQuestion", SqlDbType.NVarChar, newPasswordQuestion);
parameters[3] = CreateSqlParameter("@NewPasswordAnswer", SqlDbType.NVarChar, encodedNewPasswordAnswer);
return Update("aspnet_Membership_ChangePasswordQuestionAndAnswer", parameters);
}
/**//// <summary>
/// Creates a new user record
/// </summary>
/// <param name="username">
/// User's username
/// </param>
/// <param name="password">
/// User's password
/// </param>
/// <param name="email">
/// User's email
/// </param>
/// <param name="passwordQuestion">
/// User's password question
/// </param>
/// <param name="passwordAnswer">
/// User's password answer
/// </param>
/// <param name="isApproved">
/// Specifies wether the user is approved
/// </param>
/// <param name="providerUserKey">
/// Specifies the key that uniquely identifies the user record among other records
/// </param>
/// <param name="status"></param>
/// <returns>
/// MembershipUser that represents the newly created user
/// </returns>
public override MembershipUser CreateUser(string username, string password, string email,
string passwordQuestion, string passwordAnswer, bool isApproved,
object providerUserKey, out MembershipCreateStatus status)
...{
string encodedPasswordAnswer;
byte[] randomNumber = new byte[1];
RNGCryptoServiceProvider gen = new RNGCryptoServiceProvider();
gen.GetBytes(randomNumber);
string passwordSalt = Convert.ToBase64String(randomNumber);
string encodedPassword = GetEncodedPassword(password, (int)passwordFormat, passwordSalt);
if (passwordAnswer != null)
passwordAnswer = passwordAnswer.Trim();
if (!string.IsNullOrEmpty(passwordAnswer))
encodedPasswordAnswer = GetEncodedPassword(passwordAnswer.ToLower(), (int)this.passwordFormat, passwordSalt);
else
encodedPasswordAnswer = passwordAnswer;
if ((providerUserKey != null) && !(providerUserKey is Guid))
...{
status = MembershipCreateStatus.InvalidProviderUserKey;
return null;
}
if (password.Length < MinRequiredPasswordLength)
...{
status = MembershipCreateStatus.InvalidPassword;
return null;
}
int nonAlphanumericCharactersCount = 0;
for (int cnt = 0; cnt < password.Length; cnt++)
...{
if (!char.IsLetterOrDigit(password, cnt))
nonAlphanumericCharactersCount++;
}
if (nonAlphanumericCharactersCount < MinRequiredNonAlphanumericCharacters)
...{
status = MembershipCreateStatus.InvalidPassword;
return null;
}
if ((PasswordStrengthRegularExpression.Length > 0) && !Regex.IsMatch(password, PasswordStrengthRegularExpression))
...{
status = MembershipCreateStatus.InvalidPassword;
return null;
}
ValidatePasswordEventArgs args = new ValidatePasswordEventArgs(username, password, true);
this.OnValidatingPassword(args);
if (args.Cancel)
...{
status = MembershipCreateStatus.InvalidPassword;
return null;
}
SqlParameter[] parameters = new SqlParameter[13];
parameters[0] = CreateSqlParameter("@ApplicationName", SqlDbType.NVarChar, ApplicationName);
parameters[1] = CreateSqlParameter("@UserName", SqlDbType.NVarChar, username);
parameters[2] = CreateSqlParameter("@Password", SqlDbType.NVarChar, encodedPassword);
parameters[3] = CreateSqlParameter("@PasswordSalt", SqlDbType.NVarChar, passwordSalt);
parameters[4] = CreateSqlParameter("@Email", SqlDbType.NVarChar, email);
parameters[5] = CreateSqlParameter("@PasswordQuestion", SqlDbType.NVarChar, passwordQuestion);
parameters[6] = CreateSqlParameter("@PasswordAnswer", SqlDbType.NVarChar, encodedPasswordAnswer);
parameters[7] = CreateSqlParameter("@IsApproved", SqlDbType.Bit, isApproved);
parameters[8] = CreateSqlParameter("@UniqueEmail", SqlDbType.Int, RequiresUniqueEmail ? 1 : 0);
parameters[9] = CreateSqlParameter("@PasswordFormat", SqlDbType.Int, (int)PasswordFormat);
parameters[10] = CreateSqlParameter("@CurrentTimeUtc", SqlDbType.DateTime, DateTime.UtcNow);
parameters[11] = CreateSqlParameter("@CreateDate", SqlDbType.DateTime, DateTime.Now);
parameters[12] = CreateSqlParameter("@UserId", SqlDbType.UniqueIdentifier, providerUserKey);
parameters[12].Direction = ParameterDirection.Output;
if (!Update("aspnet_Membership_CreateUser", parameters))
...{
status = MembershipCreateStatus.UserRejected;
return null;
}
status = MembershipCreateStatus.Success;
providerUserKey = new Guid(parameters[12].Value.ToString());
DateTime localTime = DateTime.UtcNow.ToLocalTime();
return new MembershipUser(Name, username, providerUserKey, email, passwordQuestion, null,
isApproved, false, localTime, localTime, localTime, localTime, localTime);
}
/**//// <summary>
/// Deletes a specified user record
/// </summary>
/// <param name="username">
/// Username of the user whose record is being deleted
/// </param>
/// <param name="deleteAllRelatedData">
/// Indicates whether all related records of the user should be deleted as well
/// </param>
/// <returns></returns>
public override bool DeleteUser(string username, bool deleteAllRelatedData)
...{
SqlParameter[] parameters = new SqlParameter[4];
parameters[0] = CreateSqlParameter("@ApplicationName", SqlDbType.NVarChar, ApplicationName);
parameters[1] = CreateSqlParameter("@UserName", SqlDbType.NVarChar, username);
if (deleteAllRelatedData)
parameters[2] = CreateSqlParameter("@TablesToDeleteFrom", SqlDbType.Int, 15);
else
parameters[2] = CreateSqlParameter("@TablesToDeleteFrom", SqlDbType.Int, 1);
parameters[3] = new SqlParameter("@NumTablesDeletedFrom", SqlDbType.Int);
parameters[3].Direction = ParameterDirection.Output;
return Update("aspnet_Users_DeleteUser", parameters);
}
/**//// <summary>
/// Finds users whose email matches a specified email
/// </summary>
/// <param name="emailToMatch">
/// Email to match
/// </param>
/// <param name="pageIndex">
/// Index of the page of user records to be retrieved
/// </param>
/// <param name="pageSize">
/// Maximum number of user records to be retrieved
/// </param>
/// <param name="totalRecords">
/// Total user records
/// </param>
/// <returns>
/// Collection of MembershipUser objects where each object represents a user record
/// </returns>
public override MembershipUserCollection FindUsersByEmail(string emailToMatch, int pageIndex, int pageSize,
out int totalRecords)
...{
if (pageIndex < 0)
throw new ArgumentException("Page index cannot be negative!");
if (pageSize < 1)
throw new ArgumentException("Page size cannot be less than one!");
SqlParameter[] parameters = new SqlParameter[5];
MembershipUserCollection collection = null;
totalRecords = 0;
parameters[0] = CreateSqlParameter("@ApplicationName", SqlDbType.NVarChar, ApplicationName);
parameters[1] = CreateSqlParameter("@EmailToMatch", SqlDbType.NVarChar, emailToMatch);
parameters[2] = CreateSqlParameter("@PageIndex", SqlDbType.Int, pageIndex);
parameters[3] = CreateSqlParameter("@PageSize", SqlDbType.Int, pageSize);
parameters[4] = new SqlParameter("@ReturnValue", SqlDbType.Int);
parameters[4].Direction = ParameterDirection.ReturnValue;
SqlDataReader reader = Select("aspnet_Membership_FindUsersByEmail", parameters);
collection = new MembershipUserCollection();
while (reader.Read())
...{
string text1 = !reader.IsDBNull(0) ? reader.GetString(0) : null;
string text2 = !reader.IsDBNull(1) ? reader.GetString(1) : null;
string text3 = !reader.IsDBNull(2) ? reader.GetString(2) : null;
string text4 = !reader.IsDBNull(3) ? reader.GetString(3) : null;
bool flag1 = reader.GetBoolean(4);
DateTime time6 = reader.GetDateTime(5);
DateTime time1 = time6.ToLocalTime();
DateTime time7 = reader.GetDateTime(6);
DateTime time2 = time7.ToLocalTime();
DateTime time8 = reader.GetDateTime(7);
DateTime time3 = time8.ToLocalTime();
DateTime time9 = reader.GetDateTime(8);
DateTime time4 = time9.ToLocalTime();
Guid guid1 = reader.GetGuid(9);
bool flag2 = reader.GetBoolean(10);
DateTime time10 = reader.GetDateTime(11);
DateTime time5 = time10.ToLocalTime();
collection.Add(new MembershipUser(Name, text1, guid1, text2, text3,
text4, flag1, flag2, time1, time2, time3, time4, time5));
}
reader.Close();
if ((parameters[4].Value != null) && (parameters[4].Value is int))
totalRecords = (int)parameters[5].Value;
return collection;
}
/**//// <summary>
/// Retrieves user records whose username matches a specfied pattern
/// </summary>
/// <param name="usernameToMatch">
/// User name pattern to match
/// </param>
/// <param name="pageIndex">
/// Index of the page of user records to be retrieved
/// </param>
/// <param name="pageSize">
/// Maximum number of user records to be retrieved
/// </param>
/// <param name="totalRecords"></param>
/// <returns>
/// Collection of MembershipUser objects where each object represets a user record
/// </returns>
public override MembershipUserCollection FindUsersByName(string usernameToMatch, int pageIndex,
int pageSize, out int totalRecords)
...{
if (pageIndex < 0)
throw new ArgumentException("Page index cannot be negative!");
if (pageSize < 1)
throw new ArgumentException("Page size cannot be less than one!");
SqlParameter[] parameters = new SqlParameter[5];
MembershipUserCollection collection = null;
totalRecords = 0;
parameters[0] = CreateSqlParameter("@ApplicationName", SqlDbType.NVarChar, ApplicationName);
parameters[1] = CreateSqlParameter("@UserNameToMatch", SqlDbType.NVarChar, usernameToMatch);
parameters[2] = CreateSqlParameter("@PageIndex", SqlDbType.Int, pageIndex);
parameters[3] = CreateSqlParameter("@PageSize", SqlDbType.Int, pageSize);
parameters[4] = new SqlParameter("@ReturnValue", SqlDbType.Int);
parameters[4].Direction = ParameterDirection.ReturnValue;
SqlDataReader reader = Select("aspnet_Membership_FindUsersByName", parameters);
collection = new MembershipUserCollection();
while (reader.Read())
...{
string text1 = !reader.IsDBNull(0) ? reader.GetString(0) : null;
string text2 = !reader.IsDBNull(1) ? reader.GetString(1) : null;
string text3 = !reader.IsDBNull(2) ? reader.GetString(2) : null;
string text4 = !reader.IsDBNull(3) ? reader.GetString(3) : null;
bool flag1 = reader.GetBoolean(4);
DateTime time6 = reader.GetDateTime(5);
DateTime time1 = time6.ToLocalTime();
DateTime time7 = reader.GetDateTime(6);
DateTime time2 = time7.ToLocalTime();
DateTime time8 = reader.GetDateTime(7);
DateTime time3 = time8.ToLocalTime();
DateTime time9 = reader.GetDateTime(8);
DateTime time4 = time9.ToLocalTime();
Guid guid1 = reader.GetGuid(9);
bool flag2 = reader.GetBoolean(10);
DateTime time10 = reader.GetDateTime(11);
DateTime time5 = time10.ToLocalTime();
collection.Add(new MembershipUser(Name, text1, guid1, text2, text3, text4,
flag1, flag2, time1, time2, time3, time4, time5));
}
reader.Close();
if ((parameters[4].Value != null) && (parameters[4].Value is int))
totalRecords = (int)parameters[4].Value;
return collection;
}
/**//// <summary>
/// Retrieves all users of a specified application
/// </summary>
/// <param name="pageIndex">
/// Index of the page of user records to be retrieved
/// </param>
/// <param name="pageSize">
/// Maximum number of user records to be retrieved
/// </param>
/// <param name="totalRecords"></param>
/// <returns>
/// Collection of MembershipUser objects where each object represents a user
/// </returns>
public override MembershipUserCollection GetAllUsers(int pageIndex, int pageSize, out int totalRecords)
...{
if (pageIndex < 0)
throw new ArgumentException("Page index cannot be negative!");
if (pageSize < 1)
throw new ArgumentException("Page size cannot be less than one!");
SqlParameter[] parameters = new SqlParameter[4];
MembershipUserCollection collection = null;
totalRecords = 0;
parameters[0] = CreateSqlParameter("@ApplicationName", SqlDbType.NVarChar, ApplicationName);
parameters[1] = CreateSqlParameter("@PageIndex", SqlDbType.Int, pageIndex);
parameters[2] = CreateSqlParameter("@PageSize", SqlDbType.Int, pageSize);
parameters[3] = new SqlParameter("@ReturnValue", SqlDbType.Int);
parameters[3].Direction = ParameterDirection.ReturnValue;
SqlDataReader reader = Select("aspnet_Membership_GetAllUsers", parameters);
collection = new MembershipUserCollection();
while (reader.Read())
...{
string text1 = !reader.IsDBNull(0) ? reader.GetString(0) : null;
string text2 = !reader.IsDBNull(1) ? reader.GetString(1) : null;
string text3 = !reader.IsDBNull(2) ? reader.GetString(2) : null;
string text4 = !reader.IsDBNull(3) ? reader.GetString(3) : null;
bool flag1 = reader.GetBoolean(4);
DateTime time6 = reader.GetDateTime(5);
DateTime time1 = time6.ToLocalTime();
DateTime time7 = reader.GetDateTime(6);
DateTime time2 = time7.ToLocalTime();
DateTime time8 = reader.GetDateTime(7);
DateTime time3 = time8.ToLocalTime();
DateTime time9 = reader.GetDateTime(8);
DateTime time4 = time9.ToLocalTime();
Guid guid1 = reader.GetGuid(9);
bool flag2 = reader.GetBoolean(10);
DateTime time10 = reader.GetDateTime(11);
DateTime time5 = time10.ToLocalTime();
collection.Add(new MembershipUser(this.Name, text1, guid1, text2, text3, text4, flag1, flag2, time1, time2, time3, time4, time5));
}
reader.Close();
if ((parameters[3].Value != null) && (parameters[3].Value is int))
totalRecords = (int)parameters[3].Value;
return collection;
}
/**//// <summary>
/// Retrieves the number of users online
/// </summary>
/// <returns></returns>
public override int GetNumberOfUsersOnline()
...{
SqlParameter[] parameters = new SqlParameter[4];
parameters[0] = CreateSqlParameter("@ApplicationName", SqlDbType.NVarChar, ApplicationName);
parameters[1] = CreateSqlParameter("@MinutesSinceLastInActive", SqlDbType.Int, Membership.UserIsOnlineTimeWindow);
parameters[2] = CreateSqlParameter("@CurrentTimeUtc", SqlDbType.DateTime, DateTime.UtcNow);
parameters[3] = new SqlParameter("@ReturnValue", SqlDbType.Int);
parameters[3].Direction = ParameterDirection.ReturnValue;
Select("aspnet_Membership_GetNumberOfUsersOnline", parameters);
return ((parameters[3].Value != null) ? ((int)parameters[3].Value) : -1);
}
/**//// <summary>
/// Retrieves the password of a specfied user
/// </summary>
/// <param name="username">
/// Username of the user whose password is being retrieved
/// </param>
/// <param name="passwordAnswer">
/// Password answer of the user
/// </param>
/// <returns>
/// String value that contains the user's password
/// </returns>
public override string GetPassword(string username, string passwordAnswer)
...{
if (!EnablePasswordRetrieval)
throw new NotSupportedException("Password cannot be retrieved!");
if (string.IsNullOrEmpty(passwordAnswer))
return passwordAnswer;
int format = 0;
string salt = null;
SqlParameter[] parameters;
SqlDataReader reader;
string encodedPasswordAnswer = null;
if (RequiresQuestionAndAnswer)
...{
parameters = new SqlParameter[4];
parameters[0] = CreateSqlParameter("@ApplicationName", SqlDbType.NVarChar, this.ApplicationName);
parameters[1] = CreateSqlParameter("@UserName", SqlDbType.NVarChar, username);
parameters[2] = CreateSqlParameter("@UpdateLastLoginActivityDate", SqlDbType.Bit, false);
parameters[3] = CreateSqlParameter("@CurrentTimeUtc", SqlDbType.DateTime, DateTime.UtcNow);
reader = Select("aspnet_Membership_GetPasswordWithFormat", parameters);
if (reader.Read())
...{
format = reader.GetInt32(1);
salt = reader.GetString(2);
}
reader.Close();
encodedPasswordAnswer = GetEncodedPassword(passwordAnswer.ToLower(), format, salt);
}
if (RequiresQuestionAndAnswer)
parameters = new SqlParameter[6];
else
parameters = new SqlParameter[5];
parameters[0] = CreateSqlParameter("@ApplicationName", SqlDbType.NVarChar, ApplicationName);
parameters[1] = CreateSqlParameter("@UserName", SqlDbType.NVarChar, username);
parameters[2] = CreateSqlParameter("@MaxInvalidPasswordAttempts", SqlDbType.Int, MaxInvalidPasswordAttempts);
parameters[3] = CreateSqlParameter("@PasswordAttemptWindow", SqlDbType.Int, PasswordAttemptWindow);
parameters[4] = CreateSqlParameter("@CurrentTimeUtc", SqlDbType.DateTime, DateTime.UtcNow);
if (requiresQuestionAndAnswer)
parameters[5] = CreateSqlParameter("@PasswordAnswer", SqlDbType.NVarChar, encodedPasswordAnswer);
reader = Select("aspnet_Membership_GetPassword", parameters);
string password = null;
if (reader.Read())
...{
password = reader.GetString(0);
format = reader.GetInt32(1);
}
reader.Close();
if (password != null && format == 2)
...{
byte[] decodedPassword = Convert.FromBase64String(password);
byte[] decryptedPassword = this.DecryptPassword(decodedPassword);
if (decryptedPassword == null)
password = null;
else
password = Encoding.Unicode.GetString(decryptedPassword);
//password = Encoding.Unicode.GetString(decryptedPassword, 0x10, decryptedPassword.Length - 0x10);
}
return password;
}
/**//// <summary>
/// Retrieves the user record of a specified user
/// </summary>
/// <param name="providerUserKey">
/// Key that uniquely identifies the user record
/// </param>
/// <param name="userIsOnline">
/// Indicates whether the user is online
/// </param>
/// <returns>
/// MembershipUser that represents the user record
/// </returns>
public override MembershipUser GetUser(object providerUserKey, bool userIsOnline)
...{
MembershipUser user = null;
if (providerUserKey == null)
throw new ArgumentNullException("providerUserKey cannot be null!");
if (!(providerUserKey is Guid))
throw new ArgumentException("providerUserKey is not of type Guid!");
SqlParameter[] parameters = new SqlParameter[3];
parameters[0] = CreateSqlParameter("@UserId", SqlDbType.UniqueIdentifier, providerUserKey);
parameters[1] = CreateSqlParameter("@UpdateLastActivity", SqlDbType.Bit, userIsOnline);
parameters[2] = CreateSqlParameter("@CurrentTimeUtc", SqlDbType.DateTime, DateTime.UtcNow);
SqlDataReader reader = Select("aspnet_Membership_GetUserByUserId", parameters);
if (reader.Read())
...{
string text1 = !reader.IsDBNull(0) ? reader.GetString(0) : null;
string text2 = !reader.IsDBNull(1) ? reader.GetString(1) : null;
string text3 = !reader.IsDBNull(2) ? reader.GetString(2) : null;
bool flag1 = reader.GetBoolean(3);
DateTime time6 = reader.GetDateTime(4);
DateTime time1 = time6.ToLocalTime();
DateTime time7 = reader.GetDateTime(5);
DateTime time2 = time7.ToLocalTime();
DateTime time8 = reader.GetDateTime(6);
DateTime time3 = time8.ToLocalTime();
DateTime time9 = reader.GetDateTime(7);
DateTime time4 = time9.ToLocalTime();
string text4 = !reader.IsDBNull(8) ? reader.GetString(8) : null;
bool flag2 = reader.GetBoolean(9);
DateTime time10 = reader.GetDateTime(10);
DateTime time5 = time10.ToLocalTime();
user = new MembershipUser(this.Name, text4, providerUserKey, text1, text2, text3, flag1, flag2, time1, time2, time3, time4, time5);
}
reader.Close();
return user;
}
/**//// <summary>
/// Retrieves the user record of the user with a specified username
/// </summary>
/// <param name="username">
/// Username of the user whose record is being retrieved
/// </param>
/// <param name="userIsOnline">
/// Indicates whether the user is currently online
/// </param>
/// <returns>
/// MembershipUser that represents the retrieved user record
/// </returns>
public override MembershipUser GetUser(string username, bool userIsOnline)
...{
MembershipUser user = null;
SqlParameter[] parameters = new SqlParameter[4];
parameters[0] = CreateSqlParameter("@ApplicationName", SqlDbType.NVarChar, ApplicationName);
parameters[1] = CreateSqlParameter("@UserName", SqlDbType.NVarChar, username);
parameters[2] = CreateSqlParameter("@UpdateLastActivity", SqlDbType.Bit, userIsOnline);
parameters[3] = CreateSqlParameter("@CurrentTimeUtc", SqlDbType.DateTime, DateTime.UtcNow);
SqlDataReader reader = Select("aspnet_Membership_GetUserByName", parameters);
if (reader.Read())
...{
string text1 = !reader.IsDBNull(0) ? reader.GetString(0) : null;
string text2 = !reader.IsDBNull(1) ? reader.GetString(1) : null;
string text3 = !reader.IsDBNull(2) ? reader.GetString(2) : null;
bool flag1 = reader.GetBoolean(3);
DateTime time6 = reader.GetDateTime(4);
DateTime time1 = time6.ToLocalTime();
DateTime time7 = reader.GetDateTime(5);
DateTime time2 = time7.ToLocalTime();
DateTime time8 = reader.GetDateTime(6);
DateTime time3 = time8.ToLocalTime();
DateTime time9 = reader.GetDateTime(7);
DateTime time4 = time9.ToLocalTime();
Guid guid1 = reader.GetGuid(8);
bool flag2 = reader.GetBoolean(9);
DateTime time10 = reader.GetDateTime(10);
DateTime time5 = time10.ToLocalTime();
user = new MembershipUser(Name, username, guid1, text1, text2, text3, flag1, flag2,
time1, time2, time3, time4, time5);
}
reader.Close();
return user;
}
/**//// <summary>
/// Retrieves the username of a user with the specified email
/// </summary>
/// <param name="email">
/// Email of the user record being retrieved
/// </param>
/// <returns>
/// String value that contains the username
/// </returns>
public override string GetUserNameByEmail(string email)
...{
SqlParameter[] parameters = new SqlParameter[2];
parameters[0] = CreateSqlParameter("@ApplicationName", SqlDbType.NVarChar, ApplicationName);
parameters[1] = CreateSqlParameter("@Email", SqlDbType.NVarChar, email);
SqlDataReader reader = Select("aspnet_Membership_GetUserByEmail", parameters);
string text = null;
if (reader.Read())
text = !reader.IsDBNull(0) ? reader.GetString(0) : null;
reader.Close();
return text;
}
/**//// <summary>
/// Initializes the SqlMembershipProvider
/// </summary>
/// <param name="name">
/// Friendly name of the provider
/// </param>
/// <param name="config">
/// NameValueCollection that contains the values used to initialize the
/// provider's properties and fields
/// </param>
public override void Initialize(string name, NameValueCollection config)
...{
if (config == null)
throw new ArgumentNullException("config");
if (string.IsNullOrEmpty(name))
name = "SqlMembershipProvider";
if (string.IsNullOrEmpty(config["description"]))
...{
config.Remove("description");
config.Add("description", "Stores membership information in SQL Server database");
}
base.Initialize(name, config);
enablePasswordRetrieval = (config["enablePasswordRetrieval"] != null) ? bool.Parse(config["enablePasswordRetrieval"]) : false;
config.Remove("enablePasswordRetrieval");
enablePasswordReset = (config["enablePasswordReset"] != null) ? bool.Parse(config["enablePasswordReset"]) : true;
config.Remove("enablePasswordReset");
requiresQuestionAndAnswer = (config["requiresQuestionAndAnswer"] != null) ? bool.Parse(config["requiresQuestionAndAnswer"]) : true;
config.Remove("requiresQuestionAndAnswer");
requiresUniqueEmail = (config["requiresUniqueEmail"] != null) ? bool.Parse(config["requiresUniqueEmail"]) : true;
config.Remove("requiresUniqueEmail");
maxInvalidPasswordAttempts = config["passwordAttemptWindow"] != null ? int.Parse(config["passwordAttemptWindow"]) : 5;
config.Remove("maxInvalidPasswordAttempts");
passwordAttemptWindow = config["passwordAttemptWindow"] != null ? int.Parse(config["passwordAttemptWindow"]) : 10;
config.Remove("passwordAttemptWindow");
minRequiredPasswordLength = config["minRequiredPasswordLength"] != null ? int.Parse(config["minRequiredPasswordLength"]) : 7;
config.Remove("minRequiredPasswordLength");
minRequiredNonAlphanumericCharacters = config["minRequiredNonalphanumericCharacters"] != null ? int.Parse(config["minRequiredNonalphanumericCharacters"]) : 1;
config.Remove("minRequiredNonalphanumericCharacters");
passwordStrengthRegularExpression = config["passwordStrengthRegularExpression"];
config.Remove("passwordStrengthRegularExpression");
if (minRequiredNonAlphanumericCharacters > minRequiredPasswordLength)
throw new HttpException();
applicationName = config["applicationName"];
if (string.IsNullOrEmpty(applicationName))
applicationName = "/";
config.Remove("applicationName");
string strTemp = config["passwordFormat"];
if (string.IsNullOrEmpty(strTemp))
strTemp = "Hashed";
switch (strTemp)
...{
case "Clear":
passwordFormat = MembershipPasswordFormat.Clear;
break;
case "Encrypted":
passwordFormat = MembershipPasswordFormat.Encrypted;
break;
case "Hashed":
passwordFormat = MembershipPasswordFormat.Hashed;
break;
default:
throw new ProviderException("Bad password format");
}
if ((PasswordFormat == MembershipPasswordFormat.Hashed) && EnablePasswordRetrieval)
throw new ProviderException();
config.Remove("passwordFormat");
ConnectionStringSettings settings = ConfigurationManager.ConnectionStrings[config["connectionStringName"]];
connectionString = settings.ConnectionString;
if (string.IsNullOrEmpty(connectionString))
throw new ProviderException("Invalid connection string name");
config.Remove("connectionStringName");
if (config.Count > 0)
...{
string key = config.GetKey(0);
if (!string.IsNullOrEmpty(key))
throw new ProviderException("Unrecognized attribute");
}
}
/**//// <summary>
/// Resets the password of the user with the specified username and password answer
/// </summary>
/// <param name="username">
/// Username of the user whose password is being reset
/// </param>
/// <param name="passwordAnswer">
/// Password answer of the user whose password is being reset
/// </param>
/// <returns>
/// New password of the user
/// </returns>
public override string ResetPassword(string username, string passwordAnswer)
...{
if (!this.EnablePasswordReset)
throw new NotSupportedException();
int format = 0;
string salt = null;
SqlParameter[] parameters;
SqlDataReader reader;
string encodedPasswordAnswer = null;
parameters = new SqlParameter[4];
parameters[0] = CreateSqlParameter("@ApplicationName", SqlDbType.NVarChar, this.ApplicationName);
parameters[1] = CreateSqlParameter("@UserName", SqlDbType.NVarChar, username);
parameters[2] = CreateSqlParameter("@UpdateLastLoginActivityDate", SqlDbType.Bit, false);
parameters[3] = CreateSqlParameter("@CurrentTimeUtc", SqlDbType.DateTime, DateTime.UtcNow);
reader = Select("aspnet_Membership_GetPasswordWithFormat", parameters);
if (reader.Read())
...{
format = reader.GetInt32(1);
salt = reader.GetString(2);
}
reader.Close();
if (!string.IsNullOrEmpty(passwordAnswer))
encodedPasswordAnswer = GetEncodedPassword(passwordAnswer.ToLower(), format, salt);
else
encodedPasswordAnswer = passwordAnswer;
string generatedPassword = Membership.GeneratePassword((MinRequiredPasswordLength < 14) ? 14 : MinRequiredPasswordLength, MinRequiredNonAlphanumericCharacters);
ValidatePasswordEventArgs args = new ValidatePasswordEventArgs(username, generatedPassword, false);
this.OnValidatingPassword(args);
if (args.Cancel)
...{
if (args.FailureInformation != null)
throw args.FailureInformation;
//throw new ProviderException();
}
if (this.RequiresQuestionAndAnswer)
parameters = new SqlParameter[9];
else
parameters = new SqlParameter[8];
parameters[0] = CreateSqlParameter("@ApplicationName", SqlDbType.NVarChar, ApplicationName);
parameters[1] = CreateSqlParameter("@UserName", SqlDbType.NVarChar, username);
parameters[2] = CreateSqlParameter("@NewPassword", SqlDbType.NVarChar, GetEncodedPassword(generatedPassword, format, salt));
parameters[3] = CreateSqlParameter("@MaxInvalidPasswordAttempts", SqlDbType.Int, MaxInvalidPasswordAttempts);
parameters[4] = CreateSqlParameter("@PasswordAttemptWindow", SqlDbType.Int, PasswordAttemptWindow);
parameters[5] = CreateSqlParameter("@PasswordSalt", SqlDbType.NVarChar, salt);
parameters[6] = CreateSqlParameter("@PasswordFormat", SqlDbType.Int, format);
parameters[7] = CreateSqlParameter("@CurrentTimeUtc", SqlDbType.DateTime, DateTime.UtcNow);
if (this.RequiresQuestionAndAnswer)
parameters[8] = CreateSqlParameter("@PasswordAnswer", SqlDbType.NVarChar, encodedPasswordAnswer);
Update("aspnet_Membership_ResetPassword", parameters);
return generatedPassword;
}
/**//// <summary>
/// Unlocks the user with a specified username
/// </summary>
/// <param name="username">
/// Username of the user being unlocked
/// </param>
/// <returns></returns>
public override bool UnlockUser(string username)
...{
SqlParameter[] parameters = new SqlParameter[2];
parameters[0] = CreateSqlParameter("@ApplicationName", SqlDbType.NVarChar, ApplicationName);
parameters[1] = CreateSqlParameter("@UserName", SqlDbType.NVarChar, username);
return Update("aspnet_Membership_UnlockUser", parameters);
}
/**//// <summary>
/// Updates the record of the user with a specfied MembershipUser
/// </summary>
/// <param name="user">
/// MembershipUser object that contains the new information about the user
/// </param>
public override void UpdateUser(MembershipUser user)
...{
if (user == null)
throw new ArgumentNullException();
SqlParameter[] parameters = new SqlParameter[9];
parameters[0] = CreateSqlParameter("@ApplicationName", SqlDbType.NVarChar, ApplicationName);
parameters[1] = CreateSqlParameter("@UserName", SqlDbType.NVarChar, user.UserName);
parameters[2] = CreateSqlParameter("@Email", SqlDbType.NVarChar, user.Email);
parameters[3] = CreateSqlParameter("@Comment", SqlDbType.NText, user.Comment);
parameters[4] = CreateSqlParameter("@IsApproved", SqlDbType.Bit, user.IsApproved ? 1 : 0);
parameters[5] = CreateSqlParameter("@LastLoginDate", SqlDbType.DateTime, user.LastLoginDate.ToUniversalTime());
parameters[6] = CreateSqlParameter("@LastActivityDate", SqlDbType.DateTime, user.LastActivityDate.ToUniversalTime());
parameters[7] = CreateSqlParameter("@UniqueEmail", SqlDbType.Int, this.RequiresUniqueEmail ? 1 : 0);
parameters[8] = CreateSqlParameter("@CurrentTimeUtc", SqlDbType.DateTime, DateTime.UtcNow);
Update("aspnet_Membership_UpdateUser", parameters);
}
/**//// <summary>
/// Validates user credentials against the database
/// </summary>
/// <param name="username">
/// Username of the user being validated
/// </param>
/// <param name="password">
/// Password of the user being validated
/// </param>
/// <returns></returns>
public override bool ValidateUser(string username, string password)
...{
return ValidateUserInfo(username, password, true, true);
}
#endregion
}
}