Пример #1
0
        public async Task ValidadeUserPasswordForHistoryAsync_Invalid_False()
        {
            // Arrange
            var          cxn             = new SqlConnectionWrapperMock();
            var          repository      = new SqlUserRepository(cxn.Object, cxn.Object);
            const int    userId          = 99;
            var          userSalt        = new Guid();
            const string newPassword     = "******";
            var          passwordHystory = new List <SqlUserRepository.HashedPassword>
            {
                new SqlUserRepository.HashedPassword {
                    Password = HashingUtilities.GenerateSaltedHash(newPassword, userSalt), UserSALT = userSalt
                }
            };

            cxn.SetupQueryAsync(
                "GetLastUserPasswords",
                new Dictionary <string, object>
            {
                { "@userId", userId }
            },
                passwordHystory);

            // Act
            var result = await repository.ValidateUserPasswordForHistoryAsync(userId, newPassword);

            // Assert
            cxn.Verify();
            Assert.AreEqual(false, result);
        }
Пример #2
0
        public async Task <FullStubModel> AddStubAsync(StubModel stub)
        {
            if (string.IsNullOrWhiteSpace(stub.Id))
            {
                // If no ID is sent, create one here.
                var id = HashingUtilities.GetMd5String(JsonConvert.SerializeObject(stub));
                stub.Id = $"stub-{id}";
            }

            // Check that a stub with the new ID isn't already added to a readonly stub source.
            var stubs = await GetStubsAsync(true);

            if (stubs.Any(s => string.Equals(stub.Id, s.Stub.Id, StringComparison.OrdinalIgnoreCase)))
            {
                throw new ConflictException($"Stub with ID '{stub.Id}'.");
            }

            var source = GetWritableStubSource();
            await source.AddStubAsync(stub);

            return(new FullStubModel {
                Stub = stub, Metadata = new StubMetadataModel {
                    ReadOnly = false
                }
            });
        }
Пример #3
0
    /// <summary>
    /// Sets an autogenerated ID on a stub if no ID has been set yet.
    /// </summary>
    /// <param name="stub">The stub.</param>
    /// <returns>The stub ID.</returns>
    public static string EnsureStubId(this StubModel stub)
    {
        if (!string.IsNullOrWhiteSpace(stub.Id))
        {
            return(stub.Id);
        }

        var id = $"generated-{HashingUtilities.GetMd5String(JsonConvert.SerializeObject(stub))}";

        stub.Id = id;
        return(id);
    }
    public void GetMd5String_HappyFlow()
    {
        // Arrange
        var input          = "test 123";
        var expectedOutput = "39d0d586a701e199389d954f2d592720";

        // Act
        var result = HashingUtilities.GetMd5String(input);

        // Assert
        Assert.AreEqual(expectedOutput, result);
    }
    public void GetSha512String_HappyFlow()
    {
        // Arrange
        var input          = "test 123";
        var expectedOutput = "RNiw9ZCfWvIt1SyjF8exd7hnDQHw8KK1iVcbqV+fyPt6yij3RnZkJS1SsuEmtxH4jjllJO4f3HK3Rjp0hKIcbw==";

        // Act
        var result = HashingUtilities.GetSha512String(input);

        // Assert
        Assert.AreEqual(expectedOutput, result);
    }
Пример #6
0
        public async Task UpdateUserPasswordAsync(string login, string password)
        {
            var userSalt    = Guid.NewGuid();
            var newPassword = HashingUtilities.GenerateSaltedHash(password, userSalt);

            var parameters = new DynamicParameters();

            parameters.Add("@Login", login);
            parameters.Add("@UserSALT", userSalt);
            parameters.Add("@Password", newPassword);
            await _connectionWrapper.ExecuteAsync("UpdateUserOnPasswordResetAsync", parameters, commandType : CommandType.StoredProcedure);
        }
        private static void EnsureStubsHaveId(IEnumerable <StubModel> stubs)
        {
            foreach (var stub in stubs)
            {
                if (!string.IsNullOrWhiteSpace(stub.Id))
                {
                    continue;
                }

                // If no ID is set, calculate a unique ID based on the stub contents.
                var contents = JsonConvert.SerializeObject(stub);
                stub.Id = HashingUtilities.GetMd5String(contents);
            }
        }
