public async Task <IActionResult> ChangePassword(ChangeUserPasswordViewModel model) { if (!ModelState.IsValid) { return(View(model)); } var user = await _userManager.FindByIdAsync(model.userId.ToString()); if (user == null) { return(View("NotFound")); } var result = await _userManager.ResetPasswordAsync(user, model.Token, model.NewPassword); if (result.Succeeded) { await _userManager.UpdateSecurityStampAsync(user); return(Utility.CloseAndRefresh()); } foreach (var error in result.Errors) { ModelState.AddModelError(string.Empty, error.Description); } return(View(model)); }
public async Task <IActionResult> ChangePassword([FromBody] ChangeUserPasswordViewModel record) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } if (record.Password != record.ConfirmPassword) { ModelState.AddModelError("PasswordConfirmation", "The password differs from its confirmation"); } try { Dictionary <string, string> remarks = new Dictionary <string, string>(); if (await _AppService.ChangePassword(record.Id, record.PreviousPassword, record.Password, remarks)) { return(Accepted($"api/[controller]/{ record.Id }")); } foreach (var item in remarks) { ModelState.AddModelError(item.Key, item.Value); } return(BadRequest(ModelState)); } catch (ApplicationException ex) { return(new BadRequestObjectResult(ex)); } catch (Exception ex) { return(new BadRequestObjectResult(ex)); } }
public ActionResult ChangePassword(ChangeUserPasswordViewModel changeUserPasswordViewModel) { if (!ModelState.IsValid) { return(View("UserPassword", changeUserPasswordViewModel)); } var userId = AppSecurityContext.UserId; if (!_accountManager.CheckOldPassword(changeUserPasswordViewModel.OldPassword, userId.Value)) { throw new Exception("Wrong old password"); } if (!_accountManager.IsPasswordNew(changeUserPasswordViewModel.NewPassword, userId.Value)) { throw new Exception("Please create another password. Such password existed"); } if (!string.Equals(changeUserPasswordViewModel.NewPassword, changeUserPasswordViewModel.ConfirmNewPassword)) { throw new Exception("Passwords are different"); } _accountManager.SaveUserPassword(changeUserPasswordViewModel.NewPassword, userId.Value); return(RedirectToAction("Index", "Home")); }
public async Task <IActionResult> ChangePassword(ChangeUserPasswordViewModel model) { var curUser = _userManager.Users.Single(w => w.Id == GetCurrentUserIdAsync()); var _passwordValidator = HttpContext.RequestServices.GetService(typeof(IPasswordValidator <User>)) as IPasswordValidator <User>; var _passwordHasher = HttpContext.RequestServices.GetService(typeof(IPasswordHasher <User>)) as IPasswordHasher <User>; IdentityResult result = await _passwordValidator.ValidateAsync(_userManager, curUser, model.Password); if (result.Succeeded) { curUser.PasswordHash = _passwordHasher.HashPassword(curUser, model.Password); await _userManager.UpdateAsync(curUser); } else { foreach (var error in result.Errors) { ModelState.AddModelError(string.Empty, error.Description); } } return(View()); }
public async Task <IActionResult> ChangeUserPassword(ChangeUserPasswordViewModel model) { if (!ModelState.IsValid) { return(View(model)); } var user = await _userManager.FindByEmailAsync(model.Email); if (user != null) { IdentityResult resultRemovePassoword = await _userManager.RemovePasswordAsync(user); IdentityResult resultAddPassword = await _userManager.AddPasswordAsync(user, model.NewPassword); if (resultRemovePassoword.Succeeded && resultAddPassword.Succeeded) { _logger.LogInformation(3, "Hasło użytkownika zostało zmienione."); return(RedirectToAction(nameof(Index), new { Message = ManageMessageId.ChangeUserPasswordSuccess })); } AddErrors(resultRemovePassoword); AddErrors(resultAddPassword); return(View(model)); } return(RedirectToAction(nameof(Index), new { Message = ManageMessageId.Error })); }
public ActionResult ChangePassword(ChangeUserPasswordViewModel model) { if (ModelState.IsValid) { try { var user = getLoggedInUser(); if (user == null) { ViewBag.ErrorMsg = "You are not logged in"; return(View()); } bool isVerified = UserLogic.VerifyHashedPassword(user.PasswordHash, model.OldPass); if (isVerified) { user.PasswordHash = UserLogic.HashPassword(model.NewPass); userRepo.Update(user); ViewBag.ErrorMsg = "Password changed successfully"; return(View()); } ViewBag.ErrorMsg = "Wrong password"; return(View()); } catch (Exception) { //ErrorLogger.Log("Message= " + ex.Message + "\nInner Exception= " + ex.InnerException + "\n"); return(PartialView("Error")); } } ViewBag.ErrorMsg = "Invalid data"; return(View()); }
public async Task <ActionResult> ChangeUserPassword([FromBody] ChangeUserPasswordViewModel userData) { try { if (userData == null) { logger.LogError("UserData object sent from client is null."); return(BadRequest("UserData object is null")); } var result = await accountAdapter.ChangeUserPassword(userData).ConfigureAwait(false); if (!result.Succeeded) { return(new BadRequestObjectResult(Errors.AddErrorsToModelState(result, ModelState))); } logger.LogInformation($"Users password with id: {userData.Id} is successfully updated"); return(Ok("Account password successfully updated!")); } catch (Exception ex) { logger.LogError($"Something went wrong inside ChangeUserPassword action: {ex.Message}"); return(StatusCode(500, "Internal server error")); } }
public async Task <IActionResult> ChangePassword(string id, ChangeUserPasswordViewModel model) { if (!ModelState.IsValid) { return(View(model)); } var user = await this.userManager.FindByIdAsync(id); var token = await this.userManager.GeneratePasswordResetTokenAsync(user); var result = await this.userManager.ResetPasswordAsync(user, token, model.NewPassword); if (result.Succeeded) { this.TempData["SuccessMessage"] = "Password has been changed successfully"; return(RedirectToAction(nameof(All))); } else { foreach (var error in result.Errors) { ModelState.AddModelError(string.Empty, error.Description); } return(View(model)); } }
public ActionResult ChangeUserPassword(string id) { ChangeUserPasswordViewModel model = new ChangeUserPasswordViewModel { UserId = id }; return(View(model)); }
public async Task <IActionResult> ChangePassword(ChangeUserPasswordViewModel model) { if (!ModelState.IsValid) { return(View(model)); } try { if (!await ValidateAdminRights()) { TempData[ErrorMessageKey] = "Insufficient rights"; return(RedirectToAction(nameof(AllUsers))); } Regex regex = new Regex(@"^(?=.*[\p{Ll}])(?=.*[\p{Lu}])(?=.*\d)(?=.*[$@$!%*?&])[\p{Ll}\p{Lu}\d$@$!%*?&]{8,}"); Match match = regex.Match(model.Password); if (match.Success) { var userToEdit = await this.userManager.FindByIdAsync(model.Id); string code = await this.userManager.GeneratePasswordResetTokenAsync(userToEdit); IdentityResult result = await this.userManager.ResetPasswordAsync(userToEdit, code, model.Password); if (result.Succeeded) { TempData[SuccessMessageKey] = $"Успешно сменена парола на потребител: {model.Username} "; await this.userManager.ResetAuthenticatorKeyAsync(userToEdit); var currentUser = await this.userManager.FindByNameAsync(User.Identity.Name); if (currentUser.UserName == userToEdit.UserName) { await signInManager.SignOutAsync(); TempData.Remove("SuccessMessageKey"); } } else { TempData[ErrorMessageKey] = $"Паролата не е сменена. Програмна грешка"; } } else { TempData[ErrorMessageKey] = $"Паролата не отговаря на ISO 27000"; } return(RedirectToAction(nameof(AllUsers))); } catch (Exception) { TempData[ErrorMessageKey] = "Error! Основна грешка"; return(RedirectToAction("Index", "Home", new { area = "" })); } }
public async Task <IActionResult> ChangePasswordAsync( [FromBody] ChangeUserPasswordViewModel changeUserPasswordViewModel) { var changeUserPasswordDto = _mapper.Map <ChangeUserPasswordDto>( changeUserPasswordViewModel); await _userService.ChangePasswordAsync(changeUserPasswordDto); return(Ok()); }
public async Task <IActionResult> ChangeUserPassword(ChangeUserPasswordViewModel model) { if (!_uiOptions.AllowAdminsToChangeUserPasswords) { return(RedirectToAction("Index")); } if (model.UserId == Guid.Empty) { return(RedirectToAction("Index")); } var selectedSite = await _siteManager.GetSiteForDataOperations(model.SiteId); // only server admin site can edit other sites users if (selectedSite.Id != _siteManager.CurrentSite.Id) { ViewData["Title"] = string.Format(CultureInfo.CurrentUICulture, _sr["{0} - Change User Password"], selectedSite.SiteName); } else { ViewData["Title"] = _sr["Change User Password"]; } var user = await _userManager.Fetch(selectedSite.Id, model.UserId); if (user == null) { return(RedirectToAction("Index")); } if (!ModelState.IsValid) { return(View(model)); } user.MustChangePwd = model.MustChangePwd; var result = await _userManager.ChangeUserPassword(user as SiteUser, model.NewPassword, true); if (result.Succeeded) { this.AlertSuccess(_sr["The user password has been changed."]); return(RedirectToAction("Index")); } else { this.AlertDanger(_sr["oops something went wrong please try again"]); } AddErrors(result); return(View(model)); }
public virtual async Task <ActionResult> ChangeUserPassword( Guid userId, Guid?siteId ) { if (!UIOptions.AllowAdminsToChangeUserPasswords) { return(RedirectToAction("Index")); } if (userId == Guid.Empty) { return(RedirectToAction("Index")); } var selectedSite = await SiteManager.GetSiteForDataOperations(siteId); // only server admin site can edit other sites users if (selectedSite.Id != SiteManager.CurrentSite.Id) { ViewData["Title"] = string.Format(CultureInfo.CurrentUICulture, StringLocalizer["{0} - Change User Password"], selectedSite.SiteName); } else { ViewData["Title"] = StringLocalizer["Change User Password"]; } var user = await UserManager.Fetch(selectedSite.Id, userId); if (user == null) { return(RedirectToAction("Index")); } var model = new ChangeUserPasswordViewModel { SiteId = selectedSite.Id, UserId = user.Id, DisplayName = user.DisplayName, Email = user.Email }; var currentCrumbAdjuster = new NavigationNodeAdjuster(Request.HttpContext) { KeyToAdjust = "UserEdit", AdjustedText = user.DisplayName }; currentCrumbAdjuster.AddToContext(); return(View(model)); }
public virtual async Task <JsonResult> ChangeUserPassword(ChangeUserPasswordViewModel input) { if (input.NewPassword != input.NewPasswordAgain) { throw new UserFriendlyException("`new password` should be same with `new password again`"); } await _userAppService.ChangePasswordAsync(new ChangePasswordDto { CurrentPassword = input.CurrentPassword, NewPassword = input.NewPassword }); return(Json(new AjaxResponse())); }
public async Task <IActionResult> ChangeUserPassword(string email) { if (await _userManager.FindByEmailAsync(email) == null) { return(NotFound()); } var model = new ChangeUserPasswordViewModel() { Email = email }; return(View(model)); }
public virtual async Task <IActionResult> ChangeUserPassword([Required] ChangeUserPasswordViewModel model) { if (model.AuthenticationType.Equals(AuthenticationType.Ad)) { var ldapUser = await _ldapUserManager.FindByNameAsync(model.UserName); var bind = await _ldapUserManager.CheckPasswordAsync(ldapUser, model.Password); if (!bind) { ModelState.AddModelError("", $"Invalid credentials for AD authentication"); return(View(model)); } } var user = await _userManager.FindByIdAsync(model.UserId.ToString()); if (user == null) { ModelState.AddModelError("", "The user is no longer in the system"); return(View(model)); } var hasher = new PasswordHasher <GearUser>(); var hashedPassword = hasher.HashPassword(user, model.Password); user.PasswordHash = hashedPassword; user.LastPasswordChanged = DateTime.Now; var result = await _userManager.UpdateAsync(user); if (result.Succeeded) { IdentityEvents.Users.UserPasswordChange(new UserChangePasswordEventArgs { Email = user.Email, UserName = user.UserName, UserId = user.Id, Password = model.Password }); return(Redirect(model.CallBackUrl)); } foreach (var _ in result.Errors) { ModelState.AddModelError(string.Empty, _.Description); } return(View(model)); }
public void Save() { ChangeUserPasswordViewModel data = View.GetFormData(); try { using (var proxy = channel.CreateChannel()) { proxy.ChangePassword(data); } } catch (Exception ex) { throw; } }
public async Task <IActionResult> ChangePassword(ChangeUserPasswordViewModel model) { if (!ModelState.IsValid) { return(View(model)); } try { var user = await _identityService.GetUser(User); var changePasswordResult = await _mediator.Send(new ChangeUserPasswordCommand() { OldPassword = model.OldPassword, NewPassword = model.NewPassword, ConfirmPassword = model.ConfirmPassword, User = user }); if (changePasswordResult.IdentityResult.Succeeded) { var loginResponse = await _mediator.Send(new LoginCommand() { Username = user.Email, Password = model.NewPassword, RememberMe = true }); StatusMessage = "Your password has been changed."; return(RedirectToAction(nameof(ChangePassword))); } else { AddErrors(changePasswordResult.IdentityResult); } } catch (ValidationException ex) { AddErrors(ex); } return(View(model)); }
public async Task <IActionResult> Index(ChangeUserPasswordViewModel model) { if (!ModelState.IsValid) { return(View(model)); } var user = await _userManager.FindByIdAsync(model.UserId.ToString()); if (user == null) { return(View("NotFound")); } var result = await _userManager.UpdatePasswordHash(user, model.NewPassword, validatePassword : true); if (result.Succeeded) { await _userManager.UpdateSecurityStampAsync(user); // reflect the changes in the Identity cookie await _signInManager.RefreshSignInAsync(user); await _emailSender.SendEmailAsync( email : user.Email, subject : "اطلاع رسانی تغییر کلمهی عبور", viewNameOrPath : "~/Areas/Identity/Views/EmailTemplates/_ChangePasswordNotification.cshtml", model : new ChangePasswordNotificationViewModel { User = user, EmailSignature = _siteOptions.Value.Smtp.FromName, MessageDateTime = DateTime.UtcNow.ToLongPersianDateTimeString() }); return(RedirectToAction(nameof(Index), "UserCard", routeValues: new { id = user.Id })); } foreach (var error in result.Errors) { ModelState.AddModelError(string.Empty, error.Description); } return(View(model)); }
public async Task <JsonResult> ChangePasswordAsync(ChangeUserPasswordViewModel model) { // If modelstate isn't valid if (!ModelState.IsValid) { IList <string> errorMessages = new List <string>(); foreach (ModelState modelState in ModelState.Values) { foreach (ModelError error in modelState.Errors) { errorMessages.Add(error.ErrorMessage); } } return(Json(errorMessages)); } // if current user isn't found int userid = User.Identity.GetUserId <int>(); if (userid <= 0) { return(Json(new { message = "Người dùng chưa đăng nhập" })); } // change password var result = await UserManager.ChangePasswordAsync(userid, model.OldPassword, model.NewPassword); // if success if (result.Succeeded) { var user = await UserManager.FindByIdAsync(userid); if (user != null) { await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : true); } return(Json(new { message = "Đổi mật khẩu thành công" })); } return(Json(result.Errors)); }
public async Task <ActionResult> ChangePassword([Bind(Include = "Username,OldPassword,NewPassword,RepeatedPassword")] ChangeUserPasswordViewModel model) { if (model.Username != User.Identity.Name) { return(RedirectToAction("UserProfile", "Users", new { username = model.Username })); } var userManager = HttpContext.GetOwinContext().GetUserManager <ApplicationUserManager>(); ApplicationUser user = await userManager.FindByIdAsync(User.Identity.GetUserId()); if (ModelState.IsValid) { await userManager.ChangePasswordAsync( user.Id, model.OldPassword, model.NewPassword ); } Message.Create(Response, "Password was successfully changed."); return(RedirectToAction("UserProfile", "Users", new { username = model.Username })); }
public async Task <IActionResult> ChangePassword() { var user = await _identityService.GetUser(User); var userHasPasswordResult = await _mediator.Send(new HasUserPasswordQuery() { User = user }); if (!userHasPasswordResult.HasUserPassword) { return(RedirectToAction(nameof(SetPassword))); } var model = new ChangeUserPasswordViewModel { StatusMessage = StatusMessage }; return(View(model)); }
public ActionResult ChangePassword(int id) { Users user = GetByID(id); ChangeUserPasswordViewModel changeUserPasswordViewModel = new ChangeUserPasswordViewModel() { ID = user.ID, Password = user.Password }; if (user.ID != SessionDTO.ID && SessionDTO.IsAdmin == false) { return(new ViewResult { ViewName = "InsufficientPermission" }); } else { return(View(changeUserPasswordViewModel)); } }
public ActionResult ChangePassword(ChangeUserPasswordViewModel userViewModel) { if (ModelState.IsValid) { var user = UserManager.FindById(userViewModel.ID); var token = UserManager.GeneratePasswordResetToken(user.Id); var updateResult = UserManager.ResetPassword(user.Id, token, userViewModel.Password); if (updateResult.Succeeded) { return(RedirectToAction("Index")); } AddErrors(updateResult); } return(View(userViewModel)); }
public void PutEntity(ChangeUserPasswordViewModel changeUserPasswordViewModel) { var message = new Message(); var text = string.Empty; if (changeUserPasswordViewModel.NewPassword.Equals(changeUserPasswordViewModel.ConfirmPassword)) { var userId = CustomMembershipProvider.GetUserIdCookie(); if (userId != null) { var user = _userService.GetUserAndUserProfileByUserId(userId ?? 0); var password = _userService.GetMd5Hash(changeUserPasswordViewModel.Password); if (password.Equals(user.UserProfile.Password)) { var newPassword = _userService.GetMd5Hash(changeUserPasswordViewModel.NewPassword); user.UserProfile.Password = newPassword; var updatedUser = _userService.Update(user); CustomMembershipProvider.SetPassCodeCookie(user.UserProfile.UserName, user.UserProfile.Password); message.type = MessageType.success; _constantService.TryGetValue <string>("ChangePasswordWasSuccessFull", out text); message.text = text /*Core.Resources.Messages.ChangePasswordWasSuccessFull*/; } else { message.type = MessageType.error; _constantService.TryGetValue <string>("IncorrectPassword", out text); message.text = text /*Core.Resources.ExceptionMessage.IncorrectPassword*/; } } } else { message.type = MessageType.error; _constantService.TryGetValue <string>("ConfirmPasswordWasNotMatched", out text); message.text = text /*Core.Resources.ExceptionMessage.ConfirmPasswordWasNotMatched*/; } MessageStrore.Add(message); }
public ActionResult ChangePassword(ChangeUserPasswordViewModel changeUserPasswordViewModel) { if (changeUserPasswordViewModel.ID != SessionDTO.ID && SessionDTO.IsAdmin == false) { return(new ViewResult { ViewName = "InsufficientPermission" }); } if (ModelState.IsValid) { HashingPasswordService hashingPasswordService = new HashingPasswordService(); string salt = "sheldonthemightylittlegeniusman"; string hashedPassword = hashingPasswordService.GenerateSHA256Hash(changeUserPasswordViewModel.Password, salt); changeUserPasswordViewModel.Password = hashedPassword; List <Users> allUsers = UnitOfWork.UOW.UserRepository.GetAll(); Users user = allUsers.Where(x => x.ID == changeUserPasswordViewModel.ID).FirstOrDefault(); user.Password = changeUserPasswordViewModel.Password; return(base.Update(user)); } return(View(changeUserPasswordViewModel)); }
public async Task <IActionResult> ChangeUserPassword(ChangeUserPasswordViewModel changeUserPasswordViewModel) { if (ModelState.IsValid) { var user = await _userManager.Users.FirstOrDefaultAsync(a => a.Id == changeUserPasswordViewModel.id); if (user != null) { var result = await _userManager.ChangePasswordAsync(user, changeUserPasswordViewModel.OldPassword, changeUserPasswordViewModel.NewPassword); if (result.Succeeded) { return(RedirectToAction(nameof(ListUsers), new { Message = ManageMessageId.ChangePasswordSuccess })); } AddErrors(result); return(View(changeUserPasswordViewModel)); } return(RedirectToAction(nameof(ListUsers), new { Message = ManageMessageId.Error })); } return(View(changeUserPasswordViewModel)); }
// GET: Membership/Home/ChangePassword/xxx public async Task <IActionResult> ChangePassword(string id) { if (id == null) { return(NotFound()); } ApplicationUser appUser = await _userManager.FindByIdAsync(id); if (appUser == null) { return(NotFound()); } ChangeUserPasswordViewModel changePassword = new ChangeUserPasswordViewModel(); changePassword.Id = appUser.Id; changePassword.Email = appUser.Email; return(View(changePassword)); }
public async Task <ActionResult> ChangeUserPassword(ChangeUserPasswordViewModel model) { if (ModelState.IsValid) { var preresult = await UserManager.RemovePasswordAsync(model.UserId); if (preresult.Succeeded) { var result = await UserManager.AddPasswordAsync(model.UserId, model.NewPassword); if (result.Succeeded) { return(RedirectToAction("EmployeePortal", "Manage")); } AddErrors(result); } AddErrors(preresult); } // If we got this far, something failed, redisplay form return(View(model)); }
public async Task <ActionResult> ChangeUserPassword(int id, ChangeUserPasswordViewModel passwordViewModel) { var user = await _userManager.FindByIdAsync(id.ToString()); if (!ModelState.IsValid) { return(CustomResponse(ModelState)); } if (user == null) { return(NotFound()); } var result = await _userManager.RemovePasswordAsync(user); if (!result.Succeeded) { foreach (var error in result.Errors) { NotifyError(error.Description); } return(CustomResponse(ModelState)); } result = await _userManager.AddPasswordAsync(user, passwordViewModel.Password); if (!result.Succeeded) { foreach (var error in result.Errors) { NotifyError(error.Description); } } return(CustomResponse(ModelState)); }