Exemple #1
0
        public bool ChangePassword(int userId, string userName, string oldPassword, string newPassword)
        {
            if (oldPassword == newPassword)
            {
                throw new NewPasswordCannotBeAsOneOfOldPasswordsException();
            }

            Users user = GetUserById(userId);

            if (user == null)
            {
                throw new NoEntryFoundException(userId, typeof(Users).Name);
            }

            Credentials credentials = CredentialsRepository.FindByUserNameAndUserId(userId, userName);

            if (credentials == null)
            {
                throw new NoEntryFoundException(userId, typeof(Credentials).Name);
            }

            bool validPassword = CheckUserPassword(credentials, oldPassword);

            if (!validPassword)
            {
                throw new InvalidPasswordException();
            }

            bool value = CheckForPasswordHistory(userId, credentials.Id, newPassword);

            if (!value)
            {
                return(false);
            }

            UserPasswordsHistory history = new UserPasswordsHistory
            {
                CredentialsId = credentials.Id,
                UserId        = user.Id,
                PasswordHash  = credentials.PasswordHash,
                PasswordSalt  = credentials.PasswordSalt,
                ExpiredOn     = DateTime.UtcNow
            };

            ArchiveRepository.Add(history);

            HashedAndSaltedPassword newPasswordHash = PasswordHelper.CryptPassword(newPassword);

            credentials.PasswordHash = newPasswordHash.PasswordHash;
            credentials.PasswordSalt = newPasswordHash.PasswordSalt;
            CredentialsRepository.Update(credentials);

            return(true);
        }