public ActionResult ChangePassword(int id, string oldPassword, string newPassword, string confirmPassword) { // Check if password is confirmed // if (newPassword != confirmPassword) { AddMessage(TempData, new Message() { Type = "Danger", Title = "Confirmation Error!", Body = "The confirm password doesn't match!" }); return(RedirectToAction("Home")); } // Check if user with UserID == @id exists // Authorization Authorizer = new Authorization(DbContext, HttpContext); if (!Authorizer.UserExists(id)) { AddMessage(TempData, new Message() { Type = "Danger", Title = "Non-existent User", Body = string.Format("User with id {0} does not exist!", id) }); return(RedirectToAction("Index", "Home")); } // Retrieve the user to change password // Retrieve the currently logged user // var userToChange = DbContext.Users.Find(id); var userCurrent = Authorizer.GetUserFrom(HttpContext); // Check if oldPassword is correct if (Protection.HashPassword(oldPassword, userToChange.Salt) != userToChange.Password) { AddMessage(TempData, new Message() { Type = "Danger", Title = "Confirmation Error!", Body = "Wrong current password!" }); return(RedirectToAction("Home")); } // If current user is not admin // or is not the owner of the account whose password is being changed // redirect to the home page // if (userCurrent.Role.Name != "Admin" && userCurrent.UserID != id) { AddMessage(TempData, new Message() { Type = "Danger", Title = "You Lack Power!", Body = "You can't do what you just tried to do!" }); return(RedirectToAction("Index", "Home")); } // // userToChange exists // AND // userCurrent is either admin or the user who's trying to change his password // // Attempt to change the password // try { userToChange.Password = newPassword; userToChange.SecurePassword(); DbContext.Update(userToChange); DbContext.SaveChanges(); // Updated password successfully // AddMessage(TempData, new Message() { Type = "Success", Title = "Password Changed Successfully!", Body = "The password has been changed successfully!" }); return((userCurrent.Role.Name == "Admin") ? RedirectToAction("Index", "Account") : RedirectToAction("Logout")); } catch { AddMessage(TempData, new Message() { Type = "Danger", Title = "Error While Changing Password!", Body = "The password could not be changed successfully!" }); return((userCurrent.Role.Name == "Admin") ? RedirectToAction("Index", "Account") : RedirectToAction("Home", "Account")); } }