//private static RestRequest InitRequest(string resource, Method method, object payload) //{ // var request = new RestRequest(resource, method); // request.AddHeader("Content-Type", "application/json"); // request.AddBody(payload); // return request; //} public static AuthenticationModel Login(AccountLoginModel loginModel) { HttpClient httpClient = new HttpClient(); //var request = InitRequest("/login", Method.POST, loginModel); //IRestResponse<AuthenticationModel> response = client.Execute<AuthenticationModel>(request); //ConfigurationManager.AppSettings["accessToken"] = response.Data.Token; //return response.Data; return null; }
//private static RestRequest InitRequest(string resource, Method method, object payload) //{ // var request = new RestRequest(resource, method); // request.AddHeader("Content-Type", "application/json"); // request.AddBody(payload); // return request; //} public static async Task<AuthenticationModel> Login(AccountLoginModel loginModel) { HttpClient httpClient = new HttpClient(); httpClient.BaseAddress = new Uri("http://localhost:1416"); HttpRequestMessage httpRequest = new HttpRequestMessage(HttpMethod.Post,"/login"); httpRequest.Content = new StringContent(JsonConvert.SerializeObject(loginModel)); HttpResponseMessage httpResponse = await httpClient.SendAsync(httpRequest); httpResponse.EnsureSuccessStatusCode(); var data = await httpResponse.Content.ReadAsStringAsync(); var authModel = JsonConvert.DeserializeObject<AuthenticationModel>(data); //var request = InitRequest("/login", Method.POST, loginModel); //IRestResponse<AuthenticationModel> response = client.Execute<AuthenticationModel>(request); //ConfigurationManager.AppSettings["accessToken"] = response.Data.Token; //return response.Data; return null; }
public ActionResult Login(AccountLoginModel viewModel) { if (!ModelState.IsValid) { return(View(viewModel)); } string resultStr = ""; AccountDbModels act = new AccountDbModels(); EsmUser model = new EsmUser(); model = act.loginChk(viewModel); //로그인 체크 if (model == null) //아이디 페스워드 체크 { resultStr = "이메일 또는 비밀번호를 확인해 주시기 바랍니다."; ViewBag.PublicMsg = resultStr; return(View(viewModel)); } if (model.STATUS == 0) //사용 여부 체크 { resultStr = "사용이 정지된 계정입니다."; ViewBag.PublicMsg = resultStr; return(View(viewModel)); } FormsAuthentication.SetAuthCookie(viewModel.Email, false); Session["MANAGE_NO"] = model.SEQNO; Session["MANAGE_GRADE"] = model.GROUP_ID; Session["CURRENT_LOGIN_EMAIL"] = model.EMAIL; //로그인 기록 데이터 세팅 CommLoginLog clh = new CommLoginLog(); clh.EMAIL = viewModel.Email; clh.IPADDR = Request.UserHostAddress; act.loginHis(clh); //로그인 로그 기록 return(RedirectToAction("Index", "Home")); }
public async Task <ActionResult> Login(AccountLoginModel viewModel) { // Ensure we have a valid viewModel to work with if (!this.ModelState.IsValid) { return(this.View(viewModel)); } // Verify if a user exists with the provided identity information // If a user was found var user = await this.UserManager.FindByNameOrEmailAsync(viewModel.Email); if (user != null) { switch (await this.SignInManager.PasswordSignInAsync(user.UserName, viewModel.Password, viewModel.RememberMe, shouldLockout: true)) { case SignInStatus.Success: // Then create an identity for it and sign it in await this.SignInAsync(user, viewModel.RememberMe); // If the user came from a specific page, redirect back to it this.logger.Info($"{user.UserName}:登录成功"); return(this.RedirectToLocal(viewModel.ReturnUrl)); case SignInStatus.LockedOut: //return this.View("Lockout"); this.ModelState.AddModelError("", "账号被锁定,30分钟后再试"); this.logger.Warn($"{user.UserName}:账号被锁定"); return(this.View(viewModel)); case SignInStatus.RequiresVerification: case SignInStatus.Failure: default: this.ModelState.AddModelError("", "用户名或密码不准确."); this.logger.Warn($"{user.UserName}:密码不准确"); return(this.View(viewModel)); } } // No existing user was found that matched the given criteria this.ModelState.AddModelError("", "账号不存在."); this.logger.Warn($"{viewModel.Email}:账号不存在"); // If we got this far, something failed, redisplay form return(this.View(viewModel)); }
public IHttpActionResult Login( [FromBody] AccountLoginModel accountModel) { return(GetHttpResponse(Request, () => { //var cartCount = 0; bool success = _SecurityAdapter.Login(accountModel.LoginEmail, accountModel.Password, accountModel.RememberMe); // ref cartCount, if (success) { return Content(HttpStatusCode.OK, "Authenticated"); } else { return Content(HttpStatusCode.Unauthorized, "Unauthorized login."); } })); }
// // GET: /AccountApi/ public HttpResponseMessage PostLogin(AccountLoginModel model) { if (!model.Email.IsNullOrWhiteSpace() && !model.Password.IsNullOrWhiteSpace()) { var context = new StackOverflowContext(); var account = context.Accounts.FirstOrDefault(x => x.Email == model.Email && x.Password == model.Password); if (account != null) { HttpResponseMessage response = this.Request.CreateResponse(HttpStatusCode.Created, model); return(response); } } throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.BadRequest)); }
public IActionResult Login(AccountLoginModel login) { if (ModelState.IsValid) { User user = _context.Users.FirstOrDefault(u => u.Username == login.Username); if (user != null) { if (Crypto.VerifyHashedPassword(user.Password, login.Password)) { user.Token = Guid.NewGuid().ToString(); _context.SaveChanges(); Response.Cookies.Append("token", user.Token, new Microsoft.AspNetCore.Http.CookieOptions { Expires = DateTime.Now.AddYears(1), HttpOnly = true }); return(RedirectToAction("index", "home")); } } else { ModelState.AddModelError("", "Username or Password is not correct"); } } AccountIndexViewModel data = new AccountIndexViewModel { Login = login }; data.Breadcumb = new BreadcumbViewModel { Title = "Login", Path = new Dictionary <string, string>() }; data.Breadcumb.Path.Add("index", "Home"); data.Breadcumb.Path.Add("Login", null); ViewBag.Partial = data.Breadcumb; return(View("~/Views/Account/Login.cshtml")); }
public ActionResult LogIn(AccountLoginModel model) { var account = _readOnlyRepository.First <Account>( x => x.Email == model.Email && x.Password == model.Password); if (account != null) { List <string> roles = account.Roles.Select(x => x.Name).ToList(); FormsAuthentication.SetAuthCookie(model.Email, model.RememberMe); SetAuthenticationCookie(model.Email, roles); return(RedirectToAction("Index")); //redirect to wanted view. } Error("Email and/or password incorrect"); return(View(model)); }
public HttpResponseMessage Login(HttpRequestMessage request, [FromBody] AccountLoginModel accountModel) { HttpResponseMessage response = null; var success = _securityAdapter.Login(accountModel.LoginEmail, accountModel.Password, accountModel.RememberMe); if (success) { response = request.CreateResponse(HttpStatusCode.OK); } else { response = request.CreateErrorResponse(HttpStatusCode.Unauthorized, "Unauthorized login."); } return(response); }
public async Task <IActionResult> Login(AccountLoginModel model) { if (User.Identity.IsAuthenticated) { return(this.Json(AjaxResult.CreateByMessage("您已经登录,请勿重复登录", false))); } else { if (ModelState.IsValid) { string code = HttpContext.Session.GetVerifyCode(); if (code.ToLower() == model.Code.ToLower()) { try { await personService.Login(model); return(this.Json(AjaxResult.CreateByMessage(""))); } catch (ModelException ex) { return(this.Json(ex.ToAjaxResult())); } catch (Exception ex) { return(this.Json(AjaxResult.CreateByMessage(ex.Message, false))); } } else { await HttpContext.Session.RefreshVerifyCodeAsync(); AjaxResult result = new AjaxResult(); result.Success = false; result.ErrorMessages.Add(nameof(model.Code), "验证码不正确,请重新输入"); return(this.Json(result)); } } else { return(this.Json(ModelState.ToAjaxResult())); } } }
public HttpResponseMessage Login(HttpRequestMessage request, [FromBody] AccountLoginModel accountModel) { return(GetHttpResponse(request, () => { HttpResponseMessage response = null; bool success = _SecurityAdapter.Login(accountModel.LoginEmail, accountModel.Password, false); if (success) { response = request.CreateResponse(HttpStatusCode.OK); } else { response = request.CreateErrorResponse(HttpStatusCode.Unauthorized, "Unauthorized login."); } return response; })); }
public ActionResult Login(AccountLoginModel model, string returnUrl) { // Валидация if ((model == null) || (model.LoginID == null)) { ModelState.AddModelError("", "Въведете потребител"); return(View()); } if (model.Password == null) { ModelState.AddModelError("", "Въведете парола"); return(View()); } AccountModel account = null; using (AccountContext context = new AccountContext()) { account = context.GetAccount(model); } if (account == null) { ModelState.AddModelError("", "Грешна парола или потребител"); return(View()); } HttpSession.UserID = account.ID; var authTicket = new FormsAuthenticationTicket( 1, // version account.LoginID, // user name DateTime.Now, // created DateTime.Now.AddMinutes(20), // expires model.RememberMe, // persistent? account.Roles // can be used to store roles ); string encryptedTicket = FormsAuthentication.Encrypt(authTicket); var authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket); System.Web.HttpContext.Current.Response.Cookies.Add(authCookie); return(RedirectToLocal(returnUrl)); }
public EsmUser loginChk(AccountLoginModel loginModel) { string sqlQuery = " SELECT SEQNO,EMAIL,USERNAME,GROUP_ID,STATUS FROM esm_user WHERE EMAIL = '" + loginModel.Email + "' AND PASSWD = '" + loginModel.Password + "' "; string resultStr = ""; DataTable dt = GetDataTableMySQL(sqlQuery, out resultStr); EsmUser model = new EsmUser(); if (dt != null && dt.Rows.Count != 0) { model.SEQNO = int.Parse(dt.Rows[0]["SEQNO"].ToString().Trim()); model.EMAIL = dt.Rows[0]["EMAIL"].ToString().Trim(); model.USERNAME = dt.Rows[0]["USERNAME"].ToString().Trim(); model.GROUP_ID = int.Parse(dt.Rows[0]["GROUP_ID"].ToString().Trim()); model.STATUS = int.Parse(dt.Rows[0]["STATUS"].ToString().Trim()); } return(model); }
public void Login() { // Arrange Mock <ISecurityAdapter> mockSecurityAdapter = new Mock <ISecurityAdapter>(); string returnUrl = "/testreturnurl"; // Act AccountController controller = new AccountController(mockSecurityAdapter.Object); ActionResult result = controller.Login(returnUrl); // Assert Assert.True(result is ViewResult); ViewResult viewResult = result as ViewResult; Assert.True(viewResult.Model is AccountLoginModel); AccountLoginModel model = viewResult.Model as AccountLoginModel; Assert.True(model.ReturnUrl == returnUrl); }
public HttpResponseMessage Login(HttpRequestMessage request, [FromBody] AccountLoginModel model) { return(base.GetHttpResponse(request, () => { HttpResponseMessage response = null; var sucess = this._securityAdapter.Login(model.LoginEmail, model.Password, model.RememberMe); if (sucess) { response = request.CreateResponse(HttpStatusCode.OK); } else { response = request.CreateResponse(HttpStatusCode.Unauthorized, "Unauthorized login attempt."); } return response; })); }
public async Task <ActionResult> Login(AccountLoginModel viewModel) { // Ensure we have a valid viewModel to work with if (!ModelState.IsValid) { return(View(viewModel)); } // Verify if a user exists with the provided identity information //var user = await _manager.FindByEmailAsync(viewModel.Email); var user = new IdentityUser { Id = "6bc8cee0-a03e-430b-9711-420ab0d6a596", Email = "*****@*****.**", UserName = "******", PasswordHash = "APc6/pVPfTnpG89SRacXjlT+sRz+JQnZROws0WmCA20+axszJnmxbRulHtDXhiYEuQ==", SecurityStamp = "18272ba5-bf6a-48a7-8116-3ac34dbb7f38" }; //user = new UserManager(null); // If a user was found if (user != null) { // Then create an identity for it and sign it in //await SignInAsync(user, viewModel.RememberMe); FormsAuthentication.SignOut(); FormsAuthentication.SetAuthCookie(user.UserName, false); // If the user came from a specific page, redirect back to it return(RedirectToLocal(viewModel.ReturnUrl)); } // No existing user was found that matched the given criteria ModelState.AddModelError("", "Invalid username or password."); // If we got this far, something failed, redisplay form return(View(viewModel)); }
public async Task <ServiceResult <string> > LoginAsync(AccountLoginModel accountLogin) { if (accountLogin is null) { throw new ArgumentNullException(nameof(accountLogin)); } Account account = null; string token = null; var isValidLogin = false; try { await _DatabaseContext.ExecuteAsync(async u => { account = await u.AccountRepository.GetAccountByNameAsync(accountLogin.Username); isValidLogin = account != null && _PasswordHasher.IsSamePassword(accountLogin.Password, account.HashedPassword); if (isValidLogin) { account.LastLogin = DateTime.UtcNow; await u.AccountRepository.UpdateAccountAsync(account); token = _TokenGenerator.Generate(account, accountLogin.ExpireMinutes); } }); if (!isValidLogin) { _Logger.LogDebug("Wrong login or password for {0}", accountLogin.Username); return(new ServiceResult <string>(false, "Wrong login or password.")); } _Logger.LogDebug("{0} successfully logged in", accountLogin.Username); return(new ServiceResult <string>(true, result: token)); } catch (Exception ex) { _Logger.LogError(ex, "Unexpected error during account login for {0}", accountLogin.Username); return(new ServiceResult <string>(false, "Server error. Try again later.")); } }
public JsonResult Login(AccountLoginModel model) { if (!ModelState.IsValid) { } AjaxResult ajaxResult = null; var user = db.Users.SingleOrDefault(p => p.Account == model.Account && p.Password == model.Password); if (user != null) { SaveSession(user); ajaxResult = new AjaxResult() { Success = true, Msg = "用户登录成功", Body = new { Id = user.Id, Account = user.Account, NickName = user.NickName, Avatar = user.Avatar, } }; } else { ajaxResult = new AjaxResult() { Success = false, Msg = "用户名或密码错误", Body = null }; } return(new JsonResult() { ContentEncoding = Encoding.UTF8, Data = CommonJson.camelJson(ajaxResult) }); }
protected void Application_PostAuthenticateRequest(Object sender, EventArgs e) { HttpCookie authCookie = Request.Cookies[FormsAuthentication.FormsCookieName]; System.Web.HttpContext.Current.SetSessionStateBehavior(System.Web.SessionState.SessionStateBehavior.Required); if (authCookie != null) { FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value); JavaScriptSerializer serializer = new JavaScriptSerializer(); AccountLoginModel serializeModel = serializer.Deserialize <AccountLoginModel>(authTicket.UserData); CustomPrincipal newUser = new CustomPrincipal(authTicket.Name); newUser.CompanyCode = serializeModel.CompanyCode; newUser.FirstName = serializeModel.FirstName; newUser.LastName = serializeModel.LastName; HttpContext.Current.User = newUser; } }
public async Task InvalidUser_FailsLogin() { // Arrange AccountLoginModel model = new AccountLoginModel { Email = SOME_EMAIL, Password = SOME_PASSWORD }; UserLoginResponse userRepoResult = new UserLoginResponse { UserIsValid = false }; // Setup mock Mock <IUserRepository> userRepositoryMock = SetupUserRepositoryMock(userRepoResult); // Act AuthenticateService service = new AuthenticateService(userRepositoryMock.Object); AuthenticateResult results = await service.AuthenticateUser(model); // Assert results.Identity.Should().Be(null); }
[HttpPost] //método executado pelo SUBMIT do formulário public IActionResult Login(AccountLoginModel model, [FromServices] UsuarioRepository usuarioRepository) { //verificar se todos os campos foram validados com sucesso if (ModelState.IsValid) { try { //buscar o usuario no banco de dados pelo email e senha var usuario = usuarioRepository.GetByEmailAndSenha(model.Email, model.Senha); //verificando se o usuario foi encontrado if (usuario != null) { //criando a permissão de acesso do usuário var identity = new ClaimsIdentity( new[] { new Claim(ClaimTypes.Name, usuario.Email) }, CookieAuthenticationDefaults.AuthenticationScheme); //gravar a permissão em um cookie encriptado HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(identity)); //redirecionamento return(RedirectToAction("Index", "Agenda")); } else { //lançar uma exceção throw new Exception("Usuário inválido. Acesso Negado."); } } catch (Exception e) { TempData["MensagemErro"] = "Erro: " + e.Message; } } return(View()); }
public async Task <IActionResult> Login(AccountLoginModel Model) { if (!this.ModelState.IsValid) { return(View(Model ?? new AccountLoginModel())); // Fix your errors please } var authResponse = await this.authenticateService.AuthenticateUser(Model); if (!authResponse.Success) { foreach (var error in authResponse.Errors) { this.ModelState.AddModelError(error.Field, error.Message); } return(View(Model)); } if (authResponse.Identity == null) { this.ModelState.AddModelError("", "User authentication failure"); return(View(Model)); } // Only accept redirect url if it's local, prevent reflection attack: string url = "/"; if (!string.IsNullOrEmpty(Model.ReturnUrl) && Url.IsLocalUrl(Model.ReturnUrl)) { url = Model.ReturnUrl; } await this.HttpContext.SignInAsync( CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(authResponse.Identity), new AuthenticationProperties { IsPersistent = Model.RememberMe } ); return(this.LocalRedirect(url)); }
[HttpPost] //recebe o SUBMIT do formulário (envio dos dados) public IActionResult Login(AccountLoginModel model, //campos do formulário [FromServices] UsuarioRepository usuarioRepository) //injeção de dependência { //verificar se todos os campos passaram nas regras de validação if (ModelState.IsValid) { try { //buscando o usuário no banco de dados pelo email e senha var usuario = usuarioRepository.Consultar(model.Email, MD5Encrypt.GenerateHash(model.Senha)); //verificando se o usuário foi encontrado if (usuario != null) { //criando a credencial (permissão) de acesso do usuário.. var identity = new ClaimsIdentity(new[] { new Claim(ClaimTypes.Name, usuario.Email) }, CookieAuthenticationDefaults.AuthenticationScheme); //gravar esta permissão em um arquivo de cookie var principal = new ClaimsPrincipal(identity); HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal); //redirecionando para a página /Home/Index return(RedirectToAction("Index", "Home")); //Home/Index } else { TempData["MensagemErro"] = "Acesso Negado. Usuário não foi encontrado."; } } catch (Exception e) { TempData["MensagemErro"] = e.Message; } } return(View()); }
public async Task <ActionResult> Login(AccountLoginModel viewModel) { // Ensure we have a valid viewModel to work with if (!ModelState.IsValid) { return(View(viewModel)); } // Verify if a user exists with the provided identity information var user = await UserManager.FindByEmailAsync(viewModel.Email); // If a user was found if (user != null) { var result = await SignInManager.PasswordSignInAsync(user.UserName, viewModel.Password, viewModel.RememberMe, shouldLockout : false); switch (result) { case SignInStatus.Success: return(RedirectToLocal(viewModel.ReturnUrl)); case SignInStatus.LockedOut: return(View("Lockout")); case SignInStatus.RequiresVerification: return(RedirectToAction("SendCode", new { ReturnUrl = viewModel.ReturnUrl, RememberMe = viewModel.RememberMe })); case SignInStatus.Failure: default: ModelState.AddModelError("", "Invalid login attempt."); return(View(viewModel)); } } // No existing user was found that matched the given criteria ModelState.AddModelError("", "Invalid username or password."); // If we got this far, something failed, redisplay form return(View(viewModel)); }
public ActionResult Login(AccountLoginModel model) { if (User.Identity.IsAuthenticated) { return(RedirectToAction("Index", "Home")); } if (ModelState.IsValid) { users user = null; //Ищем есть ли такой пользователь в БД и совпадают ли введенные пароли using (database_murom_factory2Entities1 db = new database_murom_factory2Entities1()) { user = db.users.FirstOrDefault(u => u.Login == model.Login && u.Password == model.Password); } //Если данные введены верно //Заносим в куки Логин пользователя if (user != null) { //Файл куки может сохраняться между сеансами браузера FormsAuthentication.SetAuthCookie(model.Login, false); string name = User.Identity.Name; //Если Логин принадлежит суперпользователю if (model.Login == "Admin") { return(RedirectToAction("AdminIndex", "Admin")); } else { return(RedirectToAction("Index", "Home")); } } else { ModelState.AddModelError("", "Такой связки Логин + Пароль не существует"); } } return(View(model)); }
public CrmResponse <AccountUserModel> AccountLogin(AccountLoginModel accountModel) { string _errormsg; CrmResponse <AccountUserModel> _response = new CrmResponse <AccountUserModel>(); var data = _accountData.AccountLoginData(accountModel.UserName, accountModel.Password, out _errormsg); if (!_errormsg.Equals("")) { _response.Message = _errormsg; _response.Success = false; _response.Data = null; } else { _response.Message = ""; _response.Success = true; _response.Data = new AccountUserModel { FullName = data, Email = "", Token = "avb5t-6tyui-re34d" }; } return(_response); }
public AccountLoginModel GetAccount(string login, string password) { AccountLoginModel account = new AccountLoginModel(); using (SqlConnection conn = new SqlConnection(_connectionStringAccount)) { conn.Open(); SqlCommand cmd = new SqlCommand("dbo.GetAccount", conn); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@login", login); cmd.Parameters.AddWithValue("@password", HelperRepository.EncrypteText(password)); SqlDataReader reader = cmd.ExecuteReader(); while (reader.Read()) { account.Login = reader["Login"] != DBNull.Value ? Convert.ToString(reader["Login"]) : string.Empty; account.Token = HelperRepository.EncrypteText(reader["Token"] != DBNull.Value ? Convert.ToString(reader["Token"]) : string.Empty); } } return(account); }
public virtual ActionResult Index(LoginViewModel model, string returnUrl) { ViewBag.ReturnUrl = returnUrl; if (!ModelState.IsValid) { TempData["message"] = ""; TempData["alertType"] = "danger"; return(View(model)); } bool result = new AccountLoginModel().CheckLogin(model.Username, model.Password, model.RememberMe); if (result) { Users user = new AccountLoginModel().GetUserByLogin(model.Username, model.Password, model.RememberMe); LoggedUserInfo loggedUser = new LoggedUserInfo(); loggedUser.Username = user.Username; loggedUser.ID = user.ID; loggedUser.UserRoleEnum = user.UserRoleEnum.Value; loggedUser.PasswordHash = Crypto.SHA256(model.Password); LoggedUserInfo.AddLoggedUserInfo(loggedUser); if (Url.IsLocalUrl(returnUrl)) { return(Redirect(returnUrl)); } return(Redirect("/Admin/Posts")); } else { TempData["message"] = "Invalid login attempt"; TempData["alertType"] = "danger"; ModelState.AddModelError("", "Invalid login attempt."); return(View(model)); } }
public void Login() { Mock <ISecurityAdapter> mockSecurityAdapter = new Mock <ISecurityAdapter>(); mockSecurityAdapter.Setup(obj => obj.Initialize()); string returnUrl = "/testreturnurl"; AccountController controller = new AccountController(mockSecurityAdapter.Object); ActionResult result = controller.Login(returnUrl); Assert.IsTrue(result is ViewResult); ViewResult viewResult = result as ViewResult; Assert.IsTrue(viewResult.Model is AccountLoginModel); AccountLoginModel model = viewResult.Model as AccountLoginModel; Assert.IsTrue(model.ReturnUrl == returnUrl); }
public async Task <ActionResult> Login(AccountLoginModel viewModel) { // Ensure we have a valid viewModel to work with if (!ModelState.IsValid) { return(View("~/views/acesso/login.cshtml", viewModel)); } Usuario usuario = _restClient.GetByEmailSenha(viewModel.Email, viewModel.Password); // Prepare the identity with the provided information if ((usuario == null) || ((usuario.Email == null))) {// No existing user was found that matched the given criteria ModelState.AddModelError("", @"Usuário ou senha inválidos."); return(View("~/views/acesso/login.cshtml", viewModel)); } var user = new UsuarioApp { UserName = usuario.NomeDoUsuario, Email = usuario.Email, Id = usuario.Id.ToString(CultureInfo.InvariantCulture), IdConta = usuario.IdConta, Perfil = usuario.perfil, SPRUsuario = usuario.sprusuario, ChaveConta = usuario.ds_chave ?? string.Empty }; // Verify if a user exists with the provided identity information //var user = await _manager.FindByEmailAsync(viewModel.Email); // Then create an identity for it and sign it in await SignInAsync(user, viewModel.RememberMe); // If the user came from a specific page, redirect back to it return(RedirectToLocal(viewModel.ReturnUrl)); }
protected override async Task <ICommandResult <T> > ExecuteAsync <T>(object model) { if (model != null && model is AccountLoginModel) { AccountLoginModel loginModel = model as AccountLoginModel; var requestParams = new List <KeyValuePair <string, string> > { new KeyValuePair <string, string>("grant_type", "password"), new KeyValuePair <string, string>("username", loginModel.Username), new KeyValuePair <string, string>("password", loginModel.Password), new KeyValuePair <string, string>("remember", loginModel.RememberMe.ToString()), }; var requestParamsFormUrlEncoded = new FormUrlEncodedContent(requestParams); var tokenServiceResponse = await _client.PostAsync(URI, requestParamsFormUrlEncoded); return(await GetResultAsync <T>(tokenServiceResponse)); } else { throw new InvalidOperationException(); } }
public bool userValidation(string username, string password) { using (MPRContext3 mx3 = new MPRContext3()) { //var user = db.Applicants.Where(a => a.UserEmailAddress.Equals(username) && a.password.Equals(password)).SingleOrDefault(); var user = mx3.CorUserSetUpSet.Where(a => a.LoginID.Trim().ToUpper().Equals(username.ToUpper()) && password.Equals("@password")).FirstOrDefault(); if (user != null) { FormsAuthentication.SetAuthCookie(username, false); AccountLoginModel serializeModel = new AccountLoginModel(); //serializeModel.CompanyCode = companyCode; JavaScriptSerializer serializer = new JavaScriptSerializer(); string userData = serializer.Serialize(serializeModel); FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(1, username, DateTime.Now, DateTime.Now.AddHours(10), false, userData); string encTicket = FormsAuthentication.Encrypt(authTicket); HttpCookie faCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket); faCookie.Expires = false ? authTicket.Expiration : DateTime.Now.AddHours(10); System.Web.HttpContext.Current.Response.Cookies.Add(faCookie); System.Web.HttpContext.Current.Session["session_userfullname"] = user.Name; System.Web.HttpContext.Current.Session["session_loggedinUser"] = user.Name; System.Web.HttpContext.Current.Session["session_userstaffid"] = user.StaffID; System.Web.HttpContext.Current.Session["session_photourlpath"] = user.PhotoUrl; System.Web.HttpContext.Current.Session["session_isreportuser"] = user.IsReportUser; return(true); } } return(false); }