public async Task <IActionResult> ForgotPassword([FromBody] ForgotPasswordCommand request)
        {
            if (this.User.Identity.IsAuthenticated)
            {
                return(this.BadRequest());
            }

            try
            {
                var requestResult = await this.Mediator.Send(request);

                if (requestResult.Succeeded)
                {
                    return(this.Ok());
                }
                else
                {
                    await this.Logger.LogErrorAsync(new ArgumentException($"Invalid email ({request.Email}) from reset password form."));

                    return(this.Ok());
                }
            }
            catch (ValidationException ex)
            {
                this.ModelState.ApplyValidationException(ex);
            }
            catch (Exception)
            {
                this.ModelState.AddModelError(string.Empty, Messages.YourRequestCannotBeExecuted);
            }

            return(this.BadRequestWithModelErrors());
        }
Ejemplo n.º 2
0
        public async Task <IActionResult> ForgotPassword(ForgotPasswordCommand request)
        {
            if (this.User.Identity.IsAuthenticated)
            {
                return(this.RedirectToHomeIndex());
            }

            try
            {
                var result = await this.Mediator.Send(request);

                if (!result.Succeeded)
                {
                    await this.Logger.LogErrorAsync(new ArgumentException($"Invalid email ({request.Email}) from reset password form."));
                }

                return(await this.RedirectToSucceededExecutionResultAsync(
                           Titles.ForgotPasswordSuccess,
                           Messages.ForgotPasswordSuccessMessage,
                           "forgot-password"));
            }
            catch (ValidationException ex)
            {
                this.ModelState.ApplyValidationException(ex);
            }
            catch (Exception)
            {
                this.ModelState.AddModelError(string.Empty, Messages.YourPasswordCannotBeReset);
            }

            return(this.ForgotPasswordView(request));
        }
Ejemplo n.º 3
0
        public ICommandResult Handle(ForgotPasswordCommand command)
        {
            // Fail Fast Validation
            command.Validate();
            if (command.Invalid)
            {
                return(new GenericCommandResult(false, "Não foi possível lembrar a senha!", command.Notifications));
            }

            var user = _userRepository.GetByEmail(command.Email);

            if (user == null)
            {
                return(new GenericCommandResult(false, "Não foi possível lembrar a senha, e-mail não existente!", command.Notifications));
            }

            var passwordDecrypt = _encryption.Decrypt(user.Password);

            // Envio do email
            _email.Send("*****@*****.**", user.Email, "Solicitação de Senha", "sua senha é " + passwordDecrypt);

            IList <object> objReturnPassword = new List <object>()
            {
                new { nome = "FAKE: Senha enviada no email informado.", value = passwordDecrypt }
            };

            return(new GenericCommandResult(true, "Senha recuperada com sucesso", objReturnPassword));
        }
