public async Task SetPassword_ReturnTrue_IfCorrect() { //Arrange var updateUser = new UpdateUserPasswordDto() { EncodePassword = "******", ConfirmEncodePassword = "******", CodeOfVerification = "23432knksjcnfi2" }; mockUsersRepository .Setup(p => p.FindByCodeOfVerification(updateUser.CodeOfVerification)) .ReturnsAsync(new User()); mockUsersRepository .Setup(p => p.Create(It.IsAny <User>())) .Verifiable(); mockUsersRepository .Setup(p => p.SaveChangesAsync()) .Returns(Task.CompletedTask); var emailService = new Mock <IEmailServices>(); emailService .Setup(p => p.EmailAfterRegistration(It.IsAny <CreateUserDto>())) .Returns(true); var tokenService = new Mock <ITokenGeneratorService>(); var services = new AuthorizationService(mockUsersRepository.Object, emailService.Object, mapper, tokenService.Object, mockRefreshRepository.Object); //Act var result = await services.SetPasswordAsync(updateUser); //Assert Assert.True(result); }
public void UpdatePassword(string userName, UpdateUserPasswordDto updateUserPasswordDto) { userName.ThrowExceptionIfNullOrEmpty("userName"); updateUserPasswordDto.Password.ThrowExceptionIfNullOrEmpty("updateUserPasswordDto.Password"); _blaiseApi.UpdatePassword(userName, updateUserPasswordDto.Password); }
public async Task UpdatePasswordAsync(UpdateUserPasswordDto userUpdatePasswordDto, string idUser) { if (userUpdatePasswordDto.OldPassword.Equals(userUpdatePasswordDto.NewPassword)) { throw new AppException("The old password is the same as the new password. Then the password does not need to be changed."); } var user = _context.Users.Find(idUser); if (user == null) { throw new AppException("User not found"); } if (_passwordHasher.VerifyHashedPassword(user, user.PasswordHash, userUpdatePasswordDto.OldPassword) != PasswordVerificationResult.Success) { throw new AppException("OldPassword wrong!"); } var result = await _userManager.ChangePasswordAsync(user, userUpdatePasswordDto.OldPassword, userUpdatePasswordDto.NewPassword); if (!result.Succeeded) { throw new AppException("Um problema alterar a password!"); } }
public async Task <IActionResult> SetPasswordAsync(UpdateUserPasswordDto updateUserPassword) { if (!await authorizationService.SetPasswordAsync(updateUserPassword)) { return(NotFound(resourcesManager.GetString("CodeVerification"))); } return(Ok()); }
public IHttpActionResult UpdatePassword([FromUri] string userName, [FromBody] UpdateUserPasswordDto passwordDto) { _loggingService.LogInfo($"Attempting to update password for user '{userName}'"); _userService.UpdatePassword(userName, passwordDto); _loggingService.LogInfo($"Successfully updated password for user '{userName}'"); return(NoContent()); }
public async Task <IActionResult> UpdateUserPassword(UpdateUserPasswordDto item) { if (!ModelState.IsValid) { return(BadRequest(new ModelStateResult(ModelState))); } var updateUserPasswordResultDto = await _usersService.UpdateUserPassword(item, UserId); return(Ok(updateUserPasswordResultDto)); }
/// <summary> /// Set Password return true if hash generated correct /// and Save to database /// </summary> /// <param name="updateUserPassword"></param> /// <returns></returns> public async Task <bool> SetPasswordAsync(UpdateUserPasswordDto updateUserPassword) { var user = await userRepository.FindByCodeOfVerificationAsync(updateUserPassword.CodeOfVerification); var saltHashPassword = GenerateSaltedHash(16, updateUserPassword.EncodePassword); user.SetPassword(saltHashPassword.Hash, saltHashPassword.Salt); userRepository.Update(user); await userRepository.SaveChangesAsync(); return(true); }
public void Given_An_Empty_Password_When_I_Call_UpdatePassword_Then_An_ArgumentException_Is_Thrown() { //arrange var updatePasswordDto = new UpdateUserPasswordDto { Password = string.Empty }; //act && assert var exception = Assert.Throws <ArgumentException>(() => _sut.UpdatePassword(_userName, updatePasswordDto)); Assert.AreEqual("A value for the argument 'updateUserPasswordDto.Password' must be supplied", exception.Message); }
public void Given_A_Null_Password_When_I_Call_UpdatePassword_Then_An_ArgumentNullException_Is_Thrown() { //arrange var updatePasswordDto = new UpdateUserPasswordDto { Password = null }; //act && assert var exception = Assert.Throws <ArgumentNullException>(() => _sut.UpdatePassword(_userName, updatePasswordDto)); Assert.AreEqual("updateUserPasswordDto.Password", exception.ParamName); }
public void Given_Valid_Arguments_When_I_Call_UpdatePassword_Then_The_Correct_Service_Method_Is_Called() { //arrange var updatePasswordDto = new UpdateUserPasswordDto { Password = _password }; //act _sut.UpdatePassword(_userName, updatePasswordDto); //assert _blaiseApiMock.Verify(v => v.UpdatePassword(_userName, _password), Times.Once); }
public async Task <IActionResult> SetPassword([FromBody] UpdateUserPasswordDto dto, Guid id) { var cmd = new UpdateUserPasswordCommand { NewPassword = dto.Password, UserId = id }; var result = await _sagaBus.InvokeAsync <UpdateUserPasswordCommand, MessageResult>(cmd); if (result.Succeed) { return(Created(Url.Action(), null)); } //if user doesn't exist. return(BadRequest(result.Message)); }
public async Task <IActionResult> UpdatePassword([FromForm] UpdateUserPasswordDto dto) { if (!ModelState.IsValid) { return(UnprocessableEntity(ModelState)); } var result = await userManager.ChangePasswordAsync(await userManager.GetUserAsync(User), dto.OldPassword, dto.NewPassword); if (!result.Succeeded) { return(BadRequest()); } return(NoContent()); }
public async Task <IActionResult> UpdateMyPassword([FromBody] UpdateUserPasswordDto dto) { string userIndentifier = _httpContextAccessor.HttpContext.User.FindFirstValue(ClaimTypes.NameIdentifier); if (userIndentifier == null) { return(Forbid()); } var response = await _userAuth.UpdateUserPasswordAsync(userIndentifier, dto); if (response.Success) { return(Ok(response)); } return(BadRequest(response)); }
public IActionResult UpdatePassword(int id, [FromBody] UpdateUserPasswordDto updateUserPasswordDto) { // map dto to entity and set id var user = _mapper.Map <User>(updateUserPasswordDto); user.Id = id; try { // save _userService.UpdatePassword(user, updateUserPasswordDto.NewPassword); return(Ok(new { message = "Password alterada com sucesso!" })); } catch (AppException ex) { // return error message if there was an exception return(BadRequest(new { message = ex.Message })); } }
public async Task <IActionResult> UpdatePassword(string id, [FromBody] UpdateUserPasswordDto updateUserPasswordDto) { try { if (!ModelState.IsValid) { return(BadRequest(ModelState.Values.SelectMany(v => v.Errors).Select(modelError => modelError.ErrorMessage).ToList())); } // save await _accountService.UpdatePasswordAsync(updateUserPasswordDto, id); return(Ok(new { message = "Password alterada com sucesso!" })); } catch (AppException ex) { // return error message if there was an exception return(BadRequest(new { message = ex.Message })); } }
public async Task <UpdateUserPasswordResultDto> UpdateUserPassword(UpdateUserPasswordDto updateUserPasswordDto, int userId) { var user = await _usersRepository.GetAsync(userId); if (user == null) { throw new ValidationException(Messages.UserDoesNotExist, nameof(Messages.UserDoesNotExist)); } if (user.Password != _securityService.HashPassword(updateUserPasswordDto.OldPassword)) { throw new ValidationException(Messages.UpdateUserPasswordIncorrectOldPassword, nameof(Messages.UpdateUserPasswordIncorrectOldPassword)); } user.Password = _securityService.HashPassword(updateUserPasswordDto.Password); await _usersRepository.UpdateAsync(user); return(new UpdateUserPasswordResultDto()); }
public PmsResponseDto UpdatePassword([FromBody] UpdateUserPasswordDto request) { if (request == null || request.UserId <= 0) { throw new PmsException("User can not be updated."); } var response = new PmsResponseDto(); if (_iPmsLogic.UpdatePassword(request)) { response.ResponseStatus = PmsApiStatus.Success.ToString(); response.StatusDescription = "Record(s) saved successfully."; } else { response.ResponseStatus = PmsApiStatus.Failure.ToString(); response.StatusDescription = "Operation failed.Please contact administrator."; } return(response); }
public async Task <IActionResult> UpdatePassword(UpdateUserPasswordDto updateUserPasswordDto) { var user = await userManager.FindByIdAsync(updateUserPasswordDto.UserId); if (user != null) { var token = await userManager.GeneratePasswordResetTokenAsync(user); var updateResult = await userManager.ResetPasswordAsync(user, token, updateUserPasswordDto.NewPassword); if (updateResult.Succeeded) { return(Ok()); } else { return(BadRequest()); } } return(BadRequest()); }
public async Task <ServiceResponse <UpdateUserPasswordDto> > UpdateUserPasswordAsync(string userEmail, UpdateUserPasswordDto dto) { var response = new ServiceResponse <UpdateUserPasswordDto>(); try { var dbUser = await _context.Users.FirstOrDefaultAsync(x => x.Email == userEmail); if (dbUser == null) { throw new UserNotFoundException(); } bool isMatchPassword = ComparePassword(dto.currentPassword, dbUser.Password, dbUser.PasswordSalt); if (!isMatchPassword) { throw new PasswordMismatchException(); } (dbUser.Password, dbUser.PasswordSalt) = CreateHashedPassword(dto.newPassword); _context.Users.Update(dbUser); await _context.SaveChangeWithValidationAsync(); response.Data = dto; return(response); } catch (BaseServiceException ex) { response.Success = false; response.Message = ex.ErrorMessage; response.Code = ex.Code; _logger.LogError(ex.Message, ex.StackTrace); return(response); } catch (Exception ex) { response.Success = false; response.Message = ex.Message; response.Code = ErrorCode.AUTH_UNEXPECTED_ERROR; _logger.LogError(ex.Message, ex.StackTrace); return(response); } }
/// <summary> /// 修改密码 /// </summary> /// <param name="id"></param> /// <param name="password"></param> /// <returns></returns> internal async Task <BaseResponse> ResetPasswordAsync(UpdateUserPasswordDto resetUserPasswordDto) { return(await HttpRequestWithValidate($"api/client/user/UpdatePassword", HttpMethod.Patch, resetUserPasswordDto.BuildHttpContent())); }
public async Task <ActionResult <ResponseDto <UserResponseDto> > > UpdatePassword([FromBody] UpdateUserPasswordDto updateUserPasswordDto, [FromRoute] string id) { var user = await _userManager.FindUserByEmailAsyncFromClaimsPrincipal(HttpContext.User); if (user == null) { return(NotFound(new ResponseDto <string> { Success = false, Data = null, Error = new ApiErrorResponse(404) })); } if (user.Id != id) { return(StatusCode(403, new ResponseDto <string> { Success = false, Data = null, Error = new ApiErrorResponse(403) })); } var result = await _userManager.ChangePasswordAsync(user, updateUserPasswordDto.CurrentPassword, updateUserPasswordDto.NewPassword); if (!result.Succeeded) { return(BadRequest(new ResponseDto <string> { Success = false, Data = null, Error = new ApiErrorResponse(400) })); } return(new ResponseDto <UserResponseDto> { Success = true, Data = new UserResponseDto { User = _mapper.Map <AppUser, UserDto>(user), Token = new TokenDto { Token = _tokenService.CreateToken(user) }, }, Error = new ApiErrorResponse() }); }
/// <summary> /// Updates the user password for the provided Username and Tenancy Name. /// This endpoint is intended to be used via API to update the first login /// password. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='updatePasswordParameters'> /// </param> public static void UpdatePassword(this IUsers operations, UpdateUserPasswordDto updatePasswordParameters) { operations.UpdatePasswordAsync(updatePasswordParameters).GetAwaiter().GetResult(); }
/// <summary> /// Updates the user password for the provided Username and Tenancy Name. /// This endpoint is intended to be used via API to update the first login /// password. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='updatePasswordParameters'> /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task UpdatePasswordAsync(this IUsers operations, UpdateUserPasswordDto updatePasswordParameters, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { (await operations.UpdatePasswordWithHttpMessagesAsync(updatePasswordParameters, null, cancellationToken).ConfigureAwait(false)).Dispose(); }
public bool UpdatePassword(UpdateUserPasswordDto request) { return(DalFactory.UpdatePassword(request.UserId, request.CurrentPassword, request.NewPassword)); }