public async Task <ActionResult> ChangePassword(
            [FromBody] UserChangePasswordDto userChangePasswordDto)
        {
            var user = await _userRepo.GetUserByUserClaims(HttpContext.User);

            if (user == null)
            {
                return(Unauthorized(new { message = "User is Unauthorized" }));
            }
            var checkIfOldPasswordCorrect = await _userRepo.Login(user, userChangePasswordDto.CurrentPassword);

            if (checkIfOldPasswordCorrect == false)
            {
                return(BadRequest("Current Password Is Wrong"));
            }
            var checkIfNewPasswordValid = await _userRepo.ValidatePassword(userChangePasswordDto.NewPassword);

            if (checkIfNewPasswordValid == false)
            {
                return(BadRequest(
                           "BadPassword\nPassword Must Have at least one:{digit,Uppercase letter,Lowercase letter} and length 6 or more}"));
            }
            var result = await _userRepo.ChangePassword(user, userChangePasswordDto.CurrentPassword,
                                                        userChangePasswordDto.NewPassword);

            if (result)
            {
                return(Ok(new { message = "Password Update Succeeded" }));
            }

            throw new Exception("Error Happen When Updating The Password ");
        }
        public IActionResult ChangePassword(UserChangePasswordDto userChangePassword)
        {
            if (ModelState.IsValid)
            {
                if (userChangePassword.Password == userChangePassword.CorrectPassword)
                {
                    User updateUser = _userManager.Find(x => x.UserId == userChangePassword.UserId);
                    using var hmac          = new HMACSHA512();
                    updateUser.PasswordHash = hmac.ComputeHash(Encoding.UTF8.GetBytes(userChangePassword.Password));
                    updateUser.PasswordSalt = hmac.Key;
                    updateUser.Guid         = Guid.NewGuid().ToString();
                    _userManager.UpdateAsync(updateUser);
                    return(RedirectToAction("Login", "Home"));
                }
                else
                {
                    ModelState.AddModelError("", "Password and Verify password cannot match");
                    return(View(userChangePassword));
                }
            }
            else
            {
                ModelState.AddModelError("", "Write your password");

                return(View(userChangePassword));
            }
        }
Esempio n. 3
0
        public async Task <IActionResult> ChangePasswordAsync(UserChangePasswordDto model)
        {
            var changePassword = new ChangeUserPassword.Command(model);
            var res            = await _mediator.Send(changePassword);

            return(Ok(res));
        }
Esempio n. 4
0
        public ActionResult <ApiResponse <bool> > ChangePassword(int id, UserChangePasswordDto user)
        {
            var response = new ApiResponse <bool>();

            try
            {
                var dto = _userRepository.Find(us => us.Id == id);
                if (dto != null)
                {
                    if (_userRepository.VerifyPassword(dto.Password, user.oldPassword))
                    {
                        dto.Password = _userRepository.HashPassword(user.newPassword);

                        StreamReader reader = new StreamReader(Path.GetFullPath("Templates/Email.html"));
                        //_hierarchyRepository.Update(hie, item.Hierarchies[0].Id);
                        _userRepository.Update(dto, id);
                        response.Success = true;
                        response.Message = "La contraseña se actualizó correctamente";
                        response.Result  = true;

                        string body = string.Empty;
                        body = reader.ReadToEnd();
                        body = body.Replace("{username}", "Saludos, " + dto.Name + " " + dto.LastName + " " + dto.MotherName);
                        body = body.Replace("{pass}", "Tu nueva contraseña es " + user.newPassword);

                        Email mail = new Email();
                        mail.To         = dto.Email;
                        mail.Subject    = "Cambio de contraseña";
                        mail.Body       = body;
                        mail.IsBodyHtml = true;
                        _emailService.SendEmail(mail);
                    }
                    else
                    {
                        response.Success = false;
                        response.Message = "La contraseña no coincide, favor de verificar";
                        response.Result  = false;
                    }
                }
                else
                {
                    response.Success = false;
                    response.Message = "El usuario no existe, favor de verificar";
                    response.Result  = false;
                }
            }
            catch (Exception ex)
            {
                response.Result  = false;
                response.Success = false;
                response.Message = "Internal server error";
                _logger.LogError($"Something went wrong: { ex.ToString() }");
                return(StatusCode(500, response));
            }
            return(Ok(response));
        }
        public async Task <IdentityResult> UserChangePasswordAsync(UserChangePasswordDto userPassword)
        {
            var userExists = await _identityRepository.ExistsUserAsync(userPassword.UserId);

            if (!userExists)
            {
                throw new UserFriendlyErrorPageException(string.Format(_identityServiceResources.UserDoesNotExist().Description, userPassword.UserId), _identityServiceResources.UserDoesNotExist().Description);
            }

            var identityResult = await _identityRepository.UserChangePasswordAsync(userPassword.UserId, userPassword.Password);

            return(HandleIdentityError(identityResult, _identityServiceResources.UserChangePasswordFailed().Description, _identityServiceResources.IdentityErrorKey().Description, userPassword));
        }
