Пример #1
0
        /// <summary>
        /// Resets the password.
        /// </summary>
        /// <param name="passwordResetToken">The password reset token.</param>
        /// <param name="newPassword">The new password.</param>
        /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
        /// <exception cref="System.InvalidOperationException">
        /// The <seealso cref="Initialized"/> method was not called.-or-
        /// The <seealso cref="InitializeDatabaseConnection(string)"/> method was not called.-or-
        /// The <seealso cref="MySqlSimpleMembershipProvider"/> membership provider is not registered in the configuration of your site.
        /// For more information, contact your site's system administrator.
        /// </exception>
        public static bool ResetPassword(string passwordResetToken, string newPassword)
        {
            MySqlSimpleMembershipProvider provider = VerifyProvider();

            Debug.Assert(provider != null);             // VerifyProvider checks this
            return(provider.ResetPasswordWithToken(passwordResetToken, newPassword));
        }
        public override string[] GetUsersInRole(string roleName)
        {
            if (!Initialized)
            {
                return(_prevProvider.GetUsersInRole(roleName));
            }
            if (string.IsNullOrEmpty(roleName))
            {
                MySqlSimpleMembershipProvider.NullArgumentException("roleName");
            }

            int roleid = GetRoleId(roleName);

            if (roleid > 0)
            {
                using (MySqlDatabaseWrapper dbConn = new MySqlDatabaseWrapper(ConnectionString))
                {
                    var users = dbConn.ExecuteQuery(string.Format("select ut.{0} from {1} as urt join {2} as ut on urt.userid = ut.{3} where urt.roleid=?;", UserNameColumn, _userInRolesTable, UserTableName, UserIdColumn), roleid);
                    if (users.Count() > 0)
                    {
                        return(users.Select(role => role[0].ToString()).ToArray());
                    }
                }
            }
            return(null);
        }
        public override bool IsUserInRole(string username, string roleName)
        {
            if (!Initialized)
            {
                return(_prevProvider.IsUserInRole(username, roleName));
            }
            string connString = ConnectionString;

            if (string.IsNullOrEmpty(username))
            {
                MySqlSimpleMembershipProvider.NullArgumentException("username");
            }
            if (string.IsNullOrEmpty(roleName))
            {
                MySqlSimpleMembershipProvider.NullArgumentException("roleName");
            }
            int userid = MySqlSimpleMembershipProvider.GetUserId(username, connString, UserTableName, UserIdColumn, UserNameColumn);
            int roleid = GetRoleId(roleName);

            if (userid <= 0 || roleid <= 0)
            {
                return(false);
            }
            using (MySqlDatabaseWrapper dbConn = new MySqlDatabaseWrapper(connString))
            {
                return((dbConn.ExecuteQuery(string.Format("select count(userid) from {0} where userid=? and roleid=?;", _userInRolesTable), userid, roleid)).Count() > 0);
            }
        }
        public override void CreateRole(string roleName)
        {
            if (!Initialized)
            {
                _prevProvider.CreateRole(roleName);
            }
            else
            {
                if (string.IsNullOrEmpty(roleName))
                {
                    MySqlSimpleMembershipProvider.NullArgumentException("roleName");
                }

                using (MySqlDatabaseWrapper dbConn = new MySqlDatabaseWrapper(ConnectionString))
                {
                    int roleid = GetRoleId(roleName);
                    if (roleid != 0)
                    {
                        throw new InvalidOperationException(string.Format(Resources.RoleAlreadyExists, roleName));
                    }
                    if (dbConn.ExecuteNonQuery(string.Format("insert into {0} (rolename) values(?);", _rolesTable), roleName) <= 0)
                    {
                        throw new ProviderException(string.Format(Resources.CreateRoleFailed, roleName));
                    }
                }
            }
        }
        public override string[] GetRolesForUser(string username)
        {
            if (!Initialized)
            {
                return(_prevProvider.GetRolesForUser(username));
            }
            if (string.IsNullOrEmpty(username))
            {
                MySqlSimpleMembershipProvider.NullArgumentException("username");
            }

            string connString = ConnectionString;
            int    userid     = MySqlSimpleMembershipProvider.GetUserId(username, connString, UserTableName, UserIdColumn, UserNameColumn);

            if (userid > 0)
            {
                using (MySqlDatabaseWrapper dbConn = new MySqlDatabaseWrapper(connString))
                {
                    var roles = dbConn.ExecuteQuery(string.Format("select rt.rolename from {0} as urt join {1} as rt on urt.roleid = rt.roleid where urt.userid=?;", _userInRolesTable, _rolesTable), userid);
                    if (roles.Count() > 0)
                    {
                        return(roles.Select(role => role[0].ToString()).ToArray());
                    }
                }
            }
            return(null);
        }
