public ActionResult Login(Login model) { if (ModelState.IsValid) { var user = db.Users.Where(u => String.Compare(u.UserName, model.UserName) == 0).FirstOrDefault(); if (user != null) { if (user.IsActive) { // Verify user password var success = SaltedHash.Verify(user.Salt, user.Password, model.Password); if (success) { // Save authentication info ElectricalShopPrincipleModel principle = new ElectricalShopPrincipleModel(); principle.UserId = user.UserId; principle.FullName = user.FullName; principle.Roles = user.Roles.Select(r => r.RoleName).ToArray(); // Add authentication cookie FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(1, model.UserName, DateTime.Now, DateTime.Now.AddDays(7), model.RememberMe, JsonConvert.SerializeObject(principle)); String authTicketEncrypted = FormsAuthentication.Encrypt(authTicket); HttpCookie asCookie = new HttpCookie(FormsAuthentication.FormsCookieName, authTicketEncrypted); Response.Cookies.Add(asCookie); // Write action log Log log = new Log(); log.LogDate = DateTime.Now; log.Action = "Login"; log.Tags = GetRequestedIP() + "," + model.UserName; log.Message = "Đăng nhập hệ thống"; LogWritter.WriteLog(log); return(RedirectToAction("Index", "Admin")); } else { ModelState.AddModelError("", "Sai mật khẩu!"); } } else { ModelState.AddModelError("", "Tài khoản đã bị khóa!"); } } else { ModelState.AddModelError("", "Tài khoản không tồn tại trong hệ thống!"); } } return(View(model)); }
protected void Application_PostAuthenticateRequest() { HttpCookie authCookie = Request.Cookies[FormsAuthentication.FormsCookieName]; if (authCookie != null) { FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value); ElectricalShopPrincipleModel serializeModel = JsonConvert.DeserializeObject <ElectricalShopPrincipleModel>(authTicket.UserData); ElectricalShopPrinciple principle = new ElectricalShopPrinciple(authTicket.Name); principle.UserId = serializeModel.UserId; principle.FullName = serializeModel.FullName; principle.Roles = serializeModel.Roles; HttpContext.Current.User = principle; } }