Ejemplo n.º 4
0
        public async Task <ICommandResult> Handler(ForgotPasswordCommand command)
        {
            try
            {
                User user = await _service.GetByEmailAsync(command.Email);

                if (user == null)
                {
                    return(new CommandResult(false, Messages.USER_NOT_FOUND, null));
                }

                string token = await _service.ForgotPasswordAsync(user);

                string message = await _service.CreateMessageForgotPassword(user.Email, token);

                SmtpStatusCode status = await _service.SendAsync(user.Email, message, "Reset Password");

                if (status == SmtpStatusCode.GeneralFailure)
                {
                    return(new CommandResult(false, Messages.FORGOT_PASSWORD_FAILED, null));
                }

                return(new CommandResult(true, Messages.FORGOT_PASSWORD_SUCCESS, null));
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
Ejemplo n.º 5
0
        public void ForgotPassword(ForgotPasswordCommand command)
        {
            var user = UserRepository.GetByEmail(command.Email);

            AssertConcern.AssertArgumentNotNull(user, "Usuário não encontrado");

            var passwordKey = UserService.GeneratePasswordKey(user);

            UserRepository.SavePasswordKey(user.UserId, passwordKey);

            var sB = new StringBuilder();

            sB.Append("Olá, <br/>").AppendLine()
            .Append(" Para recuperar a senha utilize esse código: <br/>").AppendLine()
            .Append($"<p> <strong>{passwordKey}</strong> </p> ").AppendLine()
            .Append("<br/>").AppendLine()
            .Append("Atenciosamente, <br/>").AppendLine()
            .Append("Equipe SexMove");

            var emailService = new EmailService();

            emailService.SendEmail(sB.ToString(), "SexMove - Recuperar senha", user.Email);

            Uow.Commit();
        }
        public void EmptyOrNullEmail_ShouldHaveError(string email)
        {
            var command = new ForgotPasswordCommand {
                Email = email
            };

            _sut.ShouldHaveValidationErrorFor(x => x.Email, command);
        }
Ejemplo n.º 7
0
        public async Task WhenISubmitAForgotPasswordRequestWithAnInvalidEmail(string email)
        {
            _command = new ForgotPasswordCommand {
                Email = email
            };

            _response = await _client.PostAsync(BaseUrl, Utilities.GetRequestContent(_command));
        }
Ejemplo n.º 8
0
        public async Task WhenISubmitAForgotPasswordRequestWithAnUnknownEmail()
        {
            _command = new ForgotPasswordCommand {
                Email = "*****@*****.**"
            };

            _response = await _client.PostAsync(BaseUrl, Utilities.GetRequestContent(_command));
        }
Ejemplo n.º 9
0
        public async Task WhenISubmitAForgotPasswordRequest()
        {
            _command = new ForgotPasswordCommand {
                Email = _user.Email
            };

            _response = await _client.PostAsync(BaseUrl, Utilities.GetRequestContent(_command));
        }
        public void ValidLoginAndPassword_ShouldNotHaveErrors()
        {
            var command = new ForgotPasswordCommand {
                Email = "*****@*****.**"
            };

            _sut.ShouldNotHaveValidationErrorFor(x => x.Email, command);
        }
        public void InvalidEmail_ShouldHaveError()
        {
            var command = new ForgotPasswordCommand {
                Email = "invalidEmail"
            };

            _sut.ShouldHaveValidationErrorFor(x => x.Email, command);
        }
Ejemplo n.º 12
0
        public async Task <IActionResult> ForgotPassword(ForgotPasswordRequest request, CancellationToken cancellationToken)
        {
            var command = new ForgotPasswordCommand
            {
                Email = request.Email
            };

            var result = await _mediator.Send(command, cancellationToken);

            return(this.GetResponseFromResult(result));
        }
Ejemplo n.º 13
0
        public async Task <IActionResult> RequestResetPasswordForTheCurrentUser()
        {
            var currentUser = await this.currentUserProvider.GetCurrentUserAsync();

            var request = new ForgotPasswordCommand
            {
                Email = currentUser.Email,
            };

            return(this.Ok(await this.Mediator.Send(request)));
        }
Ejemplo n.º 14
0
        public async Task <IActionResult> ForgotPassword([FromBody] ForgotPasswordCommand command)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest());
            }

            await _userService.ForgotPasswordAsync(command);

            return(Ok(ResponseDto.Default));
        }
Ejemplo n.º 15
0
        public IActionResult ForgotPassword()
        {
            if (this.User.Identity.IsAuthenticated)
            {
                return(this.RedirectToHomeIndex());
            }

            var request = new ForgotPasswordCommand();

            return(this.ForgotPasswordView(request));
        }
Ejemplo n.º 16
0
        public async Task <IActionResult> ForgotPassword(string email)
        {
            var command = new ForgotPasswordCommand()
            {
                Email = email.ToLower().Trim()
            };

            await _mediator.Send(command);

            return(Ok());
        }
        public async Task <IActionResult> ForgotPassword([FromBody] ForgotPasswordCommand forgotPassword)
        {
            var result = await Mediator.Send(forgotPassword);

            if (result.Success)
            {
                return(Ok(result));
            }

            return(BadRequest(result));
        }