Пример #6
0
        /// <summary>
        /// Confirms that an account for the specified user name is valid and activates the account.
        /// </summary>
        /// <param name="userName">The user name.</param>
        /// <param name="accountConfirmationToken">A confirmation token to pass to the authentication provider.</param>
        /// <returns><c>true</c> if the account is confirmed; otherwise, <c>false</c>.</returns>
        /// <exception cref="System.InvalidOperationException">
        /// The <seealso cref="Initialized"/> method was not called.-or-
        /// The <seealso cref="InitializeDatabaseConnection(string)"/> method was not called.-or-
        /// The <seealso cref="MySqlSimpleMembershipProvider"/> membership provider is not registered in the configuration of your site.
        /// For more information, contact your site's system administrator.
        /// </exception>
        public static bool ConfirmAccount(string userName, string accountConfirmationToken)
        {
            MySqlSimpleMembershipProvider provider = VerifyProvider();

            Debug.Assert(provider != null);             // VerifyProvider checks this
            return(provider.ConfirmAccount(userName, accountConfirmationToken));
        }
        public override bool DeleteRole(string roleName, bool throwOnPopulatedRole)
        {
            if (!Initialized)
            {
                return(_prevProvider.DeleteRole(roleName, throwOnPopulatedRole));
            }
            if (string.IsNullOrEmpty(roleName))
            {
                MySqlSimpleMembershipProvider.NullArgumentException("roleName");
            }

            int roleid = GetRoleId(roleName);

            if (roleid <= 0)
            {
                return(false);
            }
            using (MySqlDatabaseWrapper dbConn = new MySqlDatabaseWrapper(ConnectionString))
            {
                if (throwOnPopulatedRole)
                {
                    if (IsRoleInUse(roleid))
                    {
                        throw new InvalidOperationException(string.Format(Resources.RoleInUse, roleName));
                    }
                }
                else
                {
                    dbConn.ExecuteNonQuery(string.Format("delete from {0} where roleid=?;", _userInRolesTable), roleid);
                }
                return(dbConn.ExecuteNonQuery(string.Format("delete from {0} where roleid=?;", _rolesTable), roleid) > 0);
            }
        }
        private static void InitializeMembershipProvider(string connectionStringName, string connectionString, string providerName, string userTableName, string userIdColumn, string userNameColumn, bool createTables, bool checkIfInitialized = false)
        {
            if (checkIfInitialized)
            {
                if (_provider != null)
                {
                    return;
                }
            }

            MySqlSimpleMembershipProvider simpleMembership = new MySqlSimpleMembershipProvider(Membership.Provider);

            if (_provider != null && _provider.Initialized)
            {
                throw new InvalidOperationException(Resources.SimpleMembershipAlreadyInitialized);
            }
            simpleMembership.ConnectionStringName = connectionStringName;
            simpleMembership.ConnectionString     = connectionString;
            simpleMembership.ProviderName         = providerName;
            simpleMembership.UserTableName        = userTableName;
            simpleMembership.UserIdColumn         = userIdColumn;
            simpleMembership.UserNameColumn       = userNameColumn;
            if (createTables)
            {
                simpleMembership.CreateTables();
            }
            else
            {
                simpleMembership.ValidateUserTable();
            }
            simpleMembership.Initialized = true;
            _provider = simpleMembership;
        }
        public override string[] FindUsersInRole(string roleName, string usernameToMatch)
        {
            if (!Initialized)
            {
                return(_prevProvider.FindUsersInRole(roleName, usernameToMatch));
            }
            if (string.IsNullOrEmpty(roleName))
            {
                MySqlSimpleMembershipProvider.NullArgumentException("roleName");
            }
            if (string.IsNullOrEmpty(usernameToMatch))
            {
                return(GetUsersInRole(roleName));
            }

            using (MySqlDatabaseWrapper dbConn = new MySqlDatabaseWrapper(ConnectionString))
            {
                var usersName = dbConn.ExecuteQuery(string.Format("select ut.{0} from {1} as rt join {2} as urt on rt.roleid=urt.roleid join {3} as ut on rt.userid=ut.{4} where rt.rolename=? and ut.name like '%?%'", UserNameColumn, _rolesTable, _userInRolesTable, UserTableName, UserIdColumn), roleName, usernameToMatch);
                if (usersName.Count() > 0)
                {
                    return(usersName.Select(username => username[0].ToString()).ToArray());
                }
            }
            return(null);
        }
