public ActionResult Login(LoginViewModel model, string returnUrl) { try { usuario user = null; { if (ValidateLogin(model)) { return PartialView(model); } if (ValidateAutenticacao(model, out user)) { return PartialView(model); } HttpCookiesSection cookieSection = (HttpCookiesSection)ConfigurationManager.GetSection("system.web/httpCookies"); AuthenticationSection authenticationSection = (AuthenticationSection)ConfigurationManager.GetSection("system.web/authentication"); FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket( 1, user.perfil.nome_perfil, DateTime.Now, DateTime.Now.AddMinutes(authenticationSection.Forms.Timeout.TotalMinutes), false, string.Empty); String encryptedTicket = FormsAuthentication.Encrypt(authTicket); FormsAuthentication.Authenticate(user.perfil.nome_perfil, null); HttpCookie authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket); if (cookieSection.RequireSSL || authenticationSection.Forms.RequireSSL) { authCookie.Secure = true; } HttpContext.Response.Cookies.Add(authCookie); FormsAuthentication.SetAuthCookie(user.perfil.nome_perfil, true); Session["usuario"] = user; return RedirectToAction("Index", "Home"); } } catch (Exception) { return PartialView(model); } }
//Validações de autenticação (Dados preenchidos?) public bool ValidateLogin(LoginViewModel Login) { bool retorno = false; if (string.IsNullOrEmpty(Login.UserCpf)) { ModelState.AddModelError("UserCpf", "Campo obrigatório."); retorno = true; } if (string.IsNullOrEmpty(Login.Password)) { ModelState.AddModelError("Password", "Campo obrigatório."); retorno = true; } return retorno; }
//Validações de autenticação (Dados corretos?) public bool ValidateAutenticacao(LoginViewModel Login, out usuario user) { bool retorno = false; user = UsuarioRepository.GetOne(Login.UserCpf, SecurityHelper.EncryptData(Login.Password)); if (user == null) { ModelState.AddModelError("", "Dados inválidos. Verifique os dados informados e tente novamente."); retorno = true; } return retorno; }