public ActionResult Create(FormCollection collection, LoginModel model) { try { if(ModelState.IsValid && model.PassConfirm.Equals(model.Password)) { using(DataModelContext ctx = new DataModelContext()) { if(model.PermissionCode != "a95e") { ModelState.AddModelError("regResult", "Permission code invalid."); return View("Index", model); } if (ctx.Users.Any(o => o.Username == model.NewUser.Username)) { ModelState.AddModelError("regResult", "Username already exists."); return View("Index", model); } else { byte[] salt = GenerateSalt(16); byte[] hash = GenerateSaltedHash( System.Text.Encoding.UTF8.GetBytes(model.Password), salt); ctx.Users.Add(new User() { EmailAddress = model.NewUser.EmailAddress, RealName = model.NewUser.RealName, Username = model.NewUser.Username, LastLogin = System.DateTime.Now, AccessGroup = model.department, PasswordSalt = salt, PasswordHash = hash, }); ctx.SaveChanges(); FormsAuthentication.SetAuthCookie(model.NewUser.Username, false); return RedirectToAction("Index", "Home"); } } } else { ModelState.AddModelError("regResult", "Password does not match confirmation."); return View("Index", model); } } catch { return RedirectToAction("Index", "Home"); } }
// // GET: /Account/ //public ActionResult Index() //{ // return View(new LoginModel()); //} public ActionResult Index(LoginModel model, string returnUrl) { // If the user hasn't tried to log in yet, let them try. if(model.Username == null) return View(model); using(DataModelContext ctx = new DataModelContext()) { foreach(var u in ctx.Users.Where(u => u.Username == model.Username)) { byte[] salt = u.PasswordSalt; byte[] hash = GenerateSaltedHash( System.Text.Encoding.UTF8.GetBytes(model.Password), salt); if(u.PasswordHash.SequenceEqual(hash)) { FormsAuthentication.SetAuthCookie(model.Username, false); if(returnUrl != null) return Redirect(returnUrl); return RedirectToAction("Index", "Home"); } } ModelState.AddModelError("result", "Incorrect username or password. Try again."); } return View(model); }