Esempio n. 6
0
        public IHttpActionResult ChangePassword([FromBody] UserChangePasswordDto model)
        {
            if (ModelState.IsValid == false)
            {
                return(BadRequest(ModelState));
            }

            userRepo.ChangePassword(UserK, model.CurrentPassword, model.NewPassword);

            userRepo.SaveChanges();

            return(Ok());
        }
Esempio n. 7
0
        public async Task ValidPasswordChangeTet()
        {
            var dto = new UserChangePasswordDto
            {
                UserId      = UserHelper.OtherUserModel.Id,
                OldPassword = UserHelper.LoginDto.Password,
                NewPassword = "******"
            };

            var result = await _userService.ChangePassword(dto);

            Assert.AreEqual(UserHelper.OtherUserModel.Id, dto.UserId);
            Assert.IsNotEmpty(result.Token);
        }
        public async Task <IActionResult> UserChangePassword(Guid id)
        {
            if (string.IsNullOrEmpty(id.ToString()))
            {
                return(NotFound());
            }

            var user = await _identityService.GetUserAsync(new UserDto { Id = id });

            var userDto = new UserChangePasswordDto {
                UserId = id, UserName = user.UserName
            };

            return(View(userDto));
        }
Esempio n. 9
0
        public async Task <IActionResult> UserChangePassword(TUserDtoKey id)
        {
            if (EqualityComparer <TUserDtoKey> .Default.Equals(id, default))
            {
                return(NotFound());
            }

            var user = await _identityService.GetUserAsync(id.ToString());

            var userDto = new UserChangePasswordDto <TUserDtoKey> {
                UserId = id, UserName = user.UserName
            };

            return(View(userDto));
        }
Esempio n. 10
0
        public async Task <IActionResult> UserChangePassword(int id)
        {
            if (id == 0)
            {
                return(NotFound());
            }

            var user = await _identityService.GetUserAsync(new UserDto { Id = id });

            var userDto = new UserChangePasswordDto {
                UserId = id, UserName = user.UserName
            };

            return(View(userDto));
        }
        public async Task <bool> ChangePasswordAsync(string userId, UserChangePasswordDto userChangePasswordDto)
        {
            var user = _userManager.FindByIdAsync(userId).Result;

            var connexion = await _userManager.CheckPasswordAsync(user, userChangePasswordDto.CurrentPassword);

            if (connexion)
            {
                var result = await _userManager.ChangePasswordAsync(user, userChangePasswordDto.CurrentPassword, userChangePasswordDto.NewPassword);

                return(result.Succeeded);
            }

            return(false);
        }
        public IActionResult ChangePassword(Guid id)
        {
            User PasswordChangeUser = _userManager.Find(x => x.Guid == id.ToString());

            if (PasswordChangeUser == null)
            {
                return(RedirectToAction("Login", "Home"));
            }
            else
            {
                UserChangePasswordDto user = new UserChangePasswordDto
                {
                    UserId = PasswordChangeUser.UserId
                };

                return(View(user));
            }
        }