Пример #8
0
        public async Task ResetPassword(AuthenticationUser user, string oldPassword, string newPassword)
        {
            if (string.IsNullOrEmpty(newPassword))
            {
                throw new BadRequestException("Password reset failed, new password cannot be empty", ErrorCodes.EmptyPassword);
            }

            if (oldPassword != null && oldPassword == newPassword)
            {
                throw new BadRequestException("Password reset failed, new password cannot be equal to the old one", ErrorCodes.SamePassword);
            }

            if (newPassword.ToLower() == user.Login?.ToLower())
            {
                throw new BadRequestException("Password reset failed, new password cannot be equal to login name", ErrorCodes.PasswordSameAsLogin);
            }

            if (newPassword.ToLower() == user.DisplayName?.ToLower())
            {
                throw new BadRequestException("Password reset failed, new password cannot be equal to display name", ErrorCodes.PasswordSameAsDisplayName);
            }

            string errorMsg;

            if (!PasswordValidationHelper.ValidatePassword(newPassword, true, out errorMsg))
            {
                throw new BadRequestException("Password reset failed, new password is invalid", ErrorCodes.TooSimplePassword);
            }

            if (await IsChangePasswordCooldownInEffect(user))
            {
                throw new ConflictException("Password reset failed, password reset cooldown in effect", ErrorCodes.ChangePasswordCooldownInEffect);
            }

            if (!await _userRepository.ValidateUserPasswordForHistoryAsync(user.Id, newPassword))
            {
                throw new BadRequestException("The new password matches a previously used password.", ErrorCodes.PasswordAlreadyUsedPreviously);
            }

            var newGuid = Guid.NewGuid();

            user.UserSalt = newGuid;
            user.Password = HashingUtilities.GenerateSaltedHash(newPassword, user.UserSalt);

            await _userRepository.UpdateUserOnPasswordResetAsync(user);
        }
Пример #9
0
        public async Task <bool> ValidateUserPasswordForHistoryAsync(int userId, string newPassword)
        {
            var prm = new DynamicParameters();

            prm.Add("@userId", userId);
            var passwordHistory = await _connectionWrapper.QueryAsync <HashedPassword>("GetLastUserPasswords", prm, commandType : CommandType.StoredProcedure);

            foreach (var password in passwordHistory)
            {
                var newHashedPassword = HashingUtilities.GenerateSaltedHash(newPassword, password.UserSALT);
                if (string.Equals(newHashedPassword, password.Password))
                {
                    return(false);
                }
            }

            return(true);
        }
Пример #10
0
        public async Task <UserLogInModelOut> LogIn(UserLoginModelIn modelIn, UserTokenSessionModel userTokenSessionModel)
        {
            UserTokenSession userTokenSession = _mapper.Map <UserTokenSession>(userTokenSessionModel);

            UserLogInModelOut response = new UserLogInModelOut();

            User user = await _repos.Users.GetUserByEmailAndPassword(modelIn.Email, modelIn.Password);

            if (user == null)
            {
                response.AddError(CustomErrorEnum.UnsuccessfulLogIn);

                return(response);
            }

            response.Id              = user.Id;
            response.Email           = user.Email;
            response.EmailIsVerified = user.EmailIsVerified;
            response.PhoneNumber     = user.PhoneNumber;
            response.Token           = HashingUtilities.GetHashSHA512(Guid.NewGuid().ToString());

            userTokenSession.UserId         = user.Id;
            userTokenSession.Date           = DateTime.UtcNow;
            userTokenSession.LastUpdateDate = DateTime.UtcNow;
            userTokenSession.Token          = response.Token;

            await _repos.UserTokenSessions.Create(userTokenSession);

            if (await _repos.SaveAsync() == 0)
            {
                response.AddError(CustomErrorEnum.UnsuccessfulLogIn);

                return(response);
            }

            UserTokenSessionCacheModel clientTokenSessionCacheModel = _mapper.Map <UserTokenSessionCacheModel>(userTokenSession);

            _memoryCache.Set(response.Token, clientTokenSessionCacheModel, _cacheExpirationByMinutes.Value);

            return(response);
        }