Ejemplo n.º 18
0
        public async Task <IActionResult> ForgotPassword([FromForm] ForgotPasswordCommand command)
        {
            var result = await _handler.Handler(command);

            if (result.Succeeded)
            {
                result.Message = _localizer["FORGOT_PASSWORD_SUCCESS"].Value;
                return(Ok(result));
            }
            result.Message = _localizer["FORGOT_PASSWORD_FAILED"].Value;
            return(BadRequest(result));
        }
        public Task <bool> Handle(ForgotPasswordCommand request, CancellationToken cancellationToken)
        {
            var user = _context.Users.FirstOrDefault(x => x.Email == request.MailAddress);

            if (user == null)
            {
                throw new UserNotFoundException();
            }

            user.CreateForgotPassword();
            return(Task.FromResult(true));
        }
Ejemplo n.º 20
0
        public async Task <IActionResult> ForgotPassword([FromBody] ForgotPasswordViewModel viewModel)
        {
            var command = new ForgotPasswordCommand(viewModel);
            var result  = await mediator.Send(command);

            if (!String.IsNullOrEmpty(result)) // to be refactored into command handler
            {
                var passwordResetLink = Url.Action("ResetPassword", "Recovery",
                                                   new { email = viewModel.Email, token = result }, Request.Scheme);
            }

            return(Ok(result));
        }
        public void SetUp()
        {
            _service    = new Mock <IForgotPasswordService>();
            _unitOfWork = new Mock <IUnitOfWork>();
            _sut        = new ForgotPasswordCommandHandler(_service.Object, _unitOfWork.Object);

            _command = new ForgotPasswordCommand {
                Email = "email"
            };

            _user = new User("email", "organizationId");
            _service.Setup(x => x.GetUserFromRepo(_command.Email, default))
            .ReturnsAsync(_user);
        }
        public async Task <ActionResult> ForgotPassword(ForgotPasswordCommand command)
        {
            if (ModelState.IsValid)
            {
                var user = await signInManager.UserManager.FindByNameAsync(command.Email);

                if (user == null || !(await signInManager.UserManager.IsEmailConfirmedAsync(user.Id)))
                {
                    return(View("ForgotPasswordConfirmation"));
                }
            }

            return(View(command));
        }
Ejemplo n.º 23
0
        public async Task <ApiResponse> ForgottenPassword([FromBody] ForgotPasswordCommand command)
        {
            var commandResponse = await this._forgotPasswordCommandHandler.Handle(command);

            if (commandResponse.ValidationResult.IsValid)
            {
                var response = ApiResponse.CreateSuccess(null);
                return(response);
            }
            else
            {
                return(ApiResponse.CreateError(commandResponse.ValidationResult));
            }
        }
Ejemplo n.º 24
0
        public async Task Handler_ForgotPassword()
        {
            var user = DataHelper.GetUser("test");

            _userRepository.
            Setup(x => x.GetAsync(It.IsAny <Expression <Func <User, bool> > >())).Returns(() => Task.FromResult(user));
            forgotPasswordCommand = new ForgotPasswordCommand
            {
                Email      = user.Email,
                TCKimlikNo = Convert.ToString(user.CitizenId)
            };
            var result = await forgotPasswordCommandHandler.Handle(forgotPasswordCommand, new System.Threading.CancellationToken());

            Assert.That(result.Success, Is.True);
        }
        public async Task Handler_ForgotPassword()
        {
            var user = DataHelper.GetUser("test");

            _userRepository.Setup(x => x.GetAsync(It.IsAny <Expression <Func <User, bool> > >()))
            .Returns(() => Task.FromResult(user));
            _forgotPasswordCommand = new ForgotPasswordCommand
            {
                Email      = user.Email,
                TcKimlikNo = Convert.ToString(user.CitizenId)
            };
            var result =
                await _forgotPasswordCommandHandler.Handle(_forgotPasswordCommand, new CancellationToken());

            result.Success.Should().BeTrue();
        }