Esempio n. 13
0
        public async Task <Contract.Models.User> ChangePassword(UserChangePasswordDto changePasswordDto)
        {
            ValidationHelper.ValidateAndThrow(changePasswordDto);

            var user = await _userGetOperations.GetById(changePasswordDto.UserId);

            if (user is null)
            {
                throw new NotFoundException("Пользователь не найден");
            }
            if (!PasswordHelper.ComparePassword(user, changePasswordDto.OldPassword))
            {
                throw new InvalidPasswordException();
            }

            var(hash, salt) = PasswordHelper.GeneratePassword(changePasswordDto.NewPassword);
            return(await _userWriteOperations.UpdatePassword(user.Id, hash, salt));
        }
Esempio n. 14
0
        public async Task <bool> ChangeUserPasswordAsync(Guid?userId, UserChangePasswordDto changePasswordDto, ModelStateDictionary modelState)
        {
            var user = await _userManager.FindByIdAsync(userId.ToString());

            var result = await _userManager.ChangePasswordAsync(user,
                                                                changePasswordDto.OldPassword, changePasswordDto.NewPassword);

            if (result.Succeeded)
            {
                return(true);
            }

            foreach (var error in result.Errors)
            {
                modelState.TryAddModelError(error.Code, error.Description);
            }

            return(false);
        }
Esempio n. 15
0
        public IActionResult ChangePassword([FromBody] UserChangePasswordDto userChangePasswordDto)
        {
            var user = _userService.GetById(Int32.Parse(User.Identity.Name));

            if (user == null)
            {
                return(Unauthorized());
            }
            User authUser;

            try
            {
                authUser = _userService.Authenticate(user.Username, userChangePasswordDto.OldPassword);
            }
            catch (ApplicationException)
            {
                return(BadRequest(Properties.resultMessages.OldPasswordInvalid));
            }

            var userDto = _mapper.Map <UserDto>(authUser);

            userDto.Password = userChangePasswordDto.NewPassword;

            var validator = new UserValidator();
            var result    = validator.Validate(userDto);

            try
            {
                if (!result.IsValid)
                {
                    throw new ApplicationException(string.Join(",", result.Errors));
                }

                _userService.Update(authUser, userChangePasswordDto.NewPassword);
            }
            catch (ApplicationException ex)
            {
                return(BadRequest(ex.Message));
            }

            return(Ok());
        }
Esempio n. 16
0
        public async Task <ActionResponse <object> > ChangePassword(UserChangePasswordDto passwordDto)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(passwordDto.Email) || string.IsNullOrWhiteSpace(passwordDto.NewPassword))
                {
                    return(await ActionResponse <object> .ReturnError("Dio obaveznih parametara nedostaje. Izmjena nije moguća."));
                }

                var user = await userManager.FindByEmailAsync(passwordDto.Email);

                if (user == null)
                {
                    return(await ActionResponse <object> .ReturnError("Korisnik sa odabranom email adresom ne postoji u sustavu."));
                }

                var validator = userManager.PasswordValidators.First();
                var isValid   = await validator.ValidateAsync(userManager, user, passwordDto.NewPassword);

                if (!isValid.Succeeded)
                {
                    return(await ActionResponse <object>
                           .ReturnError("Odabrana lozinka ne odgovara standardima. Lozinka mora imati barem jedan poseban znak, jedan broj i kombinaciju malih i velikih slova."));
                }

                var resetToken = await userManager.GeneratePasswordResetTokenAsync(user);

                var result = await userManager.ResetPasswordAsync(user, resetToken, passwordDto.NewPassword);

                if (!result.Succeeded)
                {
                    return(await ActionResponse <object> .ReturnError("Greška prilikom izmjene lozinke. Molimo pokušajte ponovno ili kontaktirajte administratore."));
                }

                return(await ActionResponse <object> .ReturnSuccess(null, "Lozinka uspješno izmijenjena."));
            }
            catch (Exception)
            {
                return(await ActionResponse <object> .ReturnError("Nepredviđena greška prilikom izmjene lozinke. Molimo pokušajte ponovno ili kontaktirajte administratore."));
            }
        }
        public async Task <IActionResult> UserChangePassword(UserChangePasswordDto <TUserDtoKey> userPassword)
        {
            if (!ModelState.IsValid)
            {
                return(Success(userPassword));
            }

            var identityResult = await _identityService.UserChangePasswordAsync(userPassword);

            if (!identityResult.Errors.Any())
            {
                return(Success(new { Id = userPassword.UserId }));
            }

            foreach (var error in identityResult.Errors)
            {
                ModelState.AddModelError(string.Empty, error.Description);
            }

            return(Success(userPassword));
        }
