public ActionResult ChangePassword(ManageUserViewModel model) { HttpCookie cookie = HttpContext.Request.Cookies["PointsCookie"]; NameValueCollection collection = cookie.Values; var username = collection["username"].ToString(); var user = this.pointsDbEntity.Users.First(a => string.Compare(a.Username, username) == 0); if (user != null) { var hashedResult = MD5Hasher.Hash(model.OldPassword); var isPasswordValid = string.Compare(user.Password, hashedResult) == 0; if (ModelState.IsValid && isPasswordValid) { user.Password = MD5Hasher.Hash(model.NewPassword); this.pointsDbEntity.Entry(user).State = EntityState.Modified; this.pointsDbEntity.SaveChanges(); return RedirectToAction("ChangePassword", new { message = "修改成功!" }); } else { var modelErrors = ModelState.Values.SelectMany(a => a.Errors).ToList(); foreach (var error in modelErrors) { ModelState.AddModelError("", error.ErrorMessage); } } } return View("Index"); }
public async Task<ActionResult> Manage(ManageUserViewModel model) { bool hasPassword = HasPassword(); ViewBag.HasLocalPassword = hasPassword; ViewBag.ReturnUrl = Url.Action("Manage"); if (hasPassword) { if (ModelState.IsValid) { IdentityResult result = await UserManager.ChangePasswordAsync(User.Identity.GetUserId(), model.OldPassword, model.NewPassword); if (result.Succeeded) { return RedirectToAction("Manage", new { Message = ManageMessageId.ChangePasswordSuccess }); } else { AddErrors(result); } } } else { // User does not have a password so remove any validation errors caused by a missing OldPassword field ModelState state = ModelState["OldPassword"]; if (state != null) { state.Errors.Clear(); } if (ModelState.IsValid) { IdentityResult result = await UserManager.AddPasswordAsync(User.Identity.GetUserId(), model.NewPassword); if (result.Succeeded) { return RedirectToAction("Manage", new { Message = ManageMessageId.SetPasswordSuccess }); } else { AddErrors(result); } } } // If we got this far, something failed, redisplay form return View(model); }