public void UserController_ChangePassword_ValidViewModel_CallsService() { // Given _Controller.TempData = new TempDataDictionary(httpContext, Mock.Of <ITempDataProvider>()); var UserVm = new PasswordViewModel() { EmailAddress = "*****@*****.**", NewPassword = "******" }; _svc.Setup( m => m.UpdatePassword( UserVm.EmailAddress, UserVm.NewPassword)).Returns(true); // When _Controller.ChangePassword(UserVm); // Then _svc.Verify(r => r.UpdatePassword( UserVm.EmailAddress, UserVm.NewPassword), Times.Once()); }
public void UserController_ChangePassword_InValidViewModel_DoesNotCallService() { // Given _Controller.TempData = new TempDataDictionary(httpContext, Mock.Of <ITempDataProvider>()); var UserVm = new PasswordViewModel() { EmailAddress = "*****@*****.**", NewPassword = "******" }; _svc.Setup( m => m.UpdatePassword( UserVm.EmailAddress, UserVm.NewPassword)).Returns(true); _Controller.ModelState.AddModelError("Oh Oh", "Oh, oh"); // When var Result = _Controller.ChangePassword(UserVm) as ViewResult; var Model = (PasswordViewModel)Result.ViewData.Model; // Then _svc.Verify(r => r.UpdatePassword( UserVm.EmailAddress, UserVm.NewPassword), Times.Never()); }
public PasswordPage(PasswordModel model) { InitializeComponent(); _VM = _VM ?? new PasswordViewModel(model); this.BindingContext = _VM; }
public IActionResult ResetPassword([FromBody] PasswordViewModel password) { string newPassword = password.Password.SHA256Encrypt(); if (!ModelState.IsValid) { return(BadRequest(ModelState.GetErrors().First())); } int userId = User.Claims.GetUserId(); User user = userRepository.GetUserById(userId); if (user == null) { return(NotFound()); } if (user.Password == newPassword) { return(BadRequest("Your new password cannot be the same as the old one.")); } user.Password = newPassword; userRepository.UpdateUser(user); return(Ok()); }
public void UserController_ChangePassword_ValidViewModel_Redirects() { // Given _Controller.TempData = new TempDataDictionary(httpContext, Mock.Of <ITempDataProvider>()); var UserVm = new PasswordViewModel() { EmailAddress = "*****@*****.**", NewPassword = "******" }; _svc.Setup( m => m.UpdatePassword( UserVm.EmailAddress, UserVm.NewPassword)).Returns(true); // When var Result = (RedirectToActionResult)_Controller.ChangePassword(UserVm); var RouteValue = (Object[])Result.RouteValues.Values; // Then Assert.Equal("User", Result.ControllerName); Assert.Equal("UserSettings", Result.ActionName); Assert.Equal("*****@*****.**", RouteValue[0].ToString()); }
public IActionResult Password(PasswordViewModel passwordViewModel) { if (ModelState.IsValid) { IdentityUser identityUser = userManager.FindByIdAsync(userManager.GetUserId(HttpContext.User)).Result; var result = userManager.RemovePasswordAsync(identityUser).Result; if (result.Succeeded) { result = userManager.AddPasswordAsync(identityUser, passwordViewModel.Password).Result; if (result.Succeeded) { return(RedirectToAction("Index")); } ModelState.AddModelError("", "Nie można zmienić hasła!"); } else { ModelState.AddModelError("", "Nie można zmienić hasła!"); } } return(View(passwordViewModel)); }
public async Task TestPassword() { await Login("*****@*****.**", "ktbffh"); // Post password var pass = new PasswordViewModel() { Length = 5, LowerChars = true, UpperChars = true, Digits = true, Symbols = false, Hint = "ktbffh" }; var id = 0; using (var response = await _client.PostAsJsonAsync("/api/password", pass)) { var responseString = await response.Content.ReadAsStringAsync(); dynamic res = JObject.Parse(responseString); Assert.Equal(true, (bool)res.success); id = (int)res.id; } // Get user's passwords using (var responseGet = await _client.GetAsync("/api/user/jt26/passwords")) { responseGet.EnsureSuccessStatusCode(); } // Log out await _client.DeleteAsync("/api/logout/" + id); }
public ActionResult ChangePassword(PasswordViewModel model) { if (model != null) { var userLogin = (UserLogin)Session[Managing_Teacher_Work.Common.CommonConstants.USER_SESSION]; if (model.PasswordNew.Trim() != model.PasswordConfirm.Trim()) { SetAlert("Xác nhận mật khẩu không chính xác!", "warning"); } else { var user = db.User.SingleOrDefault(x => x.ID == userLogin.ID); if (user.Password != Encryptor.MD5Hash(model.Password)) { SetAlert("Mật khẩu hiện tại không chính xác!", "error"); } else { user.Password = Encryptor.MD5Hash(model.PasswordNew); user.ModifiedDate = System.DateTime.Now; db.SaveChanges(); model = null; SetAlert("Cập nhật thông tin thành công! :D", "success"); } } } return(RedirectToAction("Profile")); }
public ActionResult NewPassword(PasswordViewModel model) { if (ModelState.IsValid) { if (ctx.Ligues.Where(a => a.email == model.Email).Count() == 1) { ModelState.AddModelError("", "Votre nouveau mot de passe a été envoyé sur votre adresse email."); Ligues l = ctx.Ligues.Where(a => a.email == model.Email).FirstOrDefault(); ctx.Ligues.Attach(l); String tmp = generator(); l.password = encrypt(tmp); ctx.SaveChanges(); envoyer(l.email, l.Libelle, "", tmp); } else if (ctx.Responsable.Where(a => a.Email == model.Email).Count() == 1) { ModelState.AddModelError("", "Votre nouveau mot de passe a été envoyé sur votre adresse email."); Responsable r = ctx.Responsable.Where(a => a.Email == model.Email).FirstOrDefault(); ctx.Responsable.Attach(r); String tmp = generator(); r.Password = encrypt(tmp); ctx.SaveChanges(); envoyer(r.Email, r.Nom, r.Prenom, tmp); } else { ModelState.AddModelError("", "Cette adresse email est introuvable."); } } return(View(model)); }
public ActionResult Password(PasswordViewModel model) { if (Session["userid"] != null) { if (ModelState.IsValid) { if (model.newPaswword == model.reNewPassword) { int idAuthor = (int)Session["userid"]; var author = _context.getAuthors().Where(n => n.Pass == model.oldPassword && n.IdAuthor == idAuthor).SingleOrDefault(); if (author != null) { author.Pass = model.newPaswword; _context.getContext().SaveChanges(); TempData["MessageSuccess"] = "Pomyślnie zmieniono hasło !"; return(View(model)); } TempData["Message"] = "Stare hasło nie pasuje"; } else { TempData["Message"] = "Podane nowe hasła nie pasują do siebie"; } } return(View(model)); } else { return(Redirect("~/Login")); } }
public IActionResult Password(PasswordViewModel model) { if (ModelState.IsValid) { var id = Int32.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value); var user = _repository.DohvatiPrekoID(id); if (!user.Lozinka.Equals(model.StaraLoz)) { ModelState.AddModelError("StaraLoz", "Pogrešna lozinka."); return(View(model)); } if (!model.NovaLoz.Equals(model.NovaLozPon)) { ModelState.AddModelError("NovaLoz", "Lozinke nisu iste."); return(View(model)); } user.Lozinka = model.NovaLoz; _repository.Azuriraj(user); return(RedirectToAction("Index", "Home")); } else { return(View(model)); } }
public async Task <ActionResult> ResetPass(PasswordViewModel viewModel) { ViewBag.ViewModel = viewModel; UserProfile item = models.GetTable <UserProfile>().Where(u => u.PID == viewModel.PID && u.LevelID == (int)Naming.MemberStatusDefinition.Checked) .FirstOrDefault(); if (item == null) { return(Redirect($"~{Startup.Properties["LoginUrl"]}")); } ViewBag.ModelState = this.ModelState; if (!this.CreatePassword(viewModel)) { return(View(item)); } item.Password = (viewModel.Password).MakePassword(); //models.DeleteAllOnSubmit<ResetPassword>(r => r.UID == item.UID); models.SubmitChanges(); await HttpContext.SignOnAsync(item); return(Redirect(this.ProcessLogin(item))); }
public ActionResult ChangePassword([Bind(Include = "ID,Sifre,YeniSifre,YeniSifreOnay")] PasswordViewModel password) { Kullanicilar sifresiDegisecekOlanKullanici = db.Kullanicilar.Find(password.ID); if (ModelState.IsValid) { if (password.Sifre != sifresiDegisecekOlanKullanici.Sifre) { sifresiDegisecekOlanKullanici.PasswordErrorMessage = "Şifrenizi doğru girmediniz!"; sifresiDegisecekOlanKullanici.Sifre = null; return(PartialView(@"~\Views\Depremler\AccountPartial.cshtml", sifresiDegisecekOlanKullanici)); } if (password.YeniSifre == password.Sifre) { sifresiDegisecekOlanKullanici.PasswordErrorMessage = "Yeni şifre ve eski şifre aynı olamaz!"; sifresiDegisecekOlanKullanici.Sifre = null; return(PartialView(@"~\Views\Depremler\AccountPartial.cshtml", sifresiDegisecekOlanKullanici)); } sifresiDegisecekOlanKullanici.Sifre = password.YeniSifre; sifresiDegisecekOlanKullanici.SifreOnay = password.YeniSifre; db.SaveChanges(); return(Json(new { url = Url.Action("Index", "Depremler") })); } return(PartialView(@"~\Views\Depremler\AccountPartial.cshtml", sifresiDegisecekOlanKullanici)); }
public async Task <IActionResult> EditPasswordPost(PasswordViewModel passwordViewModel, string token, int id) { if (ModelState.IsValid) { var userToUpdate = await DbContext.Users.FirstOrDefaultAsync(s => s.UserId == id); if (await TryUpdateModelAsync <DbUser>(userToUpdate, "", s => s.Password)) { try { userToUpdate.Password = HashProfile.GetSaltedHashData(userToUpdate.Password, userToUpdate.PasswordSalt); await DbContext.SaveChangesAsync(); return(RedirectToAction("Login", "Auth")); } catch (DbUpdateException) { ModelState.AddModelError("", "Unable to save changes. " + "Try again, and if the problem persists, " + "see your system administrator."); } } } return(View(passwordViewModel)); }
public async Task <IActionResult> ChangePassword([FromBody] PasswordViewModel model) { var CurrentUserId = User.FindFirstValue(ClaimTypes.NameIdentifier); var CurrentUser = await _userManager.FindByIdAsync(CurrentUserId); _logger.LogDebug("In the controller"); if (ModelState.IsValid) { _logger.LogDebug("Model is valid"); var result = await _userManager.CheckPasswordAsync(CurrentUser, model.CurrentPassword); if (result) { _logger.LogDebug("Password checked"); CurrentUser.PasswordHash = _userManager.PasswordHasher.HashPassword(CurrentUser, model.NewPassword); _logger.LogDebug("Password hashed"); } await _userManager.UpdateAsync(CurrentUser); _logger.LogDebug("Password updated"); //or: await _userManager.ChangePasswordAsync(CurrentUser, model.CurrentPassword, model.NewPassword) return(Ok(new MessageViewModel("Your password changed successfully.", DateTime.Now))); } return(BadRequest(new MessageViewModel("Password change failed.", DateTime.Now))); }
public ActionResult ChangePassword(int mid, string cpass, string npass, string rpass) { if (Session["userId"] == null) { return(RedirectToAction("Index", "UserHome")); } if (Convert.ToInt32(Session["userId"]) == mid) { PasswordViewModel p = new PasswordViewModel(); p.ReportCount = _ReportService.GetByUnseenStatus().Count(); p.member = _MemberService.GetById(mid); if (p.member.Password != cpass) { return(RedirectToAction("Change_Password", "Admin", new { id = mid, f = 1 })); } else if (npass != rpass) { return(RedirectToAction("Change_Password", "Admin", new { id = mid, f = 2 })); } else { p.member.Password = npass; _MemberService.Update(p.member); return(RedirectToAction("Dashboard", "Admin", new { id = mid })); } } else { return(RedirectToAction("Dashboard", "Admin")); } }
public async ASYNC.Task <IActionResult> ChangePassword(string id, PasswordViewModel model) { if (!ModelState.IsValid) { // throw exception } var user = await this.userService.GetUserById(id); if (user == null) { return(NotFound($"Unable to load user with ID '{id}'.")); } var changePasswordResult = await this.userManager.ChangePasswordAsync(user, model.OldPassword, model.NewPassword); if (!changePasswordResult.Succeeded) { foreach (var error in changePasswordResult.Errors) { ModelState.AddModelError(string.Empty, error.Description); } // display errors return(RedirectToAction("Password", "Admin", new { id = id })); } await this.signInManager.RefreshSignInAsync(user); this.logger.LogInformation("User changed their password successfully."); model.StatusMessage = "Your password has been changed."; return(RedirectToAction("Password", "Admin", new { id = id, statusMessage = model.StatusMessage })); }
public ActionResult Change_Password(int id, int f = 0) { if (Session["userId"] == null) { return(RedirectToAction("Index", "UserHome")); } if (Convert.ToInt32(Session["userId"]) == id) { PasswordViewModel p = new PasswordViewModel(); p.ReportCount = _ReportService.GetByUnseenStatus().Count(); p.MemberId = id; p.Name = _MemberService.GetById(id).Name; // p.totalProductInCart = _CartService.GetByMemberId(Convert.ToInt32(Session["userId"])).Count(); p.member = _MemberService.GetById(id); if (f == 1) { p.flag = 1; } else if (f == 2) { p.flag = 2; } else { p.flag = 0; } return(View(p)); } else { return(RedirectToAction("Index", "Admin")); } }
public async Task <IActionResult> Password([FromBody] PasswordViewModel model) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } var user = await _userManager.FindByEmailAsync(model.Email); if (user == null) { return(BadRequest(Errors.AddErrorToModelState("user_search_failure", "Could not find user in database.", ModelState))); } if (await _userManager.CheckPasswordAsync(user, model.OldPassword)) { if (model.OldPassword == model.NewPassword) { return(BadRequest(Errors.AddErrorToModelState("user_search_failure", "New password cannot match old password", ModelState))); } await _userManager.ChangePasswordAsync(user, model.OldPassword, model.NewPassword); await _appDbContext.SaveChangesAsync(); return(new OkObjectResult("Password Updated")); } else { return(BadRequest(Errors.AddErrorToModelState("user_search_failure", "Old password is invalid", ModelState))); } }
public ActionResult EditPassword(PasswordViewModel passwordViewModel) { if (ModelState.IsValid) { CustomerDb dbCustomer = new CustomerDb(); bool isPasswordEdited; var w = passwordViewModel; isPasswordEdited = dbCustomer.UpdateCustomerPasword(passwordViewModel); if (isPasswordEdited) { var claimIdentity = User.Identity as ClaimsIdentity; int id = Convert.ToInt32(claimIdentity.FindFirst(ClaimTypes.NameIdentifier).Value); if (id > 0) { return(RedirectToAction("Detail", "Account")); } return(RedirectToAction("Index", "Home")); } return(RedirectToAction("Index", "Home")); } return(RedirectToAction("Index", "Home")); }
/// <summary> /// Update the password of a specific customer /// </summary> /// <param name="passwordViewModel"></param> /// <returns>bool</returns> public bool UpdateCustomerPasword(PasswordViewModel passwordViewModel) { connection(); SqlCommand cmd = new SqlCommand("UpdateUserPassword", con); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@Id", passwordViewModel.IdUser); cmd.Parameters.AddWithValue("@Password", passwordViewModel.Password); con.Open(); try { cmd.ExecuteNonQuery(); return(true); } catch (SqlException ex) { return(false); } finally { con.Close(); } }
public ActionResult EditPassword(PasswordViewModel model) { if (ModelState.IsValid && !model.NewPassword.Equals(model.ConfirmPassword, StringComparison.OrdinalIgnoreCase)) { ModelState.AddModelError("NewPasswordMismatch", "Your new password and confirm password do not match..."); } if (!ModelState.IsValid) { model.NewPassword = string.Empty; model.ConfirmPassword = string.Empty; return(View("_Password", model)); } _registrationService.ChangePassword(UserHelper.UserId.Value, model.NewPassword); var websiteAddress = $@"http://{System.Web.HttpContext.Current.Request.Url.Authority}"; EmailHelper.Send(new List <string> { UserHelper.EmailAddress }, "Account Notice", $"<p>Hello {UserHelper.FullName}</p><p>We just wanted to let you know that your password was changed at {websiteAddress}. If you didn't change your password, please let us know"); return(Content("Refresh")); }
public ActionResult SetPassword(PasswordViewModel pvm, AccountModel am) { string email = SessionPersister.Email.ToString(); int userId = am.find(email).User_ID; if (pvm.Password != pvm.ConfirmPassword) { ViewBag.Error = "Password and confirm password must match."; return(View("Register")); } //update query var query = from acc in db.Accounts where acc.User_ID == userId select acc; foreach (Account acc in query) { acc.Password = Hashing.ComputeHash(pvm.Password); } try { db.SaveChanges(); ViewBag.Message = "You have now registered your password! Please log in."; return(View("Index")); } catch (Exception e) { Console.WriteLine(e); } return(View("Register")); }
public MainWindow() { var vm = new PasswordViewModel(); this.DataContext = vm; InitializeComponent(); }
public async Task <IActionResult> ChangePassword(PasswordViewModel model) { if (!ModelState.IsValid) { IEnumerable <ModelError> allErrors = ModelState.Values.SelectMany(v => v.Errors); return(new BadRequestObjectResult(allErrors)); } else { var userId = User.GetUserId(); var isValid = await _userService.ChangePassword(userId.ToString(), model.CurrentPassword, model.Password); if (isValid) { await _signInManager.SignOutAsync(); return(new OkObjectResult(new GenericResult(true))); } else { return(new OkObjectResult(new GenericResult(false))); } } }
public virtual ActionResult ChangePassword(PasswordViewModel model) { LogI("ChangePassword begin"); if (ModelState.IsValid) { // ChangePassword will throw an exception rather // than return false in certain failure scenarios. bool changePasswordSucceeded; try { MembershipUser currentUser = Membership.GetUser(User.Identity.Name, true /* userIsOnline */); changePasswordSucceeded = currentUser.ChangePassword(model.OldPassword, model.NewPassword); } catch (Exception) { changePasswordSucceeded = false; } if (changePasswordSucceeded) { model.Result = MessageResult.Success("Password has been successfully changed"); } else { ModelState.AddModelError("", "The current password is incorrect or the new password is invalid."); } } return(PartialView("_ChangePasswordPartial", model)); }
public ActionResult ResetPass(PasswordViewModel viewModel) { ViewBag.ViewModel = viewModel; UserProfile item = models.EntityList.Where(u => u.PID == viewModel.PID && u.LevelID == (int)Naming.MemberStatusDefinition.Checked) .FirstOrDefault(); if (item == null) { return(Redirect(FormsAuthentication.LoginUrl)); } ViewBag.ModelState = this.ModelState; if (!this.CreatePassword(viewModel)) { return(View(item)); } item.Password = (viewModel.Password).MakePassword(); //models.DeleteAllOnSubmit<ResetPassword>(r => r.UID == item.UID); models.SubmitChanges(); HttpContext.SignOn(item); return(Redirect(this.ProcessLogin(item))); }
public async Task <IActionResult> Password(PasswordViewModel viewModel) { if (ModelState.IsValid) { var user = await _userManager.FindByNameAsync(viewModel.Login); if (user == null || user.Email != viewModel.Email) { ModelState.AddModelError("", "Пользователя с таким логином и e-mail не существует!"); return(View(viewModel)); } // if user.PasswordHash = _userManager.PasswordHasher.HashPassword(user, viewModel.Password); var result = await _userManager.UpdateAsync(user); if (result.Succeeded) { return(RedirectToAction("Index", "Notices")); } } // if return(View(viewModel)); } // Password
public static bool CreatePassword(this Controller controller, PasswordViewModel viewModel) { if (String.IsNullOrEmpty(viewModel.lockPattern)) { if (String.IsNullOrEmpty(viewModel.Password)) { controller.ModelState.AddModelError("Password", "請輸入密碼!!"); controller.ModelState.AddModelError("lockPattern", "請設定圖形密碼!!"); return(false); } else if (viewModel.Password != viewModel.Password2) { controller.ModelState.AddModelError("Password2", "密碼確認錯誤!!"); return(false); } } else { if (viewModel.lockPattern.Length < 9) { controller.ModelState.AddModelError("lockPattern", "設定圖形的密碼過短!!"); } else { viewModel.Password = viewModel.lockPattern; } } return(true); }
public async Task <ActionResult> ChangePassword(PasswordViewModel vm) { if (ModelState.IsValid) { var user = _userManager.FindByNameAsync(this.User.Identity.Name).Result; if (vm.NewPassword != vm.RepeatNewPassword) { ModelState.AddModelError("PasswordDiferentes", "Los nuevos passwords no coinciden."); } var signInResult = await _signInManager.PasswordSignInAsync(user.UserName, vm.CurrentPassword, false, true); if (!signInResult.Succeeded) { ModelState.AddModelError("PasswordActual", "El password actual no coincide."); } if (ModelState.IsValid) { var result = await _userManager.ChangePasswordAsync(user, vm.CurrentPassword, vm.NewPassword); await _userManager.UpdateAsync(user); if (result.Succeeded) { if (User.Identity.IsAuthenticated) { await _signInManager.SignOutAsync(); } return(RedirectToAction("Login", "Auth")); } } } return(View()); }
public ActionResult ChangePassword(PasswordViewModel viewModel) { if (this.ModelState.IsValid) { Member member = this._membershipService.GetMemberById(viewModel.MemberId); member.UpdatePassword(viewModel.Password); this._membershipService.SaveMember(member); return this.RedirectToRoute(AdminRoutes.Membership.Edit, new { saved = true }); } return this.Edit(viewModel.MemberId); }
public ActionResult EditPassword(PasswordViewModel model) { var data = accountService.GetById(model.Id); if (data == null) return HttpNotFound(); if (accountService.CheckPassword(model.OldPassword, data.Password)) { TempData["alert"] = "舊密碼輸入錯誤"; return View(model); } else if (model.NewPassword != model.PasswordConfirm) { TempData["alert"] = "新密碼輸入不一致"; return View(model); } else { accountService.DbUpdatePassword(model.Id, model.NewPassword); TempData["alert"] = "密碼已成功更改"; return RedirectToAction("Index", "Home"); } }
public ActionResult EditPassword() { // 未登入 if (User.Identity.IsAuthenticated == false) { return RedirectToAction("Login"); } var data = accountService.GetById(Guid.Parse(User.Identity.GetUserId())); if (data == null) return HttpNotFound(); var model = new PasswordViewModel { Id = data.Id }; return View(model); }