public async Task <IActionResult> ResetPassword([FromBody] ResetPasswordCommand command) { try { if (command == null) { return(await Response(null, new List <Notification> { new Notification("Reset", "Reset Inválido") })); } var contract = new AuthenticateUserCommandContract(command); if (contract.Contract.Invalid) { return(await Response(command, contract.Contract.Notifications)); } var result = _authenticateAppService.ResetarSenha(command); return(await Response(result, null)); } catch (Exception ex) { return(await Response(null, new List <Notification> { new Notification("ResetSenha", ex.Message) })); } }
public async Task <string> ResetPassword(ResetPasswordCommand request) { var user = await _userManager.FindByEmailAsync(request.Email); if (user == null) { // Don't reveal that the user does not exist return(null); } var result = await _userManager.ResetPasswordAsync(user, request.Code, request.Password); if (result.Succeeded) { _logger.LogInformation("Password reseted successfull."); return(user.Id); } else { foreach (var error in result.Errors) { await _bus.RaiseEvent(new DomainNotification(result.ToString(), error.Description)); } } return(null); }
private async Task <ResultWithError <ErrorData> > Process( ResetPasswordCommand request, CancellationToken cancellationToken) { var whenHappened = this._clock.GetCurrentInstant().ToDateTimeUtc(); var userMaybe = await this._userRepository.FindByUserBySecurityToken(request.Token, whenHappened, cancellationToken); if (userMaybe.HasNoValue) { return(ResultWithError.Fail(new ErrorData(ErrorCodes.UserNotFound))); } if (!this._passwordValidator.IsValid(request.NewPassword)) { return(ResultWithError.Fail(new ErrorData(ErrorCodes.PasswordTooWeak, "Password is to weak"))); } var user = userMaybe.Value; if (this._identitySettings.ValidatePasswordAgainstHistory && user.IsPasswordInHistory( this._identitySettings.PreviousPasswordCheck, s => this._passwordHasher.ValidatePassword(request.NewPassword, s))) { return(ResultWithError.Fail(new ErrorData(ErrorCodes.PasswordInHistory))); } user.ChangePasswordAndAddToHistory( this._passwordHasher.HashPassword(request.NewPassword), whenHappened); user.CompleteTokenLifecycle(request.Token, whenHappened); this._userRepository.Update(user); return(ResultWithError.Ok <ErrorData>()); }
public async Task ResetPasswordAsync(ResetPasswordCommand command) { var user = await _context.Users .FirstOrDefaultAsync(x => x.PasswordResetToken == command.Token); if (user == null) { throw new GfsException(ErrorCode.UserNotFound, _dictionary.UserNotFound); } if (command.NewPassword == null) { throw new GfsException(ErrorCode.EmptyPassword, _dictionary.EmptyPassword); } var hash = _userManager.PasswordHasher.HashPassword(user, command.NewPassword); if (hash == null) { throw new GfsException(ErrorCode.ChangePasswordFailed, _dictionary.EmptyPassword); } user.PasswordHash = hash; user.PasswordResetToken = null; await _context.SaveChangesAsync(); }
public async Task <IActionResult> ResetPassword( [FromQuery] string token, [FromBody] ResetPasswordCommand command) { command.Token = token; return(Ok(await _mediator.Send(command))); }
public async Task <IActionResult> ResetPassword(ResetPasswordCommand request) { if (this.User.Identity.IsAuthenticated && this.User.Identity.Name?.Trim().ToLower() != request.Email?.Trim().ToLower()) { return(this.RedirectToHomeIndex()); } try { var requestResult = await this.Mediator.Send(request); if (requestResult.Succeeded) { return(await this.RedirectToSucceededExecutionResultAsync( Titles.ResetPasswordSuccess, Messages.ResetPasswordSuccessMessage, "reset-password")); } else { this.ModelState.AddModelError(string.Empty, Messages.YourPasswordCannotBeReset); } } catch (ValidationException ex) { this.ModelState.ApplyValidationException(ex); } catch (Exception) { this.ModelState.AddModelError(string.Empty, Messages.YourPasswordCannotBeReset); } return(this.ResetPasswordView(request)); }
public async Task <IActionResult> OnPostAsync([FromBody] ResetPasswordDto dto) { if (!ModelState.IsValid) { return(await Task.FromResult(new JsonResult(new { Status = false, ErrorMessage = ModelState.Where(e => e.Value.Errors.Count > 0).Select(e => e.Value.Errors.First().ErrorMessage).First() }))); } var userId = _accountContext.UserId; var command = new ResetPasswordCommand(dto.Email, dto.Password, dto.Code); await _bus.SendCommand(command); if (_notifications.HasNotifications()) { var errorMessage = string.Join(";", _notifications.GetNotifications().Select(x => x.Content)); return(await Task.FromResult(new JsonResult(new { status = false, errorMessage }))); } return(await Task.FromResult(new JsonResult(new { status = true }))); }
public void IsInvalidWhen_MatchesNoEntity() { var command = new ResetPasswordCommand { Token = Guid.NewGuid() }; var scenarioOptions = new ScenarioOptions { Command = command, EmailConfirmation = new EmailConfirmation(EmailConfirmationIntent.CreatePassword), }; var validator = CreateValidator(scenarioOptions); var results = validator.Validate(command); results.IsValid.ShouldBeFalse(); results.Errors.Count.ShouldBeInRange(1, int.MaxValue); var error = results.Errors.SingleOrDefault(e => e.PropertyName == "Token"); error.ShouldNotBeNull(); // ReSharper disable PossibleNullReferenceException error.ErrorMessage.ShouldEqual(string.Format( ValidateEmailConfirmation.FailedBecauseTokenMatchedNoEntity, command.Token)); // ReSharper restore PossibleNullReferenceException }
public ICommandResult Handle(ResetPasswordCommand command) { // Fail Fast Validation command.Validate(); if (command.Invalid) { return(new GenericCommandResult(false, "Não foi possível atualizar o usuário!", command.Notifications)); } var user = _userRepository.GetByEmail(command.Email); if (user == null) { return(new GenericCommandResult(false, "Não foi possível alterar a senha, e-mail não existente!", command.Notifications)); } // Descriptografia da senha para validar var passwordDecrypt = _encryption.Decrypt(user.Password); // Compara senha do command de entrada com a senha do banco if (passwordDecrypt != command.Oldpassword) { return(new GenericCommandResult(false, "Não foi possível alterar a senha, antiga senha não confere!", command.Notifications)); } // Descriptografia da senha para validar o acesso var newPasswordEncrypt = _encryption.Encrypt(command.Password); user.UpdatePassword(newPasswordEncrypt); _userRepository.Update(user); return(new GenericCommandResult(true, "Senha alterada com sucesso", null)); }
public void IsInvalidWhen_MatchesUnintendedEntity() { var confirmation = new EmailConfirmation(EmailConfirmationIntent.CreatePassword) { ExpiresOnUtc = DateTime.UtcNow.AddMinutes(-1), }; var command = new ResetPasswordCommand { Token = confirmation.Token, }; var scenarioOptions = new ScenarioOptions { EmailConfirmation = confirmation, Command = command, }; var validator = CreateValidator(scenarioOptions); var results = validator.Validate(command); results.IsValid.ShouldBeFalse(); results.Errors.Count.ShouldBeInRange(1, int.MaxValue); var error = results.Errors.SingleOrDefault(e => e.PropertyName == "Token"); error.ShouldNotBeNull(); // ReSharper disable PossibleNullReferenceException error.ErrorMessage.ShouldEqual(string.Format( ValidateEmailConfirmation.FailedBecauseIntentWasIncorrect, confirmation.Intent, confirmation.Token)); // ReSharper restore PossibleNullReferenceException }
public async Task <ActionResult> ResetPassword(ResetPasswordCommand command) { if (!ModelState.IsValid) { return(View(command)); } var user = await signInManager.UserManager.FindByNameAsync(command.Email); if (user == null) { // Don't reveal that the user does not exist return(RedirectToAction("ResetPasswordConfirmation", "Account")); } var result = await signInManager.UserManager.ResetPasswordAsync(user.Id, command.Code, command.NewPassword); if (result.Succeeded) { return(RedirectToAction("ResetPasswordConfirmation", "Account")); } foreach (var error in result.Errors) { ModelState.AddModelError(string.Empty, error); } return(View()); }
public async Task <IActionResult> Reset(ResetPasswordCommand command) { if (!ModelState.IsValid) { return(View(command)); } var response = await this.Mediator.Send(command); if (response.IsFailure) { ModelState.AddModelErrors(response.Errors); command.NewPassword = string.Empty; command.ConfirmNewPassword = string.Empty; return(View(command)); } return(RedirectToAction("Result", new ResultViewModel { IsSuccess = true, Title = "Reset Password", Description = "You can reset your password", Messages = new List <string>() { "You're password has been successfully changed!" } })); }
public AuthenticateUserCommandContract(ResetPasswordCommand command) { Contract = new ValidationContract() .Requires() .IsNotNullOrEmpty(command.Token, "Token", "O campo Token é obrigatório") .IsNotNullOrEmpty(command.Senha, "Password", "O campo Password é obrigatório") .HasMinLen(command.Senha, 6, "Password", "O campo Password precisa ter no mínimo 6 caracteres"); }
public void TokenIsNullOrEmpty_ShouldHaveError(string passwordToken) { var command = new ResetPasswordCommand { PasswordToken = passwordToken }; _sut.ShouldHaveValidationErrorFor(x => x.PasswordToken, command); }
public void ConfirmNewPasswordIsNullOrEmpty_ShouldHaveError(string confirmNewPassword) { var command = new ResetPasswordCommand { ConfirmNewPassword = confirmNewPassword }; _sut.ShouldHaveValidationErrorFor(x => x.ConfirmNewPassword, command); }
public void PasswordAndConfirmPasswordDoNotMatch_ShouldHaveError() { var command = new ResetPasswordCommand { NewPassword = "******", ConfirmNewPassword = "******" }; _sut.ShouldHaveValidationErrorFor(x => x.NewPassword, command); }
public override async Task <AccountId> ResetPassword(People.Grpc.Common.Identity request, ServerCallContext context) { var command = new ResetPasswordCommand(request.ToIdentityKey(), _language); var data = await _mediator.Send(command, context.CancellationToken); return(data.ToAccountId()); }
public async Task <ApiResult> ResetPassword([FromBody] ResetPasswordCommand command) { var rs = await mediator.Send(command); return(new ApiResult() { Result = rs }); }
public void SetUp() { passwordManager = new Mock <IResetPasswordManager>(); cryptoService = new Mock <ICryptoService>(); cryptoService.Setup(cs => cs.Decrypt(It.IsAny <string>())) .Returns("test"); resetPasswordCommand = new(passwordManager.Object, cryptoService.Object); }
public async Task WhenISubmitAResetPasswordRequestWithValidProperties() { _command = new ResetPasswordCommand { PasswordToken = _user.PasswordToken, NewPassword = "******", ConfirmNewPassword = "******" }; _response = await _client.PostAsync(BaseUrl, Utilities.GetRequestContent(_command)); }
public async Task <IActionResult> ResetPassword([FromBody] ResetPasswordCommand command) { if (!ModelState.IsValid) { return(BadRequest()); } await _userService.ResetPasswordAsync(command); return(Ok(ResponseDto.Default)); }
private HttpContent GetHttpContent <T>(ResetPasswordCommand <T> command) { var requestBody = new { Version = command.Version, TokenValue = command.TokenValue, NewPassword = command.NewPassword }; return(new StringContent(this.serializerService.Serialize(requestBody))); }
public async Task WhenISubmitAResetPasswordRequestWithAnInvalidPasswordResetToken() { _command = new ResetPasswordCommand { PasswordToken = "Invalid Password token", NewPassword = "******", ConfirmNewPassword = "******" }; _response = await _client.PostAsync(BaseUrl, Utilities.GetRequestContent(_command)); }
public async Task WhenISubmitAResetPasswordRequestWithAConfirmPasswordThatDoesNotMatchThePassword() { _command = new ResetPasswordCommand { PasswordToken = "Password token", NewPassword = "******", ConfirmNewPassword = "******" }; _response = await _client.PostAsync(BaseUrl, Utilities.GetRequestContent(_command)); }
public async Task WhenISubmitAResetPasswordRequestWithAnEmptyOrANullConfirmNewPassword(string confirmNewPassword) { _command = new ResetPasswordCommand { PasswordToken = "Password token", NewPassword = "******", ConfirmNewPassword = confirmNewPassword }; _response = await _client.PostAsync(BaseUrl, Utilities.GetRequestContent(_command)); }
public async Task HandleAsync_Should_Reset_Password() { var resetPasswordCommand = new ResetPasswordCommand("*****@*****.**", "123456", "Password"); var token = Token.Builder() .SetIssued(DateTimeOffset.UtcNow) .SetExpires(DateTimeOffset.UtcNow.AddDays(1)) .SetType(TokenTypeEnumeration.PasswordReset) .SetValue(resetPasswordCommand.Code) .Build(); var account = Account.Builder() .SetId(Guid.NewGuid()) .SetEmail(resetPasswordCommand.Email) .SetConfirmed(false) .SetPasswordHash("PasswordHash") .SetSecurityStamp(Guid.NewGuid()) .SetCreated(DateTimeOffset.UtcNow) .SetRoles(new List <Guid> { Guid.NewGuid() }) .SetTokens(new List <Token> { token }) .Build(); var getAccountResult = GetResult <Account> .Ok(account); var accountIsConfirmedVerificationResult = VerificationResult.Ok(); var passwordIsSetVerificationResult = VerificationResult.Ok(); var tokenIsCorrectVerificationResult = VerificationResult.Ok(); const string newPasswordHash = "NewPasswordHash"; var cancellationToken = new CancellationToken(); _accountGetterServiceMock.Setup(x => x.GetByEmailAsync(It.IsAny <string>())) .ReturnsAsync(getAccountResult); _accountVerificationServiceMock.Setup(x => x.VerifyAccountIsConfirmed(It.IsAny <bool>())) .Returns(accountIsConfirmedVerificationResult); _accountVerificationServiceMock.Setup(x => x.VerifyPasswordIsSet(It.IsAny <string>())) .Returns(passwordIsSetVerificationResult); _accountVerificationServiceMock.Setup(x => x.VerifyConfirmationCode(It.IsAny <Token>(), It.IsAny <string>())) .Returns(tokenIsCorrectVerificationResult); _passwordServiceMock.Setup(x => x.HashPassword(It.IsAny <string>())).Returns(newPasswordHash); _communicationBusMock.Setup(x => x.DispatchDomainEventsAsync(It.IsAny <Account>(), It.IsAny <CancellationToken>())) .Returns(Task.CompletedTask); _accountRepositoryMock.Setup(x => x.UpdateAsync(It.IsAny <Account>())).Returns(Task.CompletedTask); Func <Task> result = async() => await _commandHandler.HandleAsync(resetPasswordCommand, cancellationToken); await result.Should().NotThrowAsync <Exception>(); account.PasswordHash.Should().Be(newPasswordHash); account.Tokens.Should().NotContain(token); _communicationBusMock.Verify( x => x.DispatchDomainEventsAsync(It.Is <Account>(a => a == account), It.Is <CancellationToken>(ct => ct == cancellationToken)), Times.Once); }
public async Task <IActionResult> ResetPassword([FromBody] ResetPasswordCommand resetPasswordCommand) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } var result = await _mediator.Send(resetPasswordCommand); return(StatusCodeResult(result)); }
public async Task <IActionResult> ResetPassword(ResetPasswordRequest model, CancellationToken cancellationToken) { var command = new ResetPasswordCommand() { Token = model.Token, Password = model.Password }; await _commandProcessor.SendAsync(command, cancellationToken : cancellationToken); return(Ok()); }
public static int ResetPassword(string newPassword, int Code, string Email) { ResetPasswordCommand command = new ResetPasswordCommand(); command.EMail = Email; command.NewHash = TCPManager.Hash(newPassword); command.Code = Code; ResultWithNoData result = JsonConvert.DeserializeObject <ResultWithNoData>(TCPManager.SendRequest(JsonConvert.SerializeObject(command))); return(result.statusCode); }
public async Task <IActionResult> ResetPassword([FromServices] ResetPasswordCommand command) { var result = await _handler.Handler(command); if (result.Succeeded) { result.Message = _localizer["RESET_PASSWORD_SUCCESS"].Value; return(Ok(result)); } result.Message = _localizer["RESET_PASSWORD_FAILED"].Value; return(BadRequest(result)); }
public async Task <CommandResult> Handler(ResetPasswordCommand command) { if (command.Invalid) { return(new CommandResult(false, "Error to find user", command.Notifications)); } var user = await _userRepository.FindByEmail(command.Email); return(user == null ? new CommandResult(false, "user not found.", null) : new CommandResult(true, "Generate token", new ResetPasswordCommandResponse(user.Id.ToString(), ""))); }
public void ValidCommandData_ShouldNotHaveError() { var command = new ResetPasswordCommand { PasswordToken = "token", NewPassword = "******", ConfirmNewPassword = "******" }; _sut.ShouldNotHaveValidationErrorFor(x => x.PasswordToken, command); _sut.ShouldNotHaveValidationErrorFor(x => x.NewPassword, command); _sut.ShouldNotHaveValidationErrorFor(x => x.ConfirmNewPassword, command); }
public void IsValidWhen_MatchesEntity_Intended_Unexpired_Unretired_Redeemed_WithNonSamlLocalUser() { var confirmation = new EmailConfirmation(EmailConfirmationIntent.ResetPassword) { ExpiresOnUtc = DateTime.UtcNow.AddMinutes(1), RedeemedOnUtc = DateTime.UtcNow, EmailAddress = new EmailAddress { IsConfirmed = true, Person = new Person { User = new User { Name = "local" } } } }; var command = new ResetPasswordCommand { Token = confirmation.Token, }; var scenarioOptions = new ScenarioOptions { Command = command, EmailConfirmation = confirmation, LocalMemberExists = true, }; var validator = CreateValidator(scenarioOptions); var results = validator.Validate(command); var error = results.Errors.SingleOrDefault(e => e.PropertyName == "Token"); error.ShouldBeNull(); }
public void IsInvalidWhen_IsIncorrectMatch() { var confirmation = new EmailConfirmation(EmailConfirmationIntent.ResetPassword) { Ticket = "ticket1", }; var command = new ResetPasswordCommand { Token = confirmation.Token, Ticket = "ticket2", }; var scenarioOptions = new ScenarioOptions { EmailConfirmation = confirmation, Command = command, }; var validator = CreateValidator(scenarioOptions); var results = validator.Validate(command); results.IsValid.ShouldBeFalse(); results.Errors.Count.ShouldBeInRange(1, int.MaxValue); var error = results.Errors.SingleOrDefault(e => e.PropertyName == "Ticket"); error.ShouldNotBeNull(); // ReSharper disable PossibleNullReferenceException error.ErrorMessage.ShouldEqual(string.Format( ValidateEmailConfirmation.FailedBecauseTicketWasIncorrect, command.Ticket, confirmation.Token)); // ReSharper restore PossibleNullReferenceException }
public void IsValidWhen_IsNotEmpty_AndIsCorrectMatch() { var confirmation = new EmailConfirmation(EmailConfirmationIntent.ResetPassword) { Ticket = "tomato", }; var command = new ResetPasswordCommand { Token = confirmation.Token, Ticket = "tomato" }; var scenarioOptions = new ScenarioOptions { EmailConfirmation = confirmation, Command = command, }; var validator = CreateValidator(scenarioOptions); var results = validator.Validate(command); var error = results.Errors.SingleOrDefault(e => e.PropertyName == "Ticket"); error.ShouldBeNull(); }
public void IsValidWhen_IsNotEmpty_AndConfirmationWasNull() { var command = new ResetPasswordCommand { Ticket = "test" }; var scenarioOptions = new ScenarioOptions(); var validator = CreateValidator(scenarioOptions); var results = validator.Validate(command); var error = results.Errors.SingleOrDefault(e => e.PropertyName == "Ticket"); error.ShouldBeNull(); }
public void IsInvalidWhen_IsEmptyString() { var command = new ResetPasswordCommand { Password = string.Empty }; var scenarioOptions = new ScenarioOptions(); var validator = CreateValidator(scenarioOptions); var results = validator.Validate(command); results.IsValid.ShouldBeFalse(); results.Errors.Count.ShouldBeInRange(1, int.MaxValue); var error = results.Errors.SingleOrDefault(e => e.PropertyName == "Password"); error.ShouldNotBeNull(); // ReSharper disable PossibleNullReferenceException error.ErrorMessage.ShouldEqual( ValidatePassword.FailedBecausePasswordWasEmpty); // ReSharper restore PossibleNullReferenceException }
public void IsInvalidWhen_Length_IsLessThanSixCharacters() { var command = new ResetPasswordCommand { Password = "******" }; var scenarioOptions = new ScenarioOptions { MinimumPasswordLength = 6, }; var validator = CreateValidator(scenarioOptions); var results = validator.Validate(command); results.IsValid.ShouldBeFalse(); results.Errors.Count.ShouldBeInRange(1, int.MaxValue); var error = results.Errors.SingleOrDefault(e => e.PropertyName == "Password"); error.ShouldNotBeNull(); // ReSharper disable PossibleNullReferenceException error.ErrorMessage.ShouldEqual( ValidatePassword.FailedBecausePasswordWasTooShort(6)); // ReSharper restore PossibleNullReferenceException }
public void IsValidWhen_Length_IsSixCharactersOrMore() { var command = new ResetPasswordCommand { Password = "******" }; var scenarioOptions = new ScenarioOptions(); var validator = CreateValidator(scenarioOptions); var results = validator.Validate(command); var error = results.Errors.SingleOrDefault(e => e.PropertyName == "Password"); error.ShouldBeNull(); }
public void IsInvalidWhen_DoesNotEqualPassword_AndPasswordIsValid() { var command = new ResetPasswordCommand { Password = "******", PasswordConfirmation = "12345", }; var scenarioOptions = new ScenarioOptions(); var validator = CreateValidator(scenarioOptions); var results = validator.Validate(command); results.IsValid.ShouldBeFalse(); results.Errors.Count.ShouldBeInRange(1, int.MaxValue); var error = results.Errors.SingleOrDefault(e => e.PropertyName == "PasswordConfirmation"); error.ShouldNotBeNull(); // ReSharper disable PossibleNullReferenceException error.ErrorMessage.ShouldEqual( ValidatePassword.FailedBecausePasswordConfirmationDidNotEqualPassword); // ReSharper restore PossibleNullReferenceException }
public void IsValidWhen_EqualsPassword_AndPasswordIsValid() { var command = new ResetPasswordCommand { Password = "******", PasswordConfirmation = "123456", }; var scenarioOptions = new ScenarioOptions(); var validator = CreateValidator(scenarioOptions); var results = validator.Validate(command); results.IsValid.ShouldBeFalse(); results.Errors.Count.ShouldBeInRange(1, int.MaxValue); var error = results.Errors.SingleOrDefault(e => e.PropertyName == "PasswordConfirmation"); error.ShouldBeNull(); }
public void IsInvalidWhen_MatchesUser_WithNoLocalAccount() { var confirmation = new EmailConfirmation(EmailConfirmationIntent.ResetPassword) { RedeemedOnUtc = DateTime.UtcNow, ExpiresOnUtc = DateTime.UtcNow.AddMinutes(1), EmailAddress = new EmailAddress { IsConfirmed = true, Person = new Person { User = new User { Name = "something", } } } }; var command = new ResetPasswordCommand { Token = confirmation.Token, }; var scenarioOptions = new ScenarioOptions { EmailConfirmation = confirmation, Command = command, }; var validator = CreateValidator(scenarioOptions); var results = validator.Validate(command); results.IsValid.ShouldBeFalse(); results.Errors.Count.ShouldBeInRange(1, int.MaxValue); var error = results.Errors.SingleOrDefault(e => e.PropertyName == "Token"); error.ShouldNotBeNull(); // ReSharper disable PossibleNullReferenceException error.ErrorMessage.ShouldEqual(string.Format( ValidateUser.FailedBecauseNameMatchedNoLocalMember, confirmation.EmailAddress.Person.User.Name)); // ReSharper restore PossibleNullReferenceException }