Exemplo n.º 1
0
        public async Task <ActionResult> ChangePassword(UserChangePasswordViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            if (model.NewPassword != model.NewPasswordCopy)
            {
                ModelState.AddModelError("", GetErrorMessage.PasswordsDontMatch);
                return(View(model));
            }

            AppUser user = GetCurrentUser();

            if (user != null)
            {
                bool correctPass = await _userManager.CheckPasswordAsync(user, model.OldPassword);

                if (!correctPass)
                {
                    ModelState.AddModelError("", GetErrorMessage.PasswordNotValid);
                    return(View(model));
                }

                IdentityResult validPass = await _userManager.PasswordValidator.ValidateAsync(model.NewPassword);

                if (validPass.Succeeded)
                {
                    user.PasswordHash = _userManager.PasswordHasher.HashPassword(model.NewPassword);

                    IdentityResult result = await _userManager.UpdateAsync(user);

                    if (result.Succeeded)
                    {
                        _mailingRepository.PasswordChangedMail(user.Email);

                        return(RedirectToAction("Index"));
                    }
                    else
                    {
                        AddErrorsFromResult(result);
                    }
                }
                else
                {
                    AddErrorsFromResult(validPass);
                    return(View(model));
                }
            }
            else
            {
                ModelState.AddModelError("", GetErrorMessage.NullUser);
            }
            return(View(model));
        }