internal static void CheckArrayParameter(ref string[] param, bool checkForNull, bool checkIfEmpty, bool checkForCommas, int maxSize, string paramName) { if (param == null) { throw new ArgumentNullException(paramName); } if (param.Length < 1) { throw new ArgumentException("The array parameter '" + paramName + "' should not be empty.", paramName); } for (int i = param.Length - 1; i >= 0; i--) { SecUtility.CheckParameter(ref param[i], checkForNull, checkIfEmpty, checkForCommas, maxSize, paramName + "[ " + i.ToString(CultureInfo.InvariantCulture) + " ]"); } for (int i = param.Length - 1; i >= 0; i--) { for (int j = i - 1; j >= 0; j--) { if (param[i].Equals(param[j])) { throw new ArgumentException("The array '" + paramName + "' should not contain duplicate values.", paramName); } } } }
public override string[] GetUsersInRole(string roleName) { SecUtility.CheckParameter(ref roleName, true, true, true, 255, "roleName"); StringCollection sc = new StringCollection(); String[] strReturn; AccessConnectionHolder holder = MyConnectionHelper.GetConnection(_DatabaseFileName, true); SqlDataReader reader = null; SqlConnection connection = holder.Connection; try { try { int appId = GetApplicationId(holder); int roleId = GetRoleId(connection, appId, roleName); SqlCommand command; if (roleId == 0) { throw new ProviderException("Role not found: " + roleName); } command = new SqlCommand(@"SELECT UserName " + @"FROM UsersInRoles ur, Users u " + @"WHERE ur.RoleId = @RoleId AND ur.UserId = u.UserId " + @"ORDER BY UserName", connection); command.Parameters.Add(new SqlParameter("@RoleId", roleId)); reader = command.ExecuteReader(CommandBehavior.SequentialAccess); while (reader.Read()) { sc.Add(reader.GetString(0)); } } catch (Exception e) { throw MyConnectionHelper.GetBetterException(e, holder); } finally { if (reader != null) { reader.Close(); } holder.Close(); } } catch { throw; } strReturn = new String[sc.Count]; sc.CopyTo(strReturn, 0); return(strReturn); }
public override bool IsUserInRole(string username, string roleName) { SecUtility.CheckParameter(ref username, true, false, true, 255, "username"); if (username.Length < 1) { return(false); } SecUtility.CheckParameter(ref roleName, true, true, true, 255, "roleName"); AccessConnectionHolder holder = MyConnectionHelper.GetConnection(_DatabaseFileName, true); SqlConnection connection = holder.Connection; try { try { int appId = GetApplicationId(holder); int userId = MyConnectionHelper.GetUserID(connection, appId, username, false); int roleId = GetRoleId(connection, appId, roleName); SqlCommand command; if (userId == 0) { return(false); } if (roleId == 0) { return(false); } command = new SqlCommand(@"SELECT UserId FROM UsersInRoles WHERE UserId = @UserId AND RoleId = @RoleId", connection); command.Parameters.Add(new SqlParameter("@UserId", userId)); command.Parameters.Add(new SqlParameter("@RoleId", roleId)); object result = command.ExecuteScalar(); if (result == null || !(result is int) || ((int)result) != userId) { return(false); } return(true); } catch (Exception e) { throw MyConnectionHelper.GetBetterException(e, holder); } finally { holder.Close(); } } catch { throw; } }
public override void Initialize(string name, NameValueCollection config) { if (config == null) { throw new ArgumentNullException("config"); } if (String.IsNullOrEmpty(name)) { name = "AccessRoleProvider"; } if (string.IsNullOrEmpty(config["description"])) { config.Remove("description"); config.Add("description", "$safeprojectname$ Role Provider"); } base.Initialize(name, config); _DatabaseFileName = config["connectionStringName"]; if (_DatabaseFileName == null || _DatabaseFileName.Length < 1) { throw new ProviderException("Connection name not specified"); } string temp = MyConnectionHelper.GetFileNameFromConnectionName(_DatabaseFileName, true); if (temp == null || temp.Length < 1) { throw new ProviderException("Connection string not found: " + _DatabaseFileName); } _DatabaseFileName = temp; //HandlerBase.CheckAndReadRegistryValue(ref _DatabaseFileName, true); MyConnectionHelper.CheckConnectionString(_DatabaseFileName); _AppName = config["applicationName"]; if (string.IsNullOrEmpty(_AppName)) { _AppName = SecUtility.GetDefaultAppName(); } if (_AppName.Length > 255) { throw new ProviderException("Provider application name too long, max is 255."); } config.Remove("connectionStringName"); config.Remove("applicationName"); config.Remove("description"); if (config.Count > 0) { string attribUnrecognized = config.GetKey(0); if (!String.IsNullOrEmpty(attribUnrecognized)) { throw new ProviderException("Provider unrecognized attribute: " + attribUnrecognized); } } }
public override bool ValidateUser(string username, string password) { if (!SecUtility.ValidateParameter(ref username, true, true, false, 255)) { return(false); } if (!SecUtility.ValidateParameter(ref password, true, true, false, 128)) { return(false); } AccessConnectionHolder holder = MyConnectionHelper.GetConnection(_databaseFileName, true); SqlConnection connection = holder.Connection; try { try { int appId = GetAppplicationId(holder); int userId = MyConnectionHelper.GetUserID(connection, appId, username, false); if (CheckPassword(connection, userId, password)) { return(true); } else { return(false); } } catch (Exception e) { throw MyConnectionHelper.GetBetterException(e, holder); } finally { holder.Close(); } } catch { throw; } }
public override bool RoleExists(string roleName) { try { SecUtility.CheckParameter(ref roleName, true, true, true, 255, "roleName"); } catch { return(false); } AccessConnectionHolder holder = MyConnectionHelper.GetConnection(_DatabaseFileName, true); SqlConnection connection = holder.Connection; try { try { int appId = GetApplicationId(holder); int roleId = GetRoleId(connection, appId, roleName); return(roleId != 0); } catch (Exception e) { throw MyConnectionHelper.GetBetterException(e, holder); } finally { holder.Close(); } } catch { throw; } }
public override void CreateRole(string roleName) { SecUtility.CheckParameter(ref roleName, true, true, true, 255, "roleName"); AccessConnectionHolder holder = MyConnectionHelper.GetConnection(_DatabaseFileName, true); SqlConnection connection = holder.Connection; try { try { int appId = GetApplicationId(holder); SqlCommand command; command = new SqlCommand(@"INSERT INTO Roles (RoleName) VALUES (@RName)", connection); command.Parameters.Add(new SqlParameter("@RName", roleName)); int returnValue = command.ExecuteNonQuery(); if (returnValue == 1) { return; } throw new ProviderException("Unknown provider failure"); } catch (Exception e) { throw MyConnectionHelper.GetBetterException(e, holder); } finally { holder.Close(); } } catch { throw; } }
public override void AddUsersToRoles(string[] usernames, string[] roleNames) { SecUtility.CheckArrayParameter(ref roleNames, true, true, true, 255, "roleNames"); SecUtility.CheckArrayParameter(ref usernames, true, true, true, 255, "usernames"); AccessConnectionHolder holder = MyConnectionHelper.GetConnection(_DatabaseFileName, true); SqlConnection connection = holder.Connection; bool fBeginTransCalled = false; try { try { int appId = GetApplicationId(holder); int[] userIds = new int[usernames.Length]; int[] roleIds = new int[roleNames.Length]; SqlCommand command; for (int iterR = 0; iterR < roleNames.Length; iterR++) { roleIds[iterR] = GetRoleId(connection, appId, roleNames[iterR]); if (roleIds[iterR] == 0) { throw new ProviderException("Provider role not found: " + roleNames[iterR]); } } for (int iterU = 0; iterU < usernames.Length; iterU++) { userIds[iterU] = MyConnectionHelper.GetUserID(connection, appId, usernames[iterU], false); } command = new SqlCommand("BEGIN TRANSACTION", connection); command.ExecuteNonQuery(); fBeginTransCalled = true; for (int iterU = 0; iterU < usernames.Length; iterU++) { if (userIds[iterU] == 0) { continue; } for (int iterR = 0; iterR < roleNames.Length; iterR++) { command = new SqlCommand(@"SELECT UserId FROM UsersInRoles WHERE UserId = @UserId AND RoleId = @RoleId", connection); command.Parameters.Add(new SqlParameter("@UserId", userIds[iterU])); command.Parameters.Add(new SqlParameter("@RoleId", roleIds[iterR])); object result = command.ExecuteScalar(); if (result != null && (result is int) && ((int)result) == userIds[iterU]) { // Exists! throw new ProviderException("The user " + usernames[iterU] + " is already in role " + roleNames[iterR]); } } } for (int iterU = 0; iterU < usernames.Length; iterU++) { if (userIds[iterU] == 0) { userIds[iterU] = MyConnectionHelper.GetUserID(connection, appId, usernames[iterU], true); } if (userIds[iterU] == 0) { throw new ProviderException("User not found: " + usernames[iterU]); } } for (int iterU = 0; iterU < usernames.Length; iterU++) { for (int iterR = 0; iterR < roleNames.Length; iterR++) { command = new SqlCommand(@"INSERT INTO UsersInRoles (UserId, RoleId) VALUES(@UserId, @RoleId)", connection); command.Parameters.Add(new SqlParameter("@UserId", userIds[iterU])); command.Parameters.Add(new SqlParameter("@RoleId", roleIds[iterR])); if (command.ExecuteNonQuery() != 1) { throw new ProviderException("Unknown provider failure"); } } } command = new SqlCommand("COMMIT TRANSACTION", connection); command.ExecuteNonQuery(); } catch (Exception e) { try { if (fBeginTransCalled) { SqlCommand command = new SqlCommand("ROLLBACK TRANSACTION", connection); command.ExecuteNonQuery(); } } catch { } throw MyConnectionHelper.GetBetterException(e, holder); } finally { holder.Close(); } } catch { throw; } }
public override string[] GetRolesForUser(string username) { SecUtility.CheckParameter(ref username, true, false, true, 255, "username"); if (username.Length < 1) { return(new string[0]); } AccessConnectionHolder holder = MyConnectionHelper.GetConnection(_DatabaseFileName, true); SqlConnection connection = holder.Connection; SqlDataReader reader = null; try { try { int appId = GetApplicationId(holder); int userId = MyConnectionHelper.GetUserID(connection, appId, username, false); if (userId == 0) { return(new string[0]); } SqlCommand command; StringCollection sc = new StringCollection(); String[] strReturn; command = new SqlCommand(@"SELECT RoleName FROM UsersInRoles ur, Roles r " + @"WHERE ur.UserId = @UserId AND ur.RoleId = r.RoleId " + @"ORDER BY RoleName", connection); command.Parameters.Add(new SqlParameter("@UserId", userId)); reader = command.ExecuteReader(CommandBehavior.SequentialAccess); while (reader.Read()) { sc.Add(reader.GetString(0)); } strReturn = new String[sc.Count]; sc.CopyTo(strReturn, 0); return(strReturn); } catch (Exception e) { throw MyConnectionHelper.GetBetterException(e, holder); } finally { if (reader != null) { reader.Close(); } holder.Close(); } } catch { throw; } }
public override bool DeleteRole(string roleName, bool throwOnPopulatedRole) { SecUtility.CheckParameter(ref roleName, true, true, true, 255, "roleName"); AccessConnectionHolder holder = MyConnectionHelper.GetConnection(_DatabaseFileName, true); SqlConnection connection = holder.Connection; bool fBeginTransCalled = false; try { try { int appId = GetApplicationId(holder); SqlCommand command; int roleId = GetRoleId(connection, appId, roleName); if (roleId == 0) { return(false); } if (throwOnPopulatedRole) { command = new SqlCommand(@"SELECT COUNT(*) " + @"FROM UsersInRoles ur, Users u " + @"WHERE ur.RoleId = @RoleId AND ur.UserId = u.UserId", connection); command.Parameters.Add(new SqlParameter("@RoleId", roleId)); object num = command.ExecuteScalar(); if (!(num is int) || ((int)num) != 0) { throw new ProviderException("Role is not empty"); } } command = new SqlCommand("BEGIN TRANSACTION", connection); command.ExecuteNonQuery(); fBeginTransCalled = true; command = new SqlCommand(@"DELETE FROM Roles WHERE RoleId = @RoleId", connection); command.Parameters.Add(new SqlParameter("@RoleId", roleId)); int returnValue = command.ExecuteNonQuery(); command = new SqlCommand("COMMIT TRANSACTION", connection); command.ExecuteNonQuery(); fBeginTransCalled = false; return(returnValue == 1); } catch (Exception e) { if (fBeginTransCalled) { try { SqlCommand command = new SqlCommand("ROLLBACK TRANSACTION", connection); command.ExecuteNonQuery(); } catch { } } throw MyConnectionHelper.GetBetterException(e, holder); } finally { holder.Close(); } } catch { throw; } }
public override bool DeleteUser(string username, bool deleteAllRelatedData) { SecUtility.CheckParameter(ref username, true, true, true, 255, "username"); AccessConnectionHolder holder = MyConnectionHelper.GetConnection(_databaseFileName, true); SqlConnection connection = holder.Connection; bool fBeginTransCalled = false; try { try { int appId = GetAppplicationId(holder); int userId = MyConnectionHelper.GetUserID(connection, appId, username, false); if (userId == 0) { return(false); // User not found } SqlCommand command; // // Start transaction // command = new SqlCommand("BEGIN TRANSACTION", connection); command.ExecuteNonQuery(); fBeginTransCalled = true; bool returnValue = false; if (deleteAllRelatedData) { command = new SqlCommand(@"DELETE FROM UsersInRoles WHERE UserId = @UserId", connection); command.Parameters.Add(new SqlParameter("@UserId", userId)); command.ExecuteNonQuery(); command = new SqlCommand(@"DELETE FROM Users WHERE UserId = @UserId", connection); command.Parameters.Add(new SqlParameter("@UserId", userId)); returnValue = (command.ExecuteNonQuery() == 1); } // // End transaction // command = new SqlCommand("COMMIT TRANSACTION", connection); command.ExecuteNonQuery(); fBeginTransCalled = false; return(returnValue); } catch (Exception e) { throw MyConnectionHelper.GetBetterException(e, holder); } finally { if (fBeginTransCalled) { try { SqlCommand cmd = new SqlCommand("ROLLBACK TRANSACTION", connection); cmd.ExecuteNonQuery(); } catch { } } holder.Close(); } } catch { throw; } }
public override MembershipUser CreateUser(string username, string password, string email, string passwordQuestion, string passwordAnswer, bool isApproved, object providerUserKey, out MembershipCreateStatus status) { if (!SecUtility.ValidateParameter(ref password, true, true, false, 0)) { status = MembershipCreateStatus.InvalidPassword; return(null); } string salt = GenerateSalt(); string pass = EncodePassword(password, (int)_passwordFormat, salt); if (pass.Length > 128) { status = MembershipCreateStatus.InvalidPassword; return(null); } if (!SecUtility.ValidateParameter(ref username, true, true, true, 255)) { status = MembershipCreateStatus.InvalidUserName; return(null); } AccessConnectionHolder holder = MyConnectionHelper.GetConnection(_databaseFileName, true); SqlConnection connection = holder.Connection; try { try { // // Start transaction // SqlCommand command = new SqlCommand(); int appId = GetAppplicationId(holder); object result; int uid; //////////////////////////////////////////////////////////// // Step 1: Check if the user exists in the Users table: create if not uid = MyConnectionHelper.GetUserID(connection, appId, username, false); if (uid != 0) { // User not created successfully! status = MembershipCreateStatus.DuplicateUserName; return(null); } //////////////////////////////////////////////////////////// // Step 4: Create user in Membership table DateTime dt = MyConnectionHelper.RoundToSeconds(DateTime.Now); command = new SqlCommand(@"INSERT INTO users " + "(UserName,PasswordHash, Salt) " + "VALUES (@UserName,@PasswordHash, @salt)", connection); int pFormat = (int)_passwordFormat; command.Parameters.Add(new SqlParameter("@UserName", username)); command.Parameters.Add(new SqlParameter("@PasswordHash", pass)); command.Parameters.Add(new SqlParameter("@salt", salt)); // // Error inserting row // if (command.ExecuteNonQuery() != 1) { status = MembershipCreateStatus.ProviderError; return(null); } status = MembershipCreateStatus.Success; return(new MembershipUser(this.Name, username, uid, email, passwordQuestion, null, isApproved, false, dt, dt, dt, dt, DateTime.MinValue)); } catch (Exception e) { throw MyConnectionHelper.GetBetterException(e, holder); } finally { holder.Close(); } } catch { throw; } }
public override void Initialize(string name, NameValueCollection config) { if (config == null) { throw new ArgumentNullException("config"); } if (String.IsNullOrEmpty(name)) { name = "AccessMembershipProvider"; } if (string.IsNullOrEmpty(config["description"])) { config.Remove("description"); config.Add("description", "Membership $safeprojectname$ Provider"); } base.Initialize(name, config); _enablePasswordRetrieval = SecUtility.GetBooleanValue(config, "enablePasswordRetrieval", false); _enablePasswordReset = SecUtility.GetBooleanValue(config, "enablePasswordReset", true); _requiresQuestionAndAnswer = SecUtility.GetBooleanValue(config, "requiresQuestionAndAnswer", false); _requiresUniqueEmail = SecUtility.GetBooleanValue(config, "requiresUniqueEmail", false); _maxInvalidPasswordAttempts = SecUtility.GetIntValue(config, "maxInvalidPasswordAttempts", 5, false, 0); _passwordAttemptWindow = SecUtility.GetIntValue(config, "passwordAttemptWindow", 10, false, 0); _minRequiredPasswordLength = SecUtility.GetIntValue(config, "minRequiredPasswordLength", 7, false, 128); _minRequiredNonalphanumericCharacters = SecUtility.GetIntValue(config, "minRequiredNonalphanumericCharacters", 1, true, 128); _hashAlgorithmType = config["hashAlgorithmType"]; if (String.IsNullOrEmpty(_hashAlgorithmType)) { _hashAlgorithmType = "MD5"; } _passwordStrengthRegularExpression = config["passwordStrengthRegularExpression"]; if (_passwordStrengthRegularExpression != null) { _passwordStrengthRegularExpression = _passwordStrengthRegularExpression.Trim(); if (_passwordStrengthRegularExpression.Length != 0) { try { Regex regex = new Regex(_passwordStrengthRegularExpression); } catch (ArgumentException e) { throw new ProviderException(e.Message, e); } } } else { _passwordStrengthRegularExpression = string.Empty; } _appName = config["applicationName"]; if (string.IsNullOrEmpty(_appName)) { _appName = SecUtility.GetDefaultAppName(); } if (_appName.Length > 255) { throw new ProviderException("Provider application name is too long, max length is 255."); } string strTemp = config["passwordFormat"]; if (strTemp == null) { 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("Provider cannot retrieve hashed password"); } _databaseFileName = config["connectionStringName"]; if (_databaseFileName == null || _databaseFileName.Length < 1) { throw new ProviderException("Connection name not specified"); } string temp = MyConnectionHelper.GetFileNameFromConnectionName(_databaseFileName, true); if (temp == null || temp.Length < 1) { throw new ProviderException("Connection string not found: " + _databaseFileName); } _databaseFileName = temp; // Make sure connection is good MyConnectionHelper.CheckConnectionString(_databaseFileName); config.Remove("connectionStringName"); config.Remove("enablePasswordRetrieval"); config.Remove("enablePasswordReset"); config.Remove("requiresQuestionAndAnswer"); config.Remove("applicationName"); config.Remove("requiresUniqueEmail"); config.Remove("maxInvalidPasswordAttempts"); config.Remove("passwordAttemptWindow"); config.Remove("passwordFormat"); config.Remove("name"); config.Remove("description"); config.Remove("minRequiredPasswordLength"); config.Remove("minRequiredNonalphanumericCharacters"); config.Remove("passwordStrengthRegularExpression"); config.Remove("hashAlgorithmType"); if (config.Count > 0) { string attribUnrecognized = config.GetKey(0); if (!String.IsNullOrEmpty(attribUnrecognized)) { throw new ProviderException("Provider unrecognized attribute: " + attribUnrecognized); } } }