protected void FormsAuthentication_OnAuthenticate(object sender, FormsAuthenticationEventArgs e) { if (FormsAuthentication.CookiesSupported) { if (Request.Cookies[FormsAuthentication.FormsCookieName] != null) { try { string username = FormsAuthentication.Decrypt(Request.Cookies[FormsAuthentication.FormsCookieName].Value).Name; string role = string.Empty; using (ContactBookDb db = new ContactBookDb()) { var account = db.Accounts.FirstOrDefault(x => x.AccountName == username && x.AccountActive == true); role = account.AccountRole; } e.User = new System.Security.Principal.GenericPrincipal( new System.Security.Principal.GenericIdentity(username, "Forms"), role.Split(';')); } catch (Exception) { throw; } } } }
public ActionResult Login(LoginModel model) { try { using (ContactBookDb db = new ContactBookDb()) { var account = db.Accounts.FirstOrDefault(x => x.AccountName == model.UserName && x.AccountPassword == model.UserPassword && x.AccountActive == true); if (account != null) { FormsAuthentication.SetAuthCookie(account.AccountName, true); return(RedirectToAction("Index")); } } } catch (Exception) { return(HttpNotFound()); } return(View()); }
public ActionResult Registration(RegisterModel model) { try { using (ContactBookDb db = new ContactBookDb()) { Accounts account = new Accounts() { AccountName = model.UserName, AccountPassword = model.UserPassword, AccountActive = true, AccountRole = "Normal" }; db.Accounts.Add(account); db.SaveChanges(); } } catch (Exception) { return(HttpNotFound()); } return(View()); }