public ActionResult EditPassword() { //prevents users from accessing this method if they are not logged in or if they are admin if (userSession.LoggedIn == false) { return(Content("You are not logged in! Please login to view this page.")); } Account account = userSession.CurrentUser; var adminUser = accountPermissionDAO.FetchByEmail(account.email); if (adminUser != null) { TempData["errorMessage"] = "To change your password, please logout and click on 'Forgotten Your Password' on the homepage"; return(RedirectToAction("SiteActivity", "Alert")); } EditPasswordViewModel model = new EditPasswordViewModel(); if (userSession.LoggedIn == true) { model.userSession = true; } else if (userSession.LoggedIn == false) { model.userSession = false; } model.adminUser = false; model.loggedInAccount = account; model.loggedInAccountID = account.accountID; return(View(model)); }
public ActionResult EditPassword(EditPasswordViewModel model, string currentPassword, string newPassword) { //updates the password of the logged in user Account account = userSession.CurrentUser; currentPassword = model.currentPassword.Encrypt(account.email); if (account != null) { if (account.password == currentPassword) { account.password = model.newPassword.Encrypt(account.email); accountDAO.Update(account); TempData["successMessage"] = "Your password has been changed !"; } else { TempData["errorMessage"] = "The current password is incorrect"; } } else { TempData["errorMessage"] = "we could not update your password"; } return(View(model)); }
public async Task <ActionResult> EditPassword(EditPasswordViewModel model) { if (ModelState.IsValid) { User user = await _userService.GetAsync(Utility.Helpers.IdentityHelpers.GetUserId(this.HttpContext.User.Identity)); if (_userService.VerifyPassword(user, model.CurrentPassword)) { ServiceOperationResult result = _userService.SetPassword(user, model.NewPassword); if (result.Succeeded) { _uow.Commit(); await _userService.SendEmailAsync(user, EmailHelpers.UserEmails.AccountPropertyChanged("Password")); TempData.Add(KeyTempDataAccountUpdates, new List <String>() { "Password has been changed successfully." }); return(RedirectToAction("Index")); } } else { ModelState.AddErrorForProperty <EditPasswordViewModel>(m => m.CurrentPassword, "Password is invalid."); } } //If we got this far something failed return(View(model)); }
public async Task <ActionResult> EditPassword([Bind(Prefix = "EditPasswordViewModel")] EditPasswordViewModel model) { if (!ModelState.IsValid) { TempData["ViewData"] = ViewData; return(RedirectToAction("Index", new { Message = ManageMessageId.Error })); } var result = await UserManager.ChangePasswordAsync(User.Identity.GetUserId(), model.OldPassword, model.NewPassword); if (result.Succeeded) { var user = await UserManager.FindByIdAsync(User.Identity.GetUserId()); if (user != null) { await SignInAsync(user, isPersistent : false); } return(RedirectToAction("Index", new { Message = ManageMessageId.ChangePasswordSuccess })); } AddErrors("password-error", result); // jeśli logowanie nie powiodło się: if (!ModelState.IsValid) { TempData["ViewData"] = ViewData; return(RedirectToAction("Index", new { Message = ManageMessageId.Error })); } return(RedirectToAction("Index", new { Message = ManageMessageId.ChangePasswordSuccess })); }
public IHttpActionResult EditPassword(EditPasswordViewModel model) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } var user = db.Users.Find(model.ID); user.UserPassword = model.Password; db.Entry(user).State = EntityState.Modified; try { db.SaveChanges(); } catch (DbUpdateConcurrencyException) { if (!UserExists(model.ID)) { return(NotFound()); } else { throw; } } return(StatusCode(HttpStatusCode.NoContent)); }
public async Task <IActionResult> EditPassword(EditPasswordViewModel newPasswrd) { if (ModelState.IsValid) { var user = await _user.FindByNameAsync(User.Identity.Name); var passwordsMatch = await _user.CheckPasswordAsync(user, newPasswrd.OldPassword); if (passwordsMatch) { var passwordHasher = HttpContext.RequestServices .GetService(typeof(IPasswordHasher <User>)) as IPasswordHasher <User>; user.PasswordHash = passwordHasher.HashPassword(user, newPasswrd.NewPassword); var res = await _user.UpdateAsync(user); if (res.Succeeded) { await _notify.AboutSecurityAsync(SecurityReason.PasswordUpdated, user.Email); return(View("Index", new Tuple <ProfileViewModel, PassportViewModel>( _profile.ConstructView(user), _passport.ConstructView(user)))); } } ModelState.AddModelError(string.Empty, "Incorrect current password!"); } return(View("Index", new Tuple <ProfileViewModel, PassportViewModel>( _profile.ConstructView(_user.WithProfile(User.Identity.Name)), _passport.ConstructView(_user.WithPassport(User.Identity.Name))))); }
public async Task <ActionResult> ForcePassword([FromBody] EditPasswordViewModel model) { if (!ModelState.IsValid) { return(Json(new { success = false, message = ErrorModelValidation.ShowError(new SerializableError(ModelState).Values) })); } try { var user = _userManager.FindByIdAsync(model.Id).Result; var Token = await _userManager.GeneratePasswordResetTokenAsync(user); var result = await _userManager.ResetPasswordAsync(user, Token, model.Password); if (result.Succeeded) { return(Json(new { success = true, message = "La contraseña se ha cambiado satisfactoriamente." })); } else { string ErrorMsj = string.Concat(" - ", result.Errors.Select(x => x.Code)); return(Json(new { success = false, message = ErrorMsj })); } } catch (Exception excError) { return(Json(new { success = false, message = excError.Message })); } }
public ActionResult EditPassword(EditPasswordViewModel model, long id) { try { if (!ModelState.IsValid) { return(View(model)); } var user = _userManager.GetById(id); if (user.password != PasswordHashing.HashPassword (model.Password, user.passwordSalt)) { throw new Exception(Resource.WrongPassword); } var newSalt = PasswordHashing.GenerateSaltValue(); user.passwordSalt = newSalt; user.password = PasswordHashing.HashPassword(model.NewPassword, newSalt); _userManager.Update(user); return(RedirectToRoute("UserPage")); } catch (Exception e) { model.Error = e.Message; return(View(model)); } }
public ActionResult EditPassword(EditPasswordViewModel model, string currentPassword, string NewPassword) { if (ModelState.IsValid) { Account account = userSession.CurrentUser; currentPassword = model.currentPassword.Encrypt(account.email); if (account.password == currentPassword) { account.password = model.newPassword.Encrypt(account.email); accountDAL.Update(account); TempData["successMessage"] = "Your password has been changed !"; } else if (account.password != currentPassword) { TempData["errorMessage"] = "The current password is incorrect"; } else { TempData["errorMessage"] = "An error occured. We could not update your password. Contact customer service for further assistance"; } } return(View(model)); }
public ActionResult PartialPassword(string id) { EditPasswordViewModel model = new EditPasswordViewModel(); model.UserId = int.Parse(id); model.UserName = System.Web.HttpContext.Current.Request.Cookies["User"].Value; return(View(model)); }
public ActionResult EditCashier(string id) { EditPasswordViewModel model = new EditPasswordViewModel(); var user = DbContext.Users.Find(id); model.Email = user.Email; model.Id = id; return(View(model)); }
public async Task <ActionResult> EditCashier(EditPasswordViewModel model) { var user = await _UserManager.FindByIdAsync(model.Id); var token = await _UserManager.GeneratePasswordResetTokenAsync(user); var result = await _UserManager.ResetPasswordAsync(user, token, model.NewPassword); return(RedirectToAction("Accountants")); }
public async Task <IActionResult> EditPasswordAsync([FromBody] EditPasswordViewModel info) { var appUser = _userManager.Users.SingleOrDefault(u => u.Email == info.Email); var check = await _userManager.ChangePasswordAsync(appUser, info.OldPassword, info.NewPassword); if (check.Succeeded) { return(Ok("Success")); } return(Conflict("Invalid Infomation!!!")); }
public async Task <IActionResult> EditPassword(EditPasswordViewModel model) { if (!ModelState.IsValid) { return(View(model)); } var user = await _userManager.FindByIdAsync(model.Id); if (user != null) { var validator = HttpContext.RequestServices.GetService(typeof(IPasswordValidator <Domain.User.UserModel>)) as IPasswordValidator <Domain.User.UserModel>; var hasher = HttpContext.RequestServices.GetService(typeof(IPasswordHasher <Domain.User.UserModel>)) as IPasswordHasher <Domain.User.UserModel>; if (validator == null) { return(View(model)); } var result = await validator.ValidateAsync(_userManager, user, model.NewPassword); if (!result.Succeeded) { foreach (var error in result.Errors) { ModelState.AddModelError(string.Empty, error.Description); } } else { if (hasher != null) { user.PasswordHash = hasher.HashPassword(user, model.NewPassword); } await _userManager.UpdateAsync(user); return(RedirectToAction("Index", "Home")); } } else { ModelState.AddModelError(string.Empty, "Пользователь не найден"); } return(View(model)); }
public async Task <IActionResult> ChangePassword(string id) { UserEntity user = await _userManager.FindByIdAsync(id); if (user == null) { return(NotFound()); } EditPasswordViewModel model = new EditPasswordViewModel { Id = user.Id, Email = user.Email }; return(View(model)); }
public IActionResult ChangePassword(EditPasswordViewModel model) { if (!ModelState.IsValid) { Alert.Warning(); var viewModel = new FormModel <EditPasswordViewModel>(model, true); return(View(viewModel)); } editUserPassword.Invoke(LoggedUser.UserModel.Id, model.NewPassword); Alert.Success("Your password has been changed"); return(RedirectToAction("Me")); }
public IActionResult EditPassword(EditPasswordViewModel model) { if (ModelState.IsValid) { model.UserName = User.Identity.Name; var result = ProfileLogic.EditPassword(model); TempData.AddOrUpdate("EditPasswordMessage", result); return(RedirectToAction("Edit", "Account")); } if (ModelState["ConfirmPassword"].ValidationState == ModelValidationState.Invalid) { ModelState.AddModelError(string.Empty, "Passwords don't match"); } return(RedirectToAction("Edit", "Account")); }
public async Task <JsonResult> EditPassword(EditPasswordViewModel model) { var errMsg = ""; if (!ModelState.IsValid) { foreach (var modelStateValue in ModelState.Values) { foreach (var error in modelStateValue.Errors) { errMsg += error.ErrorMessage + "\n"; } } return(Json(new ResponseData() { Success = false, Message = "Bir hata oluştu, " + errMsg })); } var user = await _userManager.GetUserAsync(User); var result = await _userManager.ChangePasswordAsync(user, model.CurrentPassword, model.ConfirmNewPassword); if (result.Succeeded) { return(Json(new ResponseData() { Success = true, Message = "Şifre değiştirme işlemi başarılı" })); } else { foreach (var identityError in result.Errors) { errMsg += identityError.Description + "\n"; } return(Json(new ResponseData() { Success = false, Message = "Bir hata oluştu, " + errMsg, })); } }
public IActionResult DoEditPassword(EditPasswordViewModel viewModel, MobileModel mobileModel) { var user = _sysUserService.Queryable().FirstOrDefault(x => x.Id == HttpContext.Session.GetObjectFromJson <SysUserViewModel>("CurrentUser").Id&& x.IsDeleted == false); if (user != null) { if (!BCrypt.Net.BCrypt.Verify(viewModel.CurrentPassword, user.Password)) { if (mobileModel.IsMobile) { return(new JsonResult(new { code = EnumResponseStatus.WARNING, error_message_key = CPLConstant.MobileAppConstant.EditPasswordScreenInvalidCurrentPassword })); } return(new JsonResult(new { success = false, name = "current-password", message = LangDetailHelper.Get(HttpContext.Session.GetInt32("LangId").Value, "InvalidCurrentPassword") })); } user.Password = viewModel.NewPassword.ToBCrypt(); HttpContext.Session.SetObjectAsJson("CurrentUser", Mapper.Map <SysUserViewModel>(user)); _sysUserService.Update(user); _unitOfWork.SaveChanges(); if (mobileModel.IsMobile) { return(new JsonResult(new { code = EnumResponseStatus.SUCCESS, success_message_key = CPLConstant.MobileAppConstant.EditPasswordScreenPasswordUpdatedSuccessfully })); } return(new JsonResult(new { success = true, message = LangDetailHelper.Get(HttpContext.Session.GetInt32("LangId").Value, "PasswordUpdated") })); } if (mobileModel.IsMobile) { return(new JsonResult(new { code = EnumResponseStatus.WARNING, error_message_key = CPLConstant.MobileAppConstant.EditPasswordScreenNonExistingAccount })); } return(new JsonResult(new { success = false, message = LangDetailHelper.Get(HttpContext.Session.GetInt32("LangId").Value, "NonExistingAccount") })); }
public ActionResult EditPassword(string username) { var entity = _membershipService.GetUser(username); if (entity != null) { var model = new EditPasswordViewModel() { Username = entity.Username, }; return(View(model)); } else { ErrorNotification(new Exception("未找到用户")); return(RedirectToAction("MainPage", "Employee")); } }
public async Task <IActionResult> EditPasswordPost(EditPasswordViewModel model) { // Ensure we have permission if (!await _authorizationService.AuthorizeAsync(User, Permissions.ResetUserPasswords)) { return(Unauthorized()); } if (ModelState.IsValid) { var user = await _userManager.FindByIdAsync(model.Id); if (user != null) { var result = await _platoUserManager.ResetPasswordAsync( model.Email, model.ResetToken, model.NewPassword); if (result.Succeeded) { _alerter.Success(T["Password Updated Successfully!"]); // Redirect back to edit user return(RedirectToAction(nameof(Edit), new RouteValueDictionary() { ["id"] = user.Id.ToString() })); } else { foreach (var error in result.Errors) { ViewData.ModelState.AddModelError(string.Empty, error.Description); } } } } // If we reach this point the found user's reset token does not match the supplied reset token return(await EditPassword(model.Id)); }
public JsonResult EditPassword([Bind(Include = "OldPassword,NewPassword")] EditPasswordViewModel model) { if (ModelState.IsValid) { var user = Session["User"] as User; if (BCrypt.Net.BCrypt.Verify(model.OldPassword, user.Password)) { user.Password = BCrypt.Net.BCrypt.HashPassword(model.NewPassword, 14); db.Entry(user).State = EntityState.Modified; db.SaveChanges(); Session["User"] = db.Users.Include(u => u.Logo).Single(u => u.ID == user.ID); return(Json(new SuccessMessage("Su contraseña se ha actualizado con éxito."))); } else { ModelState.AddModelError("OldPassword", "Su vieja contraseña no concuerda. Escríbala de nuevo."); } } return(Json(new ErrorMessageWithValue <Dictionary <string, string> >("", GetModelErrors(ModelState)))); }
private void ValidateEditPasswordViewModel(EditPasswordViewModel model) { if (string.IsNullOrEmpty(model.OldPassword)) { ModelState.AddModelError("OldPassword", "旧密码不能为空"); } if (string.IsNullOrWhiteSpace(model.NewPassword)) { ModelState.AddModelError("NewPassword", "新密码不能为空"); } if (string.IsNullOrWhiteSpace(model.RepeatNewPassword)) { ModelState.AddModelError("RepeatNewPassword", "重复密码不能为空"); } if (model.NewPassword != model.RepeatNewPassword) { ModelState.AddModelError("NewPassword", "新密码不一致"); } }
public async Task <IActionResult> ChangePassword(EditPasswordViewModel model) { if (ModelState.IsValid) { UserEntity user = await _userManager.FindByIdAsync(model.Id); if (user != null) { var _passwordValidator = HttpContext.RequestServices.GetService(typeof(IPasswordValidator <UserEntity>)) as IPasswordValidator <UserEntity>; var _passwordHasher = HttpContext.RequestServices.GetService(typeof(IPasswordHasher <UserEntity>)) as IPasswordHasher <UserEntity>; IdentityResult result = await _passwordValidator.ValidateAsync(_userManager, user, model.CreatenewPassword); if (result.Succeeded) { user.PasswordHash = _passwordHasher.HashPassword(user, model.CreatenewPassword); await _userManager.UpdateAsync(user); return(RedirectToAction("Index")); } else { foreach (var error in result.Errors) { ModelState.AddModelError(string.Empty, error.Description); } } } else { ModelState.AddModelError(string.Empty, "User not found!"); } } return(View(model)); }
public async Task <IActionResult> EditPassword(EditPasswordViewModel model) { if (model == null) { return(RedirectToAction("EditAccount")); } if (ModelState.IsValid) { var user = await _userManager.GetUserAsync(User).ConfigureAwait(true); if (user == null) { return(RedirectToAction("Login")); } var result = await _userManager.ChangePasswordAsync(user, model.Password, model.NewPassword).ConfigureAwait(true); return(Json(result)); } return(RedirectToAction("EditAccount")); }
public ActionResult EditPassword(EditPasswordViewModel model) { try { UserDto dto = new UserDto(); Message msg = new Message(); DataTable dt = CMSService.SelectOne("User", "CMSUser", "UserPassword='******' and UserId=" + model.UserId); if (dt.Rows.Count == 0) { msg.MessageStatus = "Error"; msg.MessageInfo = "原密码错误"; ViewBag.Status = msg.MessageStatus; ViewBag.msg = msg.MessageInfo; return(View("UserInfo")); } else { msg = CMSService.UpdateFieldOneByOne("User", "CMSUser", "UserPassword='******' and UserId=" + model.UserId, "UserPassword", CommonTools.ToMd5(model.UserPassword)); msg.MessageStatus = "Success"; msg.MessageInfo = "密码修改成功了"; ViewBag.Status = msg.MessageStatus; // TODO: Add delete logic here return(RedirectTo("/Login/Login", msg.MessageInfo)); } } catch { Message msg = new Message(); msg.MessageStatus = "Error"; msg.MessageInfo = "操作出错了"; ViewBag.Status = msg.MessageStatus; ViewBag.msg = msg.MessageInfo; return(View("UserInfo")); } }
public ActionResult EditPassword(EditPasswordViewModel model) { try { ValidateEditPasswordViewModel(model); if (ModelState.IsValid) { using (var unitOfWork = UnitOfWorkManager.NewUnitOfWork()) { var user = MembershipService.ValidateUser(model.Username, model.OldPassword); if (user != null) { user.Password = XL.Utilities.MD5Helper.MD5Encrypt(model.NewPassword); unitOfWork.Commit(); SuccessNotification("修改成功"); } else { ErrorNotification(new Exception("旧密码错误,请重试")); } return(View(model)); } } else { ErrorNotification(new Exception("修改失败,请检查输入项")); return(View(model)); } } catch (Exception ex) { ErrorNotification(new Exception("修改失败,原因是: " + ex.Message)); return(View(model)); } }
public async Task <ActionResult> EditPassword(EditPasswordViewModel model) { if (ModelState.IsValid) { var user = _userService.Get(IdentityHelpers.GetUserId(User.Identity)); if (_userService.IsPasswordMatchForUser(user.UserID, model.CurrentPassword)) { _userService.SetPassword(user.UserID, model.NewPassword); _uow.Save(); String subject = "Account Password Change"; String body = "This email is to inform you that the password associated with your account has been changed."; await _userService.SendEmailAsync(user.UserID, subject, body); ViewBag.SuccessMessage = "Password has been changed successfully."; ModelState.Clear(); return(View()); } else { ModelState.AddModelError("CurrentPassword", "Password is invalid."); return(View(model)); } } else { return(View(model)); } }
public async Task <IActionResult> EditPassword(EditPasswordViewModel model) { if (ModelState.IsValid) { AppUser user = await _userManager.FindByNameAsync(User.Identity.Name); if (await _userManager.CheckPasswordAsync(user, model.OldPassword)) { IdentityResult result = await _userManager.ChangePasswordAsync(user, model.OldPassword, model.NewPassword); if (!result.Succeeded) { result.Errors.ToList().ForEach(e => ModelState.AddModelError(e.Code, e.Description)); return(View(model)); } await _userManager.UpdateSecurityStampAsync(user); await _signInManager.SignOutAsync(); await _signInManager.SignInAsync(user, true); } } return(RedirectToAction("Index")); }
public ActionResult EditPassword(EditPasswordViewModel model) { //取得用戶IP string clintIp = ""; if (string.IsNullOrEmpty(Request.ServerVariables["HTTP_VIA"])) { //用戶非使用代理伺服器 clintIp = Request.ServerVariables["REMOTE_ADDR"].ToString(); } else { //用戶使用代理伺服器 clintIp = Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString(); } var result = service.EditPassword(model.Password, clintIp); if (!result.RESULT) { return(Json(new { result = result.RESULT, message = result.ERRMSG }, JsonRequestBehavior.AllowGet)); } return(Json(new { result = result.RESULT, message = "您的密碼已經更新成功,請繼續瀏覽!", url = Url.Action("Index", "Home") + "#login" }, JsonRequestBehavior.AllowGet)); }