Пример #10
0
        //private string GetConnectionString()
        //{
        //  if (!string.IsNullOrEmpty(ConnectionString))
        //    return ConnectionString;
        //  else
        //  {
        //    ConnectionStringSettings connString = ConfigurationManager.ConnectionStrings[ConnectionStringName];
        //    if (connString != null)
        //      return connString.ConnectionString;
        //  }

        //  if (!string.IsNullOrEmpty(_connString))
        //    return _connString;
        //  throw new InvalidOperationException(Resources.NoConnString);
        //}

        private IEnumerable <int> GetUsersId(string[] usersName)
        {
            foreach (string userName in usersName)
            {
                yield return(MySqlSimpleMembershipProvider.GetUserId(userName, ConnectionString, UserTableName, UserIdColumn, UserNameColumn));
            }
        }
Пример #11
0
        /// <summary>
        /// Returns a value that indicates whether the user has been confirmed.
        /// </summary>
        /// <param name="userName">The user name.</param>
        /// <returns><c>true</c> if the user is confirmed; otherwise, <c>false</c>.</returns>
        public static bool IsConfirmed(string userName)
        {
            MySqlSimpleMembershipProvider provider = VerifyProvider();

            Debug.Assert(provider != null);             // VerifyProvider checks this

            return(provider.IsConfirmed(userName));
        }
Пример #12
0
        public static string GeneratePasswordResetToken(string userName, int tokenExpirationInMinutesFromNow = 1440)
        {
            MySqlSimpleMembershipProvider provider = VerifyProvider();

            Debug.Assert(provider != null);             // VerifyProvider checks this

            return(provider.GeneratePasswordResetToken(userName, tokenExpirationInMinutesFromNow));
        }
Пример #13
0
        public static string CreateAccount(string userName, string password, bool requireConfirmationToken = false)
        {
            MySqlSimpleMembershipProvider provider = VerifyProvider();

            Debug.Assert(provider != null);             // VerifyProvider checks this

            return(provider.CreateAccount(userName, password, requireConfirmationToken));
        }
Пример #14
0
        private static MySqlSimpleMembershipProvider CreateDefaultExtendedMembershipProvider(string name, MembershipProvider currentDefault)
        {
            var membership             = new MySqlSimpleMembershipProvider(previousProvider: currentDefault);
            NameValueCollection config = new NameValueCollection();

            membership.Initialize(name, config);
            return(membership);
        }
Пример #15
0
        /// <summary>
        /// Returns a user ID from a password reset token.
        /// </summary>
        /// <param name="token">The password reset token.</param>
        /// <returns>The user ID.</returns>
        /// <exception cref="System.InvalidOperationException">
        /// The <seealso cref="Initialized"/> method was not called.-or-
        /// The <seealso cref="InitializeDatabaseConnection(string)"/> method was not called.-or-
        /// The <seealso cref="MySqlSimpleMembershipProvider"/> membership provider is not registered in the configuration of your site.
        /// For more information, contact your site's system administrator.
        /// </exception>
        public static int GetUserIdFromPasswordResetToken(string token)
        {
            MySqlSimpleMembershipProvider provider = VerifyProvider();

            Debug.Assert(provider != null);             // VerifyProvider checks this

            return(provider.GetUserIdFromPasswordResetToken(token));
        }
Пример #16
0
        /// <summary>
        /// Returns a value that indicates whether the specified membership account is temporarily locked because of too many failed password attempts in the specified time span.
        /// </summary>
        /// <param name="userName">The user name of the membership account.</param>
        /// <param name="allowedPasswordAttempts">The number of password attempts the user is permitted before the membership account is locked.</param>
        /// <param name="interval">The number of seconds to lock out a user account after the number of password attempts exceeds the value in the allowedPasswordAttempts parameter.</param>
        /// <returns><c>true</c> if the membership account is locked; otherwise, <c>false</c>.</returns>
        /// <exception cref="System.InvalidOperationException">
        /// The <seealso cref="Initialized"/> method was not called.-or-
        /// The <seealso cref="InitializeDatabaseConnection(string)"/> method was not called.-or-
        /// The <seealso cref="MySqlSimpleMembershipProvider"/> membership provider is not registered in the configuration of your site.
        /// For more information, contact your site's system administrator.
        /// </exception>
        public static bool IsAccountLockedOut(string userName, int allowedPasswordAttempts, TimeSpan interval)
        {
            MySqlSimpleMembershipProvider provider = VerifyProvider();

            Debug.Assert(provider != null);             // VerifyProvider checks this

            return(IsAccountLockedOutInternal(provider, userName, allowedPasswordAttempts, interval));
        }
        private static MySqlSimpleMembershipProvider CreateSimpleMembershipProvider(string name, MySQLMembershipProvider currentDefault)
        {
            MySqlSimpleMembershipProvider simpleProvider = new MySqlSimpleMembershipProvider(currentDefault);
            NameValueCollection           config         = new NameValueCollection();

            simpleProvider.Initialize(name, config);
            return(simpleProvider);
        }