Esempio n. 18
0
        public async Task <IActionResult> ChangePassword(UserChangePasswordDto userChangePasswordDto)
        {
            if (ModelState.IsValid)
            {
                var nameOfCurrentUser = HttpContext.User.Identity.Name;

                var user = await _userManager.FindByNameAsync(nameOfCurrentUser);

                if (user != null)
                {
                    IdentityResult result =
                        await _userManager.ChangePasswordAsync(user, userChangePasswordDto.OldPassword, userChangePasswordDto.NewPassword);

                    if (result.Succeeded)
                    {
                        await _emailService.SendAsync(ChangePasswordSettings.subject,
                                                      ChangePasswordSettings.GetMessage(user.Email, userChangePasswordDto.NewPassword),
                                                      user.Email);

                        return(RedirectToAction("Index", "Home"));
                    }
                    else
                    {
                        foreach (var error in result.Errors)
                        {
                            ModelState.AddModelError(string.Empty, error.Description);
                        }
                    }
                }
                else
                {
                    ModelState.AddModelError(string.Empty, "Користувач незнайдений");
                }
            }
            else
            {
                ModelState.AddModelError(string.Empty, "Неправильно введені дані");
            }
            return(PartialView(userChangePasswordDto));
        }
Esempio n. 19
0
        public async Task <IActionResult> UserChangePassword(UserChangePasswordDto userPassword)
        {
            if (!ModelState.IsValid)
            {
                return(View(userPassword));
            }

            var identityResult = await _identityService.UserChangePasswordAsync(userPassword);

            if (!identityResult.Errors.Any())
            {
                SuccessNotification(_localizer["SuccessUserChangePassword"], _localizer["SuccessTitle"]);

                return(RedirectToAction("UserProfile", new { Id = userPassword.UserId }));
            }

            foreach (var error in identityResult.Errors)
            {
                ModelState.AddModelError(string.Empty, error.Description);
            }

            return(View(userPassword));
        }
Esempio n. 20
0
        public async Task <ActionResult> ChangePassword(UserChangePasswordDto passwordDto)
        {
            var user = await _userRepository.GetById(AuthUserId);

            if (user == null)
            {
                return(Unauthorized());
            }

            var currencthash = _encrypter.GetHash(passwordDto.CurrentPassword, user.Salt);

            if (currencthash != user.Hash)
            {
                return(BadRequest());
            }

            var newSalt = _encrypter.GetSalt(passwordDto.NewPassword);
            var newHash = _encrypter.GetHash(passwordDto.NewPassword, newSalt);

            user.SetPassword(newHash, newSalt);
            await _userRepository.Update(user);

            return(NoContent());
        }
Esempio n. 21
0
 public async Task <ActionResponse <object> > ChangePassword([FromBody] UserChangePasswordDto passwordDto)
 {
     return(await userService.ChangePassword(passwordDto));
 }
        public async Task <IActionResult> ChangeUserPassword([FromBody] UserChangePasswordDto changePasswordDto)
        {
            var user = await _userService.ChangeUserPasswordAsync(User.GetCurrentUserId(), changePasswordDto, ModelState);

            return(user ? NoContent() : BadRequest(ModelState));
        }
Esempio n. 23
0
 public Command(UserChangePasswordDto user)
 {
     model = user;
 }
Esempio n. 24
0
        public async Task InvalidPasswordChangeTest()
        {
            var dto = new UserChangePasswordDto();

            Assert.ThrowsAsync <ValidationException>(async() => await _userService.ChangePassword(dto));
        }