public async Task <ActionResult> Login(LoginUserViewModel loginUserViewModel) { if (!ModelState.IsValid) { return(CustomResponse(ModelState)); } var result = await _signInManager.PasswordSignInAsync( loginUserViewModel.Email, loginUserViewModel.Password, isPersistent : false, lockoutOnFailure : true); if (result.Succeeded) { _logger.LogInformation(message: $"User {loginUserViewModel.Email} successfully logged in"); return(CustomResponse(await GenerateJwt(loginUserViewModel.Email))); } if (result.IsLockedOut) { NotificarErro("User is temporarily blocked"); return(CustomResponse(loginUserViewModel)); } NotificarErro("Wrong User or Password"); return(CustomResponse(loginUserViewModel)); }
public ActionResult Login(LoginUserViewModel loginUser) { if (!ModelState.IsValid) { return(View(loginUser)); } bool isValid = false; using (Db db = new Db()) { if (db.Users.Any(x => x.UserName.Equals(loginUser.UserName) && x.Password.Equals(loginUser.Password))) { isValid = true; } if (!isValid) { ModelState.AddModelError("", "Invalid user name or password"); return(View(loginUser)); } else { FormsAuthentication.SetAuthCookie(loginUser.UserName, loginUser.RememberMe); return(Redirect(FormsAuthentication.GetRedirectUrl(loginUser.UserName, loginUser.RememberMe))); } } }
public ActionResult Login(LoginUserViewModel model) { if (!ModelState.IsValid) { return(View(model)); } var query = from u in db.Users where u.Name == model.Username select u; var user = query.FirstOrDefault(); if (user == null || !PasswordHashService.ValidatePassword(model.Password, user.Password)) { FlashMessageHelper.SetMessage(this, FlashMessageType.Warning, "Autoryzacja użytkownika nie przebiegła pomyślnie."); return(View(model)); } UserSessionContext us = new UserSessionContext(HttpContext); us.SetUserId(user.Id); return(RedirectToAction("Index", "Character")); }
public async Task <IActionResult> Login(LoginUserViewModel details) { if (ModelState.IsValid) { AppUser user = await userManager.FindByEmailAsync(details.Email); if (user != null) { await signInManager.SignOutAsync(); Microsoft.AspNetCore.Identity.SignInResult result = await signInManager.PasswordSignInAsync(user, details.Password, false, false); if (result.Succeeded) { UserProfile profile = profileRepository.UserProfiles.FirstOrDefault(p => p.AppUserId == user.Id); flashMessage.Confirmation("Zostałeś zalogowany"); if (profile == null) { return(RedirectToAction(nameof(UserProfileController.Create), nameof(UserProfileController).Replace("Controller", ""))); } else { return(RedirectToAction(nameof(AdvertController.List), nameof(AdvertController).Replace("Controller", ""))); } } } ModelState.AddModelError(nameof(LoginUserViewModel.Email), "Nieprawidłowy adres email lub hasło"); } return(View(details)); }
public async Task <ActionResult> Login(LoginUserViewModel loginUser) { if (!ModelState.IsValid) { return(CustomResponse(ModelState)); } // lockoutOnFailure: se tentar mais de cinco vezes com credenciais erradas, ele vai travar/congelar aquele login e só irá liberar depois // de x tempo (é possível definir esse tempo, por padrão são alguns minutos - isto é um comportamento natural do Identity); var result = await _signInManager.PasswordSignInAsync(loginUser.Email, loginUser.Password, false, true); if (result.Succeeded) { _logger.LogInformation("Usuario " + loginUser.Email + " logado com sucesso"); return(CustomResponse(await GerarJwt(loginUser.Email))); } if (result.IsLockedOut) { NotificarErro("Usuário temporariamente bloqueado por tentativas inválidas"); return(CustomResponse(loginUser)); } NotificarErro("Usuário ou Senha incorretos"); return(CustomResponse(loginUser)); }
public async Task <IActionResult> Login(LoginUserViewModel loginUserViewModel) { var userDetails = _accountBusinessRepository.Login(loginUserViewModel.Email, loginUserViewModel.Password); if (userDetails != null) { var identity = new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationScheme); List <Claim> claims = new List <Claim>(); claims.Add(new Claim(ClaimTypes.Sid, userDetails.Id.ToString())); claims.Add(new Claim(ClaimTypes.Email, userDetails.Email)); claims.Add(new Claim(ClaimTypes.Name, userDetails.FirstName + " " + userDetails.LastName)); identity.AddClaims(claims); var principal = new ClaimsPrincipal(identity); await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal); return(RedirectToAction(RouteConstant.Index_Action, RouteConstant.Home_Controller)); } TempData["Error"] = ResponseMessageConstant.InvalidEmailOrPassword; return(View()); }
public async Task <IActionResult> Login(LoginUserViewModel model) { if (ModelState.IsValid) { Microsoft.AspNetCore.Identity.SignInResult result = await _authentication.SignInAsync(model); if (result.Succeeded) { // проверяем, принадлежит ли URL приложению if (!string.IsNullOrEmpty(model.ReturnUrl) && Url.IsLocalUrl(model.ReturnUrl)) { return(Redirect(model.ReturnUrl)); } else { User user = await _authentication.FindUserByEmailAsync(model.Email); if (await _authentication.IsInRole(user, RoleInitializer.ROLE_ADMIN)) { return(RedirectToAction("Index", "Admin")); } return(RedirectToAction("Index", "Home")); } } else { ModelState.AddModelError("", "Неправильный логин и (или) пароль"); } } return(View(model)); }
public ActionResult Login(LoginUserViewModel loginUserViewModel) { // Check model state if (!ModelState.IsValid) { return(View(loginUserViewModel)); } // Check if the user is valid bool isValid = false; using (Db db = new Db()) { if (db.Users.Any(u => u.Username == loginUserViewModel.Username && u.Password == loginUserViewModel.Password)) { isValid = true; } } if (!isValid) { ModelState.AddModelError("", "Invalid username or password."); loginUserViewModel.Password = ""; return(View(loginUserViewModel)); } FormsAuthentication.SetAuthCookie(loginUserViewModel.Username, loginUserViewModel.RememberMe); return(Redirect(FormsAuthentication.GetRedirectUrl(loginUserViewModel.Username, loginUserViewModel.RememberMe))); }
public async Task <IActionResult> Login(LoginUserViewModel model) { if (ModelState.IsValid) { var result = await _signInManager.PasswordSignInAsync(model.UserName, model.Password, model.RememberMe, false); if (result.Succeeded) { if (!String.IsNullOrEmpty(ViewBag.ReturnUrl) && Url.IsLocalUrl(ViewBag.ReturnUrl)) { return(Redirect(ViewBag.ReturnUrl)); } else { return(RedirectToAction("Dialogs", "Home")); } } else { ModelState.AddModelError("signIn", "Wrong login or password"); } } return(View(model)); }
public async Task <ActionResult> Login(LoginUserViewModel model, string returnUrl = null) { if (!ModelState.IsValid) { return(View(model)); } var passwordHash = HashHelper.GetMd5Hash(model.Password); var user = (await userRepository.GetAsync(x => x.Login == model.Login && x.PasswordHash == passwordHash)).FirstOrDefault(); if (user == null) { await Task.Delay(1000); ModelState.AddModelError("Password", "Wrong login or password"); return(View(model)); } FormsAuthentication.SetAuthCookie(model.Login, true); if (!string.IsNullOrEmpty(returnUrl)) { return(Redirect(returnUrl)); } else { return(RedirectToAction("Index", "Home")); } }
public async Task <IActionResult> Login(LoginUserViewModel viewModel) { if (!ModelState.IsValid) { return(View(viewModel)); } try { var result = await _signInManager.PasswordSignInAsync(viewModel.Username, viewModel.Password, viewModel.RememberMe, false); if (result.Succeeded) { return(RedirectToAction("Index", "Home")); } throw new Exception("User is not active"); } catch (Exception) { ModelState.AddModelError(string.Empty, "Invalid login attempt."); } return(View(viewModel)); }
public IActionResult Register(RegisterUserViewModel model) { if (!ModelState.IsValid) { return(View()); } var registerOutcome = this.usersService.Register( model.Username, model.Password, model.ConfirmPassword, model.Email, model.FirstName, model.LastName, model.Country, model.City, model.Street, model.PostCode); if (!registerOutcome.Result) { return(View()); } var loginViewModel = new LoginUserViewModel { Username = model.Username, Password = model.Password, RememberMe = false }; return(Login(loginViewModel)); }
public async Task <ActionResult> Login(LoginUserViewModel loginUserViewModel) { if (!ModelState.IsValid) { return(CustomResponse(ModelState)); } var result = await _signInManager.PasswordSignInAsync(loginUserViewModel.Email, loginUserViewModel.Password, false, true); if (result.Succeeded) { _logger.LogInformation($"Usuario {loginUserViewModel.Email} loggado com sucesso"); return(CustomResponse(await GerarJsonWebToken(loginUserViewModel.Email))); } if (result.IsLockedOut) { NotificarErro("Usuário temporariamento bloqueado por tentativas inválidas"); return(CustomResponse(loginUserViewModel)); } NotificarErro("Usuário ou Senha incorretos"); return(CustomResponse(loginUserViewModel)); }
public ActionResult Login(LoginUserViewModel loginUser) { if (ModelState.IsValid) { MvcApplication.logger.log("Controller: Home Action: Login Method: Post Info: ModelState is valid", 1); UserDataHandler dataSource = new UserDataHandler(); List <string> loggedUser = dataSource.checkIfUserExist(loginUser);//also check if user is active if (loggedUser.Count != 0) { //Update LastLoginTimestamp for LoggedUser dataSource.updateLastLoginTimestamp(loginUser.Email); Session["userID"] = loggedUser[1]; Session["userName"] = loggedUser[0]; string userRole = dataSource.getUserRole(loggedUser[0]); if (userRole.Equals("Admin")) { return(RedirectToAction("Index", "Admin")); } else if (userRole.Equals("User")) { return(RedirectToAction("Index", "User")); } else { MvcApplication.logger.log("Controller:Home Action: Login Method:Post Error: Unable to get user role. Check Database connection", 3); throw new Exception("CustomizeDeveloperMessage: Unable to get User Role. Check Database connection"); } } } return(View(loginUser)); }
public async Task <ActionResult> Login(LoginUserViewModel loginUser) { if (!ModelState.IsValid) { return(CustomResponse(ModelState)); } // Ultimo parametro true pq vai travar o usuários em tentativas inválidas (5 vezes de tentativas e se errar só libera depois de x tempo) var result = await _signInManager.PasswordSignInAsync(loginUser.Email, loginUser.Password, false, true); if (result.Succeeded) { _logger.LogInformation("Usuário " + loginUser.Email + " logado com sucesso"); return(CustomResponse(await GerarJwt(loginUser.Email))); } if (result.IsLockedOut) { NotificarErro("Usuário temporariamente bloqueado por tentativas inválidas"); return(CustomResponse(loginUser)); } NotificarErro("Usuário ou Senha incorretos"); return(CustomResponse(loginUser)); }
public ActionResult Login(LoginUserViewModel loginUserVM) { //Проверка модели на валидность if (!ModelState.IsValid) { ModelState.AddModelError("emptyField", "Введите данные"); return(View(loginUserVM)); } //Проверка пользователя на валидность bool isValid = false; using (DB db = new DB()) { if (db.Users.Any(x => x.UserName == loginUserVM.UserName && x.Password == loginUserVM.Password))//Проверяем логин и пароль { isValid = true; } if (!isValid) { ModelState.AddModelError("errorLogin", "Неверный логин или пароль"); return(View(loginUserVM)); } else { FormsAuthentication.SetAuthCookie(loginUserVM.UserName, loginUserVM.RememberMe); //Создает файл cookie на ПК, в параметрах принимает логин и статус оставаться в системе return(Redirect(FormsAuthentication.GetRedirectUrl(loginUserVM.UserName, loginUserVM.RememberMe))); //Переадресация происходит через web.config в котором указан адрес куда } } }
public async Task <ActionResult> Login(LoginUserViewModel loginUser) { if (!ModelState.IsValid) { return(CustomResponse(ModelState)); } // 3º parametro se é persistente e o 4º se vc irá bloquear por alguns minutos em caso de 5 falhas seguidas var result = await _signInManager.PasswordSignInAsync(loginUser.Email, loginUser.Password, false, true); if (result.Succeeded) { _logger.LogInformation("Usuário " + loginUser.Email + " logado com sucesso!"); return(CustomResponse(await GerarJwt(loginUser.Email))); //Usando token com claims //Usando Token //return CustomResponse(GerarJWT()); //Sem token //return CustomResponse(loginUser); } //Se o usuário estiver bloqueado if (result.IsLockedOut) { NotificarErro("Usuário temporariamente bloqueado por tentativas inválidas"); return(CustomResponse(loginUser)); } NotificarErro("Usuário ou Senha incorretos"); return(CustomResponse(loginUser)); }
public async Task Login_Deve_Bloquear_Usuario_Apos_Cinco_Tentativas_Incorretas() { // Arrange RegisterUserViewModel registroVM = UserViewModelTestsHelper.ObterInstanciaRegistroUsuario("*****@*****.**", "GMfks123$5555"); await RegistrarUsuarioParaTestes(registroVM); LoginUserViewModel LoginVM = UserViewModelTestsHelper.ObterInstanciaLoginUsuario("*****@*****.**", "Fmfks123&4322"); HttpContent dataRequest = ContentHelper.CreateJsonContent(LoginVM); // Act HttpResponseMessage response = null; for (int i = 0; i <= 4; i++) { response?.Dispose(); response = await base.Client.PostAsync($"{CommonUri}/entrar", dataRequest); } // Assert var result = await ContentHelper.ExtractObject <ResponseViewModel>(response.Content); Assert.False(response.IsSuccessStatusCode); Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); Assert.Single(result.Errors); Assert.Equal("Usuário temporiariamente bloqueado por ter feito várias tentativas de entrada inválidas!", result.Errors.SingleOrDefault()); }
public async Task <IActionResult> Login([Bind("EmailAddress,Password")] LoginUserViewModel m) { // call service to Autheticate User var user = _svc.Authenticate(m.EmailAddress, m.Password); // verify if user found and if not then add a model state e if (user == null) { ModelState.AddModelError("EmailAddress", "Invalid Login Credentials"); ModelState.AddModelError("Password", "Invalid Login Credentials"); return(View(m)); } // sign user in using cookie authentication to store principal await HttpContext.SignInAsync( CookieAuthenticationDefaults.AuthenticationScheme, BuildClaimsPrincipal(user) ); if (user.Role == Role.Admin) { return(RedirectToAction("AdminHome", "Home")); } return(RedirectToAction("ViewReports", "Report")); }
public async Task <ActionResult> Login(LoginUserViewModel loginUser) { if (!ModelState.IsValid) { return(CustomResponse(ModelState)); } var result = await _signInManager.PasswordSignInAsync(loginUser.Email, loginUser.Password, false, true); if (result.Succeeded) { return(CustomResponse(await GerarJwt(loginUser.Email))); } if (result.IsLockedOut) { NotificarErro("Usuário bloqueado"); return(CustomResponse(loginUser)); } NotificarErro("Usuário ou senha incorretos"); return(CustomResponse(loginUser)); }
public async Task <TWorkService.Models.LoginReturnModel> Login([FromBody()] TWorkService.Models.LoginModel loginModel) { LoginUserViewModel details = new LoginUserViewModel { Email = loginModel.UserLogin, Password = loginModel.Password }; bool succeeded = await _userService.LoginAsync(details); if (succeeded) { USER user = await _userRepository.GetUserByEmail(details.Email); return(new TWorkService.Models.LoginReturnModel { UserId = user.Id, UserLogin = user.Email, Password = loginModel.Password, Error = false, ErrorMsg = "" }); } return(new TWorkService.Models.LoginReturnModel { UserId = "", UserLogin = "", Password = "", Error = true, ErrorMsg = "User login or password is incorrect" }); }
public IActionResult Login(LoginUserViewModel loginUserViewModel) { User user = context.Users.FirstOrDefault(u => u.UserName.Equals(loginUserViewModel.UserName)); if (!ModelState.IsValid) { return(View(loginUserViewModel)); } if (user == null) { ViewBag.nameError = "That user doesn't exist"; return(View()); } if (!user.Password.Equals(loginUserViewModel.Password)) { ViewBag.passwordError = "Incorrect password"; return(View()); } session.Add("user", loginUserViewModel.UserName); return(Redirect("/User")); }
//[ValidateAntiForgeryToken] public async Task <ActionResult> Login(LoginUserViewModel details, string returnUrl) { if (ModelState.IsValid) { AppUser user = await UserManager.FindAsync(details.Name, details.Password); if (user == null) { ModelState.AddModelError("", "Некорректное имя или пароль."); } else { ClaimsIdentity ident = await UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie); AuthManager.SignOut(); AuthManager.SignIn(new AuthenticationProperties { IsPersistent = false }, ident); if (String.IsNullOrEmpty(returnUrl)) { return(Redirect("/")); } return(Redirect(returnUrl)); } return(View(details)); } return(View(details)); }
public ActionResult Login(LoginUserViewModel user) { if (ModelState.IsValid) { try { userService.LoginUser(user); } catch (InvalidCredentialsException e) { ModelState.AddModelError("", e.Message); return(View(user)); } catch (Exception) { return(View("Error")); } CreateSession(user.Email); return(RedirectToAction("Index", "Dashboard")); } else { return(View(user)); } }
public ActionResult Login(LoginUserViewModel loginUser) { //Open DB Connection bool isValid = false; using (WSADDbContext context = new WSADDbContext()) { //Hash Password //Query for user based on Username and Password if (context.Users.Any(row => row.Username.Equals(loginUser.Username) && row.Password.Equals(loginUser.Password))) { isValid = true; } } if (!isValid) { ModelState.AddModelError("", "Invalid Username or Password"); return(View()); } else { //If valid, redirect to the user profile FormsAuthentication.SetAuthCookie(loginUser.Username, loginUser.RememberMe); return(Redirect(FormsAuthentication.GetRedirectUrl(loginUser.Username, loginUser.RememberMe))); } }
public ActionResult Login(LoginUserViewModel model) { if (!ModelState.IsValid) { return(View(model)); } bool isValid = db.Users.Any(x => x.Username.Equals(model.Login) && x.Password.Equals(model.Password)); if (!isValid) { ModelState.AddModelError("", "Неверные учетные данные"); return(View(model)); } User user = db.Users.FirstOrDefault(x => x.Username == model.Login); if (!string.IsNullOrEmpty(user.Theme)) { Session["Theme"] = user.Theme; } else { Session["Theme"] = "dark"; } FormsAuthentication.SetAuthCookie(model.Login, model.RememberMe); return(Redirect(FormsAuthentication.GetRedirectUrl(model.Login, model.RememberMe))); }
public async Task <ActionResult> Login(LoginUserViewModel loginUser) { if (!ModelState.IsValid) { return(CustomResponse(ModelState)); } var result = await _signInManager.PasswordSignInAsync(loginUser.Email, loginUser.Password, false, true); if (result.Succeeded) { _logger.Info($"Usuário {loginUser.Email} efetuou o login."); return(CustomResponse(await GerarJwt(loginUser.Email))); } if (result.IsLockedOut) { _logger.Info($"Usuário {loginUser.Email} temporariamente bloqueado."); NotificarErro("Usuário temporariamente bloqueado por tentativas invalidas."); return(CustomResponse(loginUser)); } NotificarErro("Usuário ou senha incorretos."); return(CustomResponse(loginUser)); }
public ActionResult Login(LoginUserViewModel loginUserViewModel) { // instead of doing logic here call a method in the business logoc // layer to create the User, persist in the Db, and return a user to display. // user DI (Dependecy Injection) to get an instance of the business class and access to it's functionality. UserViewModel userViewModel = _businessLogicClass.LoginUser(loginUserViewModel); System.Diagnostics.Debug.WriteLine("Value of logging in UserId = " + loginUserViewModel.UserId); System.Diagnostics.Debug.WriteLine("Value of userViewModel is = " + userViewModel.UserID); Cart newCart = _businessLogicClass.CreateCart(userViewModel.UserID); // Set Session Data // Requires: using Microsoft.AspNetCore.Http; HttpContext.Session.SetString(SessionKeyName, userViewModel.Fname); HttpContext.Session.SetString(SessionKeyLast, userViewModel.Lname); HttpContext.Session.SetString(CustomerId, userViewModel.UserID.ToString()); HttpContext.Session.SetString(CustomerStore, newCart.StoreId.ToString()); HttpContext.Session.SetString(CartId, newCart.CartId.ToString()); //Guid newGuid = Guid(HttpContext.Session.GetString("CustomerId")); //HttpContext.Session.SetString(CartId, ) // Check Session Data in Output System.Diagnostics.Debug.WriteLine("Value of UserID = " + userViewModel.UserID); System.Diagnostics.Debug.WriteLine("Value of Cookie First Name = " + HttpContext.Session.GetString(SessionKeyName)); System.Diagnostics.Debug.WriteLine("Value of Cookie Last tName = " + HttpContext.Session.GetString(SessionKeyLast)); System.Diagnostics.Debug.WriteLine("Value of Cookie CustomerId = " + HttpContext.Session.GetString(CustomerId)); System.Diagnostics.Debug.WriteLine("Value of Cookie CustomerStore = " + HttpContext.Session.GetString(CustomerStore)); System.Diagnostics.Debug.WriteLine("Value of Cookie CartId = " + HttpContext.Session.GetString(CartId)); return(View("DisplayUserDetails", userViewModel)); }
public IHttpResponse Login(IHttpRequest request, LoginUserViewModel model) { if (string.IsNullOrWhiteSpace(model.Username) || string.IsNullOrWhiteSpace(model.Password)) { this.AddError("All credentials are compulsory."); return(this.FileViewResponse(LoginView)); } var exists = this.userService.Exists(model.Username, model.Password); if (exists) { this.LoginUser(request, model.Username); return(new RedirectResponse("/")); } else { this.AddError("The credentials do not match."); return(this.FileViewResponse(LoginView)); } }
public async Task <ActionResult> Logar(LoginUserViewModel loginUser) { if (!ModelState.IsValid) { return(CustomResponse(ModelState)); } var result = await _signInManager.PasswordSignInAsync(loginUser.Email, loginUser.Password, false, true); if (result.Succeeded) { _logger.LogInformation("Usuário" + loginUser.Email + " fez loggin com sucesso!"); return(CustomResponse(await GerarJWT(loginUser.Email))); } if (result.IsLockedOut) { NotificarErro("Usuário temporariamente bloqueado por tentativas inválidas!"); return(CustomResponse(loginUser)); } NotificarErro("Usuário ou senha incorreto!"); return(CustomResponse(loginUser)); }
public async Task<ActionResult> Login(LoginUserViewModel model, string returnUrl) { LoginViewModel loginModel = new LoginViewModel() { Header = this.loginHeader, User = model, ReturnUrl = returnUrl }; if (!this.ModelState.IsValid) { return this.View(loginModel); } var result = await SignInManager .PasswordSignInAsync(model.UserName, model.Password, model.RememberMe, shouldLockout: false); switch (result) { case SignInStatus.Success: return this.RedirectToLocal(returnUrl); case SignInStatus.RequiresVerification: return this.RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe }); case SignInStatus.Failure: default: this.ModelState.AddModelError("", "Invalid login attempt."); return this.View(loginModel); } }