public ActionResult Subscribe([Bind(Include = "Email,Password,ConfirmPassword")] UserSubscribeModel userModel) { if (ModelState.IsValid) { // Verify whether email is in use var userWithEmail = db.Users.Where(user => user.Email == userModel.Email).FirstOrDefault(); if (userWithEmail != null) { ViewData["ErrorMessage"] = "There is already a user with that email. Choose another one."; return(View(userModel)); } var newUser = new User { Email = userModel.Email, Password = SHAGenerator.GetSha1(userModel.Password), // Store password hashed, never in plain Role = UserRoles.Contributor // By default, new users are all contributors }; db.Users.Add(newUser); db.SaveChanges(); CurrentUser = newUser; return(RedirectToAction("Index", "Posts")); } return(View(userModel)); }
public ActionResult Edit([Bind(Include = "Id,Email,Password,Profile,Role")] UserModel user) { User userInDatabase = db.Users.Find(user.Id); if (userInDatabase != null) { // If no password has been provided, do not change it. DO this before validating the // model. Else, it will fail. if (string.IsNullOrEmpty(user.Password)) { // In case there were an error, remove it ModelState.Remove("Password"); } else { userInDatabase.Password = SHAGenerator.GetSha1(user.Password); } if (ModelState.IsValid) { // Look for the user's image HttpPostedFileBase file = Request.Files["ImageFile"]; if (file != null && file.ContentLength > 0) { // If there was a previous image, delete it from disk if (!string.IsNullOrEmpty(userInDatabase.ImagePath)) { System.IO.File.Delete(HttpContext.Server.MapPath("~/App_Data/UserProfiles/" + user.ImagePath)); } // Save the new image string randomName = Guid.NewGuid().ToString().Replace("-", string.Empty) + Path.GetExtension(file.FileName); file.SaveAs(HttpContext.Server.MapPath("~/App_Data/UserProfiles/" + randomName)); userInDatabase.ImagePath = randomName; } userInDatabase.Email = user.Email; userInDatabase.Profile = user.Profile; userInDatabase.Role = user.Role; db.Entry(userInDatabase).State = EntityState.Modified; db.SaveChanges(); return(RedirectToAction("Index")); } } return(View(user)); }
public ActionResult Login([Bind(Include = "Email,Password")] UserLoginModel userModel) { if (ModelState.IsValid) { var currentUser = db.Users.Where(user => user.Email == userModel.Email).FirstOrDefault(); if (currentUser != null) { // Verify whether hashed passwords match if (currentUser.Password == SHAGenerator.GetSha1(userModel.Password)) { CurrentUser = currentUser; return(RedirectToAction("Index", "Posts")); } } ViewData["ErrorMessage"] = "User not found with those credentials"; return(View(userModel)); } return(View(userModel)); }