Пример #18
0
        /// <summary>
        /// Returns the date and time when an incorrect password was most recently entered for the specified account.
        /// </summary>
        /// <param name="userName">The user name of the membership account.</param>
        /// <returns>The date and time when an incorrect password was most recently entered for this account, or <see cref="System.DateTime.MinValue"/> if an incorrect password has not been entered for this account.</returns>
        /// <exception cref="System.InvalidOperationException">
        /// The <seealso cref="Initialized"/> method was not called.-or-
        /// The <seealso cref="InitializeDatabaseConnection(string)"/> method was not called.-or-
        /// The <seealso cref="MySqlSimpleMembershipProvider"/> membership provider is not registered in the configuration of your site.
        /// For more information, contact your site's system administrator.
        /// </exception>
        public static DateTime GetLastPasswordFailureDate(string userName)
        {
            MySqlSimpleMembershipProvider provider = VerifyProvider();

            Debug.Assert(provider != null);             // VerifyProvider checks this

            return(provider.GetLastPasswordFailureDate(userName));
        }
Пример #19
0
        /// <summary>
        /// Returns the number of times that the password for the specified account was incorrectly entered since the last successful login or since the membership account was created.
        /// </summary>
        /// <param name="userName">The user name of the account.</param>
        /// <returns>The count of failed password attempts for the specified account.</returns>
        /// <exception cref="System.InvalidOperationException">
        /// The <seealso cref="Initialized"/> method was not called.-or-
        /// The <seealso cref="InitializeDatabaseConnection(string)"/> method was not called.-or-
        /// The <seealso cref="MySqlSimpleMembershipProvider"/> membership provider is not registered in the configuration of your site.
        /// For more information, contact your site's system administrator.
        /// </exception>
        public static int GetPasswordFailuresSinceLastSuccess(string userName)
        {
            MySqlSimpleMembershipProvider provider = VerifyProvider();

            Debug.Assert(provider != null);             // VerifyProvider checks this

            return(provider.GetPasswordFailuresSinceLastSuccess(userName));
        }
Пример #20
0
 internal static void InitializeMembershipProvider(MySqlSimpleMembershipProvider extendedMembership, DatabaseConnectionInfo connect)
 {
     if (extendedMembership.InitializeCalled)
     {
         throw new InvalidOperationException(Resources.Security_InitializeAlreadyCalled);
     }
     extendedMembership.ConnectionInfo = connect;
     // We want to validate the user table if we aren't creating them
     extendedMembership.ValidateTable();
     extendedMembership.InitializeCalled = true;
 }
Пример #21
0
        public static bool Login(string userName, string password, bool persistCookie = false)
        {
            MySqlSimpleMembershipProvider provider = VerifyProvider();
            bool success = provider.ValidateUser(userName, password);

            if (success)
            {
                FormsAuthentication.SetAuthCookie(userName, persistCookie);
            }
            return(success);
        }
Пример #22
0
        private static MySqlSimpleMembershipProvider VerifyProvider()
        {
            MySqlSimpleMembershipProvider provider = System.Web.Security.Membership.Provider as MySqlSimpleMembershipProvider;

            if (provider == null)
            {
                throw new InvalidOperationException(Resources.Security_NoExtendedMembershipProvider);
            }

            provider.VerifyInitialized();             // Have the provider verify that it's initialized (only our SimpleMembershipProvider does anything here)
            return(provider);
        }
Пример #23
0
        private List <int> GetUserIdsFromNames(MySqlSecurityDbContext db, string[] usernames)
        {
            List <int> userIds = new List <int>(usernames.Length);

            foreach (string username in usernames)
            {
                int id = MySqlSimpleMembershipProvider.GetUserId(db, username);
                if (id == -1)
                {
                    throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, Resources.Security_NoUserFound, username));
                }
                userIds.Add(id);
            }
            return(userIds);
        }
Пример #24
0
        public static string CreateUserAndAccount(string userName, string password, object propertyValues = null, bool requireConfirmationToken = false)
        {
            MySqlSimpleMembershipProvider provider = VerifyProvider();

            Debug.Assert(provider != null);             // VerifyProvider checks this

            IDictionary <string, object> values = null;

            if (propertyValues != null)
            {
                values = new Dictionary <string, object>(propertyValues as IDictionary <string, object>);
            }

            return(provider.CreateUserAndAccount(userName, password, requireConfirmationToken, values));
        }