Пример #11
0
        private AuthenticationStatus AuthenticateDatabaseUser(AuthenticationUser user, string password, int passwordExpirationInDays = 0)
        {
            var hashedPassword = HashingUtilities.GenerateSaltedHash(password, user.UserSalt);

            if (!string.Equals(user.Password, hashedPassword))
            {
                return(AuthenticationStatus.InvalidCredentials);
            }

            if (!user.IsEnabled)
            {
                return(AuthenticationStatus.Locked);
            }

            if (HasExpiredPassword(user, passwordExpirationInDays))
            {
                return(AuthenticationStatus.PasswordExpired);
            }

            return(AuthenticationStatus.Success);
        }
        public async Task <FullStubModel> GenerateStubBasedOnRequestAsync(string requestCorrelationId)
        {
            _logger.LogInformation($"Creating stub based on request with corr.ID '{requestCorrelationId}'.");

            // TODO lateron, when the querying is fixed, only query for one request result.
            var requestResults = await _stubContext.GetRequestResultsAsync();

            var requestResult = requestResults.FirstOrDefault(r => r.CorrelationId == requestCorrelationId);

            if (requestResult == null)
            {
                throw new NotFoundException(nameof(RequestResultModel), requestCorrelationId);
            }

            var stub = new StubModel();

            foreach (var handler in _handlers.OrderByDescending(w => w.Priority))
            {
                var executed = await handler.HandleStubGenerationAsync(requestResult, stub);

                _logger.LogInformation($"Handler '{handler.GetType().Name}'" + (executed ? " executed" : "") + ".");
            }

            // Set a default response
            stub.Response.Text = "OK!";

            // Generate an ID based on the created stub.
            var contents = JsonConvert.SerializeObject(stub);

            stub.Id = "generated-" + HashingUtilities.GetMd5String(contents);
            await _stubContext.DeleteStubAsync(stub.Id);

            var result = await _stubContext.AddStubAsync(stub);

            _logger.LogInformation($"Stub with ID '{stub.Id}' generated!");

            return(result);
        }
Пример #13
0
 private void PasswordBox_OnLostFocus(object sender, RoutedEventArgs e)
 {
     UserSignIn.Password = HashingUtilities.GetHash512(passwordBox.Password);
 }
Пример #14
0
 private static string CreateHash(string username, string password) =>
 HashingUtilities.GetSha512String($"{Salt}:{username}:{password}");
Пример #15
0
 private void ConfPasswordBox_LostFocus(object sender, RoutedEventArgs e)
 {
     UserSignUp.ConfirmPassword = HashingUtilities.GetHash512(ConfPasswordBox.Password);
 }
Пример #16
0
        public async Task <IHttpActionResult> PostPasswordResetAsync([FromBody] ResetPasswordContent content)
        {
            // the deserializer creates a zero filled guid when none provided
            if (content.Token == Guid.Empty || content.Token.GetHashCode() == 0)
            {
                throw new BadRequestException("Password reset failed, token not provided", ErrorCodes.PasswordResetEmptyToken);
            }

            var tokens = (await _userRepository.GetPasswordRecoveryTokensAsync(content.Token)).ToList();

            if (!tokens.Any())
            {
                // user did not request password reset
                throw new ConflictException("Password reset failed, recovery token not found.", ErrorCodes.PasswordResetTokenNotFound);
            }

            if (tokens.First().RecoveryToken != content.Token)
            {
                // provided token doesn't match last requested
                throw new ConflictException("Password reset failed, a more recent recovery token exists.", ErrorCodes.PasswordResetTokenNotLatest);
            }

            var tokenLifespan = await _applicationSettingsRepository.GetValue(PasswordResetTokenExpirationInHoursKey, DefaultPasswordResetTokenExpirationInHours);

            if (tokens.First().CreationTime.AddHours(tokenLifespan) < DateTime.Now)
            {
                // token expired
                throw new ConflictException("Password reset failed, recovery token expired.", ErrorCodes.PasswordResetTokenExpired);
            }

            var userLogin = tokens.First().Login;
            var user      = await _userRepository.GetUserByLoginAsync(userLogin);

            if (user == null)
            {
                // user does not exist
                throw new ConflictException("Password reset failed, the user does not exist.", ErrorCodes.PasswordResetUserNotFound);
            }

            if (!user.IsEnabled)
            {
                // user is disabled
                throw new ConflictException("Password reset failed, the login for this user is disabled.", ErrorCodes.PasswordResetUserDisabled);
            }

            string decodedNewPassword;

            try
            {
                decodedNewPassword = SystemEncryptions.Decode(content.Password);
            }
            catch (Exception)
            {
                throw new BadRequestException("Password reset failed, the provided password was not encoded correctly", ErrorCodes.PasswordDecodingError);
            }

            if (decodedNewPassword != null && user.Password == HashingUtilities.GenerateSaltedHash(decodedNewPassword, user.UserSalt))
            {
                throw new BadRequestException("Password reset failed, new password cannot be equal to the old one", ErrorCodes.SamePassword);
            }

            // reset password
            await _authenticationRepository.ResetPassword(user, null, decodedNewPassword);

            // drop user session
            var uri     = new Uri(WebApiConfig.AccessControl);
            var http    = _httpClientProvider.Create(uri);
            var request = new HttpRequestMessage {
                RequestUri = new Uri(uri, $"sessions/{user.Id}"), Method = HttpMethod.Delete
            };
            await http.SendAsync(request);

            return(Ok());
        }