Ejemplo n.º 26
0
        public async Task <IActionResult> ForgotPassword([FromBody] ForgotPasswordCommand command)
        {
            if (!ModelState.IsValid)
            {
                return(ErrorModelResult());
            }
            try
            {
                var result = await _commandDispatcher.DispatchAsync <ForgotPasswordCommand, Result>(command);

                return(ToResult(result));
            }
            catch (FailureResult reqEx)
            {
                return(ErrorResult(reqEx));
            }
        }
Ejemplo n.º 27
0
        public void Handle(ForgotPasswordCommand command)
        {
            if (!IsValidEmail(command.Email))
            {
                throw new ServerSideException("Email format is invalid");
            }

            using (var dbContext = new UserAccountDataContext())
            {
                var user = dbContext.Users.SingleOrDefault(u => u.Email == command.Email);

                if (user == null)
                {
                    throw new ServerSideException(
                              String.Format("User with email: {0} does not exist", command.Email));
                }

                // TODO Generate new password
                // TODO Send email with new password
            }
        }
 /// <summary>
 /// Request to reset the password in case it is forgotten by the user
 /// </summary>
 /// <param name="forgotPasswordCommand"> </param>
 /// <returns></returns>
 public string ForgotPassword(ForgotPasswordCommand forgotPasswordCommand)
 {
     // Make sure all given credential contains value
     if (!string.IsNullOrEmpty(forgotPasswordCommand.Email) && (!string.IsNullOrEmpty(forgotPasswordCommand.Username)))
     {
         // Get the user tied to this Activation Key
         User user = _userRepository.GetUserByEmail(forgotPasswordCommand.Email);
         // If activation key is valid, proceed to verify username and password
         if (user != null)
         {
             if (!user.IsActivationKeyUsed.Value)
             {
                 throw new InvalidOperationException("Account is not activated yet. In case you have forgotten your " +
                                                     "password, you can cancel your account activation" +
                                                     " and then sign up for an account again.");
             }
             if (user.Username.Equals(forgotPasswordCommand.Username))
             {
                 string newForgotPasswordCode = _passwordCodeGenerationService.CreateNewForgotPasswordCode();
                 user.AddForgotPasswordCode(newForgotPasswordCode);
                 _persistenceRepository.SaveUpdate(user);
                 return(newForgotPasswordCode);
             }
             else
             {
                 throw new InvalidCredentialException("Wrong username.");
             }
         }
         else
         {
             throw new InvalidOperationException(string.Format("{0} {1}", "No user could be found for Email: ", forgotPasswordCommand.Email));
         }
     }
     // If the user did not provide all the credentials, return with failure
     else
     {
         throw new InvalidCredentialException("Email not provided");
     }
 }
Ejemplo n.º 29
0
        public async Task ForgotPasswordAsync(ForgotPasswordCommand command)
        {
            var user = await _userManager.FindByEmailAsync(command.Email);

            if (user == null)
            {
                throw new GfsException(ErrorCode.UserNotFound, _dictionary.UserNotFound);
            }

            var token = Guid.NewGuid();

            if (token == null)
            {
                throw new GfsException(ErrorCode.EmptyToken, _dictionary.EmptyToken);
            }

            var msg = _dictionary.ResetMailMessage + " http://localhost:4200/#/auth/reset?token=" + token;

            user.PasswordResetToken = token.ToString();
            await _context.SaveChangesAsync();

            await _emailService.SendEmailAsync(user.Email, _dictionary.ResetMailSubject, msg);
        }
Ejemplo n.º 30
0
 public void OnGet()
 {
     Model = new ForgotPasswordCommand();
 }
 public ActionResult ForgotPassword(ForgotPasswordCommand command)
 {
     return RedirectToAction("Login");
 }