Пример #25
0
        private static void InitializeProviders(DatabaseConnectionInfo connect)
        {
            MySqlSimpleMembershipProvider extendedMembership = System.Web.Security.Membership.Provider as MySqlSimpleMembershipProvider;

            if (extendedMembership != null)
            {
                InitializeMembershipProvider(extendedMembership, connect);
            }

            MySqlSimpleRoleProvider extendedRoles = Roles.Provider as MySqlSimpleRoleProvider;

            if (extendedRoles != null)
            {
                InitializeRoleProvider(extendedRoles, connect);
            }

            Initialized = true;
        }
Пример #26
0
        /// <summary>
        /// Gets a list of the roles that a specified user is in for the configured applicationName.
        /// </summary>
        /// <remarks>Inherited from RoleProvider ==> Forwarded to previous provider if this provider hasn't been initialized</remarks>
        /// <param name="username">The user to return a list of roles for.</param>
        /// <returns>A string array containing the names of all the roles that the specified user is in for the configured applicationName.</returns>
        /// <exception cref="System.InvalidOperationException"></exception>
        public override string[] GetRolesForUser(string username)
        {
            if (!InitializeCalled)
            {
                return(PreviousProvider.GetRolesForUser(username));
            }
            using (var db = NewMySqlSecurityDbContext)
            {
                int userId = MySqlSimpleMembershipProvider.GetUserId(db, username);
                if (userId == -1)
                {
                    throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, Resources.Security_NoUserFound, username));
                }

                var roleNames = db.UsersInRoles.Where(x => x.UserId == userId)
                                .Select(x => x.Role.RoleName)
                                .ToArray();
                return(roleNames);
            }
        }
 internal static void PreAppStartInit()
 {
     if (IsSimpleMembershipEnabled())
     {
         MembershipProvider provider = Membership.Providers[MySqlMembershipProviderName];
         if (provider != null)
         {
             MySqlSimpleMembershipProvider mysqlProvider = CreateSimpleMembershipProvider(MySqlMembershipProviderName, (MySQLMembershipProvider)provider);
             Membership.Providers.Remove(MySqlMembershipProviderName);
             Membership.Providers.Add(mysqlProvider);
         }
         Roles.Enabled = true;
         RoleProvider roleProvider = Roles.Providers[MySqlRoleProviderName];
         if (roleProvider != null)
         {
             MySqlSimpleRoleProvider simpleRoleProv = CreateSimpleRoleProvider(MySqlRoleProviderName, (MySQLRoleProvider)roleProvider);
             Roles.Providers.Remove(MySqlRoleProviderName);
             Roles.Providers.Add(simpleRoleProv);
         }
     }
 }
Пример #28
0
 internal static bool IsAccountLockedOutInternal(MySqlSimpleMembershipProvider provider, string userName, int allowedPasswordAttempts, TimeSpan interval)
 {
     return(provider.GetUser(userName, false) != null &&
            provider.GetPasswordFailuresSinceLastSuccess(userName) > allowedPasswordAttempts &&
            provider.GetLastPasswordFailureDate(userName).Add(interval) > DateTime.Now);
 }
 internal static bool IsAccountLockedOutInternal(MySqlSimpleMembershipProvider provider, string userName, int allowedPasswordAttempts, TimeSpan interval)
 {
     return (provider.GetUser(userName, false) != null &&
             provider.GetPasswordFailuresSinceLastSuccess(userName) > allowedPasswordAttempts &&
             provider.GetLastPasswordFailureDate(userName).Add(interval) > DateTime.Now);
 }
 internal static void InitializeMembershipProvider(MySqlSimpleMembershipProvider extendedMembership, DatabaseConnectionInfo connect)
 {
     if (extendedMembership.InitializeCalled)
     {
         throw new InvalidOperationException(Resources.Security_InitializeAlreadyCalled);
     }
     extendedMembership.ConnectionInfo = connect;
     // We want to validate the user table if we aren't creating them
     extendedMembership.ValidateTable();
     extendedMembership.InitializeCalled = true;
 }
 private static MySqlSimpleMembershipProvider CreateDefaultExtendedMembershipProvider(string name, MembershipProvider currentDefault)
 {
     var membership = new MySqlSimpleMembershipProvider(previousProvider: currentDefault);
     NameValueCollection config = new NameValueCollection();
     membership.Initialize(name, config);
     return membership;
 }