public async Task ChangeUserPasswordAsync(PasswordChangeDTO passwordChange) { if (passwordChange.NewPassword != passwordChange.NewPasswordConfirmation) { return; } using var uow = UnitOfWorkProvider.Create(); var user = await userRepository.GetByIdAsync(passwordChange.UserId); if (user is null) { throw new EntityNotFoundException($"User with id '{passwordChange.UserId}' was not found."); } if (!IsLoginCredentialsValid(passwordChange.OldPassword, user)) { throw new UserAuthException($"Password verification for user '{passwordChange.UserId}' failed."); } user.PasswordHash = GetPasswordHash(passwordChange.NewPassword); await uow.CommitAsync(); }
public async Task <IActionResult> PasswordChange(PasswordChangeDTO passwordChangeDTO) { var password = await _repo.PasswordChange(passwordChangeDTO); if (password == null) { return(BadRequest()); } return(Ok()); }
public async Task <OutputResponse> UpdatePasswordAsync(PasswordChangeDTO passwordResetDTO) { var userName = passwordResetDTO.Username; var user = await _userManager.FindByNameAsync(userName); if (user == null) { return(new OutputResponse() { IsErrorOccured = true, Message = "Thandizo couldn't find your user details, please try again later" }); } var isOldPassword = await _userManager.CheckPasswordAsync(user, passwordResetDTO.NewPassword); if (isOldPassword) { return(new OutputResponse() { IsErrorOccured = true, Message = "Cannot use an old password, please try a different password" }); } if (!passwordResetDTO.NewPassword.Equals(passwordResetDTO.NewPasswordConfirmation)) { return(new OutputResponse() { IsErrorOccured = true, Message = "Your confirmation password does not match your new password" }); } var token = await _userManager.GeneratePasswordResetTokenAsync(user); var passwordReset = await _userManager.ResetPasswordAsync(user, token, passwordResetDTO.NewPassword); if (!passwordReset.Succeeded) { return(new OutputResponse { IsErrorOccured = true, Message = passwordReset.Errors.FirstOrDefault().Description }); } user.DefaultPassword = 1; await _userManager.UpdateAsync(user); return(new OutputResponse { IsErrorOccured = false, Result = passwordResetDTO.NewPassword }); }
public async Task SetPasswordTest_ValidInfo() { UserDTO newUser = new UserDTO { Email = "*****@*****.**", Password = "******", FirstName = "Phoebe", LastName = "S." }; GenericResponseDTO <int> registerResponse = await authController.Register(newUser); Assert.IsTrue(registerResponse.Success); TestAuthHelpers.attachUserToContext(registerResponse.Data, controllers); GenericResponseDTO <AccessKeysDTO> loginResponse = await authController.Login(newUser); Assert.IsTrue(registerResponse.Success); PasswordChangeDTO passwordChangeInfo = new PasswordChangeDTO { CurrentPassword = "******", NewPassword = "******" }; GenericResponseDTO <int> changePasswordResponse = await profileController.SetPassword(passwordChangeInfo); Assert.IsTrue(changePasswordResponse.Success); User currentUser = await database.Users .AsNoTracking() .FirstOrDefaultAsync(user => user.Id == registerResponse.Data); Assert.IsTrue(authHelper.GetPasswordHash("Aero125", configuration).SequenceEqual(currentUser.Password)); loginResponse = await authController.Login(newUser); Assert.IsFalse(loginResponse.Success); passwordChangeInfo.CurrentPassword = "******"; passwordChangeInfo.NewPassword = "******"; changePasswordResponse = await profileController.SetPassword(passwordChangeInfo); Assert.IsTrue(changePasswordResponse.Success); currentUser = await database.Users .AsNoTracking() .FirstOrDefaultAsync(user => user.Id == registerResponse.Data); Assert.IsTrue(authHelper.GetPasswordHash("Aquarius13", configuration).SequenceEqual(currentUser.Password)); loginResponse = await authController.Login(newUser); Assert.IsTrue(loginResponse.Success); }
public async Task <IActionResult> UpdatePassword(PasswordChangeDTO passwordResetDTO) { passwordResetDTO.Username = HttpContext.User.Identity.Name; var response = await _userManagementService.UpdatePasswordAsync(passwordResetDTO); if (response.IsErrorOccured) { ModelState.AddModelError(string.Empty, response.Message); return(View()); } return(Redirect(WebPortalURL)); }
public async Task <ActionResult <string> > ChangePassword([FromBody] PasswordChangeDTO request) { try { var user = await userManager.FindByNameAsync(request.Username); await userManager.ChangePasswordAsync(user, request.OldPassword, request.Password); return(Ok()); } catch (ArgumentNullException) { return(NotFound($"User '{request.Username}' could not be found!")); } }
public async Task <GenericResponseDTO <int> > SetPassword(PasswordChangeDTO passwordInfo) { int currentUserID; try { currentUserID = authHelper.GetCurrentUserId(User); } catch (System.NullReferenceException) { return(new GenericResponseDTO <int> { Message = "Not logged in.", Success = false }); } User currentUser = await database.Users .AsQueryable() .FirstOrDefaultAsync(user => user.Id == currentUserID); if (currentUser == null) { return(new GenericResponseDTO <int> { Message = "No matching User ID found.", Success = false }); } if (!currentUser.Password.SequenceEqual(authHelper.GetPasswordHash(passwordInfo.CurrentPassword, configuration))) { return(new GenericResponseDTO <int> { Message = "Current password is incorrect.", Success = false }); } if (!authHelper.IsValidPassword(passwordInfo.NewPassword)) { return(new GenericResponseDTO <int> { Success = false, Message = "Invalid new password, the password must contain a lowercase letter, uppercase letter, a number and be at least 7 characters." }); } currentUser.Password = authHelper.GetPasswordHash(passwordInfo.NewPassword, configuration); await database.SaveChangesAsync(); return(new GenericResponseDTO <int> { Success = true }); }
public async Task <string> PasswordChange(PasswordChangeDTO passwordChangeDTO) { var userDB = await _context.Users.FirstOrDefaultAsync(x => x.Id == passwordChangeDTO.UserId && x.Email == passwordChangeDTO.Email); if (userDB == null) { return(null); } byte[] passwordSalt, passwordHash; Password.CreateHashPassword(passwordChangeDTO.Password, out passwordSalt, out passwordHash); userDB.PasswordHash = passwordHash; userDB.PasswordSalt = passwordSalt; await _context.SaveChangesAsync(); return(passwordChangeDTO.Password); }
public async Task SetPasswordTest_IncorrectVerificationPassword() { UserDTO newUser = new UserDTO { Email = "*****@*****.**", Password = "******", FirstName = "Basther", LastName = "H." }; GenericResponseDTO <int> registerResponse = await authController.Register(newUser); Assert.IsTrue(registerResponse.Success); TestAuthHelpers.attachUserToContext(registerResponse.Data, controllers); GenericResponseDTO <AccessKeysDTO> loginResponse = await authController.Login(newUser); Assert.IsTrue(loginResponse.Success); PasswordChangeDTO passwordChangeInfo = new PasswordChangeDTO { CurrentPassword = "******", NewPassword = "******" }; GenericResponseDTO <int> changePasswordResponse = await profileController.SetPassword(passwordChangeInfo); Assert.IsFalse(changePasswordResponse.Success); User currentUser = await database.Users .AsNoTracking() .FirstOrDefaultAsync(user => user.Id == registerResponse.Data); Assert.IsFalse(authHelper.GetPasswordHash("oNe4thRee9seVen", configuration).SequenceEqual(currentUser.Password)); Assert.IsTrue(authHelper.GetPasswordHash("1fOur3niNe7", configuration).SequenceEqual(currentUser.Password)); loginResponse = await authController.Login(newUser); Assert.IsTrue(loginResponse.Success); }
public async Task SetPasswordTest_InvalidNewPassword() { UserDTO newUser = new UserDTO { Email = "*****@*****.**", Password = "******", FirstName = "Belford", LastName = "McAlister" }; GenericResponseDTO <int> registerResponse = await authController.Register(newUser); Assert.IsTrue(registerResponse.Success); TestAuthHelpers.attachUserToContext(registerResponse.Data, controllers); GenericResponseDTO <AccessKeysDTO> loginResponse = await authController.Login(newUser); Assert.IsTrue(loginResponse.Success); PasswordChangeDTO passwordChangeInfo = new PasswordChangeDTO { CurrentPassword = "******", NewPassword = "******" }; GenericResponseDTO <int> changePasswordResponse = await profileController.SetPassword(passwordChangeInfo); Assert.IsFalse(changePasswordResponse.Success); User currentUser = await database.Users .AsNoTracking() .FirstOrDefaultAsync(user => user.Id == registerResponse.Data); Assert.IsFalse(authHelper.GetPasswordHash("badpw", configuration).SequenceEqual(currentUser.Password)); Assert.IsTrue(authHelper.GetPasswordHash("sand_Boa13", configuration).SequenceEqual(currentUser.Password)); loginResponse = await authController.Login(newUser); Assert.IsTrue(loginResponse.Success); }
private void InitPasswordChangeModel(UserDTO currentUser) { PasswordChangeModel = new PasswordChangeDTO { UserId = currentUser.Id }; }
public async Task <IActionResult> PasswordChange([Bind("OldPassword,NewPassword,NewPasswordConfirmation")] PasswordChangeDTO passwordChange) { string userIdString = HttpContext.Session.GetString("UserId"); if (userIdString == null) { return(NotFound()); } int userId = int.Parse(userIdString); var user = await _context.Users.FindAsync(userId); if (user == null) { return(NotFound()); } if (passwordChange.OldPassword == null || passwordChange.NewPassword == null || passwordChange.NewPasswordConfirmation == null) { ViewBag.ErrorMessage = "Musisz wypełnić wszystkie pola!"; ViewBag.OldPassword = ""; ViewBag.NewPassword = ""; ViewBag.NewPasswordConfirmation = ""; return(View()); } ViewBag.OldPassword = passwordChange.OldPassword; ViewBag.NewPassword = passwordChange.NewPassword; ViewBag.NewPasswordConfirmation = passwordChange.NewPasswordConfirmation; string passwordInDB = user.Password; if (!PasswordHelper.VerifyHashedPassword(passwordInDB, passwordChange.OldPassword)) { ViewBag.ErrorMessage = "Podałeś błędne hasło!"; ViewBag.OldPassword = ""; } if (!passwordChange.NewPassword.Any(c => char.IsDigit(c))) { ViewBag.ErrorMessage = "Hasło musi zawierać przynajmniej jedną cyfrę!"; } if (passwordChange.NewPassword.IndexOfAny("!@#$%^&*?_~-£().,".ToCharArray()) == -1) { ViewBag.ErrorMessage = "Nowe hasło musi zawierać przynajmniej jeden znak specjalny!"; } if (!passwordChange.NewPassword.Any(c => char.IsUpper(c))) { ViewBag.ErrorMessage = "Nowe hasło musi zawierać małe i duże litery!"; } if (!passwordChange.NewPassword.Any(c => char.IsLower(c))) { ViewBag.ErrorMessage = "Nowe hasło musi zawierać małe i duże litery!"; } if (passwordChange.NewPassword.Length < 8) { ViewBag.ErrorMessage = "Hasło musi zawierać przynajmniej 8 znaków!"; } if (passwordChange.NewPassword != passwordChange.NewPasswordConfirmation) { ViewBag.ErrorMessage = "Podane hasła różnią się!"; ViewBag.NewPasswordConfirmation = ""; } if (ViewBag.ErrorMessage == null) { user.Password = PasswordHelper.HashPassword(passwordChange.NewPassword); _context.Update(user); await _context.SaveChangesAsync(); return(RedirectToAction("PasswordChange", new { id = 0 })); } return(View()); }
public async Task <IActionResult> ChangePassword([FromBody] PasswordChangeDTO passwordChangeModel) { try { if (!ModelState.IsValid) { _logger.LogTrace("Password change attempted with invalid model state."); return(BadRequest("Failed to change password - invalid request.")); } if (!passwordChangeModel.Password.Equals(passwordChangeModel.ConfirmPassword, StringComparison.Ordinal)) { _logger.LogInformation("Password change failed due to password mismatch."); return(BadRequest("Failed to change password - passwords do not match.")); } var user = await _unitOfWork.UserManager.FindByNameAsync(User.Identity.Name).ConfigureAwait(false); if (user == null) { _logger.LogWarning("Password change attempted by unidentified user {Model}", passwordChangeModel); return(StatusCode(500, "Password change unsuccessful.")); } var result = await _unitOfWork.UserManager.ChangePasswordAsync(user, passwordChangeModel.CurrentPassword, passwordChangeModel.Password).ConfigureAwait(false); if (!result.Succeeded) { _logger.LogWarning("Password change failed."); return(BadRequest("Failed to change password - operation failed.")); } _logger.LogInformation($"{user.UserName} changed their password successfully."); try { await RevokeAllActiveUserRefreshCookiesAsync(user).ConfigureAwait(false); _logger.LogInformation($"Active refresh tokens revoked for {user.UserName}."); } catch (InvalidOperationException ex) { _logger.LogError(ex, "Exception thrown attempting to modify refresh tokens in database."); } catch (DbUpdateConcurrencyException ex) { _logger.LogError(ex, "Exception thrown attempting to modify refresh tokens in database."); } InvalidateRefreshCookieInBrowser(); var emailData = new UsernameTemplate() { Username = user.UserName }; var emailResponse = await _emailSender .SendEmailAsync(user.Email, _config["SendGrid:Templates:PasswordChanged"], EmailFrom.Account, emailData) .ConfigureAwait(false); if (emailResponse.StatusCode != System.Net.HttpStatusCode.Accepted) { _logger.LogError($"SendGrid failed to send password change notification to {user.UserName}."); } else { _logger.LogInformation($"Password change confirmation email dispatched to {user.UserName}."); } return(NoContent()); } catch (Exception ex) { _logger.LogError(ex, "Exception thrown attempting to change password."); return(StatusCode(500, "Password change unsuccessful.")); } }