public async Task LoginUserSuccessfully(string email, string password, string username) { var user = new LoginUserInputModel { Email = email, Password = password, }; var json = new StringContent( JsonConvert.SerializeObject(user), Encoding.UTF8, "application/json"); var response = await client.PostAsync(LoginEndpoint, json); var content = JsonConvert.DeserializeObject <LoginViewModel>(await response.Content.ReadAsStringAsync()); response.EnsureSuccessStatusCode(); var decodedToken = new JwtSecurityTokenHandler().ReadJwtToken(content.Token); var claims = decodedToken.Claims; Assert.Equal(username, claims.First(c => c.Type == "unique_name").Value); Assert.Equal(email, claims.First(c => c.Type == "email").Value); Assert.False(Convert.ToBoolean(claims.First(c => c.Type == "isBanned").Value)); Assert.True(Convert.ToBoolean(claims.First(c => c.Type == "isAdmin").Value)); Assert.Equal(Convert.ToInt32(claims.First(c => c.Type == "iat").Value) + OneWeekInSeconds, Convert.ToInt32(claims.First(c => c.Type == "exp").Value)); }
public async Task <IActionResult> Login(LoginUserInputModel input) { if (this.User.Identity.IsAuthenticated) { return(Redirect("/School/Forum")); } if (!this.ModelState.IsValid) { return(View(input)); } var user = this.usersService.GetUserByEmail(input.Email); if (user == null) { this.ModelState.AddModelError("Wrong Email", "Invalid email"); return(View(input)); } var result = await this.signInManager.PasswordSignInAsync(user, input.Password, false, false); if (!result.Succeeded) { this.ModelState.AddModelError("Login failed", "Invalid username or password"); return(View(input)); } return(Redirect("/School/Forum")); }
public async Task <Result <UserOutputModel> > Login(LoginUserInputModel model, bool adminLogin = false) { var existingUser = await this.userManager.FindByNameAsync(model.UserName); if (existingUser == null) { return(Result <UserOutputModel> .Failure(new List <string>() { Messages.IncorrectUserNameOrPassword })); } var signInResult = await this.signInManager.PasswordSignInAsync(model.UserName, model.Password, isPersistent : true, lockoutOnFailure : false); if (!signInResult.Succeeded) { return(Result <UserOutputModel> .Failure(new List <string>() { Messages.IncorrectUserNameOrPassword })); } var userRoles = await this.userManager.GetRolesAsync(existingUser); if (adminLogin && (userRoles == null || !userRoles.Contains(Role.Administrator.ToString()))) { return(Result <UserOutputModel> .Failure(new List <string>() { Messages.IncorrectUserNameOrPassword })); } var token = this.jwtTokenGenerator.GenerateJwtToken(existingUser, userRoles); return(Result <UserOutputModel> .SuccessWith(new UserOutputModel(existingUser, token))); }
public async Task <string> Login(LoginUserInputModel model) { var user = this.UserManager.Users.SingleOrDefault(u => u.Email == model.Email); if (user is null) { throw new Exception("Invalid username or password!"); } if (user.IsActive == false) { throw new UnauthorizedAccessException("You are banned! Contact admin for further information."); } var result = await this.signInManager.PasswordSignInAsync(user, model.Password, false, false); if (!result.Succeeded) { throw new Exception("Invalid username or password!"); } await this.LoginInfo(user.Id); return(GenerateToken(user)); }
public async Task <string> GetIdByUsernameAndPasswordAsync(LoginUserInputModel inputModel) { if (await UserExistsAsync(inputModel.Username, inputModel.Password) == false) { return(null); } return((await this.userManager.FindByNameAsync(inputModel.Username)).Id); }
public string GetUserId(LoginUserInputModel model) { var hashedPassword = ComputeHash(model.Password); var user = this.dbContext.Users .FirstOrDefault(x => x.Username == model.Username && x.Password == hashedPassword); return(user?.Id); }
public async Task <User> GetUserAsync(LoginUserInputModel inputModel) { if (await UserExistsAsync(inputModel.Username, inputModel.Password) == false) { return(null); } return(await this.userManager.FindByNameAsync(inputModel.Username)); }
public async Task UserUnBanSuccessfully(string email, string password, string bannedUserEmail, string bannedUserPassword, string bannedUserUsername) { await this.Register(bannedUserEmail, bannedUserPassword, bannedUserUsername); var token = await this.Login(email, password); this.client.DefaultRequestHeaders.Add("Authorization", "Bearer " + token); var response = await this.client.GetAsync(AdminGetAll); var content = JsonConvert.DeserializeObject <ICollection <UserViewModel> >(await response.Content.ReadAsStringAsync()); var secondUser = content.First(uvm => uvm.Email == bannedUserEmail); response.EnsureSuccessStatusCode(); Assert.Equal(email, content.First().Email); Assert.Equal(bannedUserEmail, secondUser.Email); var json = new StringContent( JsonConvert.SerializeObject("{}"), Encoding.UTF8, "application/json"); response = await this.client.PostAsync(AdminBanEndpoint + secondUser.Id, json); var secondResponseContent = JsonConvert.DeserializeObject <CreateEditReturnMessage <UserViewModel> >(await response.Content.ReadAsStringAsync()); Assert.Equal($"User banned successfully", secondResponseContent.Message); Assert.Equal(StatusCodes.Status200OK, secondResponseContent.Status); var user = new LoginUserInputModel { Email = bannedUserEmail, Password = bannedUserPassword, }; json = new StringContent( JsonConvert.SerializeObject(user), Encoding.UTF8, "application/json"); var responseBannedLogin = await this.client.PostAsync("api/account/login", json); var thirdResponseContent = JsonConvert.DeserializeObject <ReturnMessage>(await responseBannedLogin.Content.ReadAsStringAsync()); Assert.Equal("You are banned! Contact admin for further information.", thirdResponseContent.Message); Assert.Equal(StatusCodes.Status401Unauthorized, thirdResponseContent.Status); response = await this.client.PostAsync(AdminUnBanEndpoint + secondUser.Id, json); var fourthResponse = JsonConvert.DeserializeObject <CreateEditReturnMessage <UserViewModel> >(await response.Content.ReadAsStringAsync()); Assert.Equal($"User unbanned successfully", fourthResponse.Message); Assert.Equal(StatusCodes.Status200OK, fourthResponse.Status); await this.Login(bannedUserEmail, bannedUserPassword); }
public string GetUserId(LoginUserInputModel model) { var hashedPassword = ComputeHash(model.Password); var user = this.db.Users .Where(u => u.Username == model.Username && u.Password == hashedPassword) .FirstOrDefault(); return(user?.Id); }
public async Task <IActionResult> Login([FromBody] LoginUserInputModel model, [FromQuery] bool adminLogin = false) { var result = await this.identity.Login(model, adminLogin); if (!result.Succeeded) { return(this.BadRequest(result.Errors)); } return(this.Ok(result.Data)); }
public HttpResponse Login(LoginUserInputModel model) { var userId = this.usersService.GetUserId(model.Username, model.Password); if (userId != null) { this.SignIn(userId); return(this.Redirect("/Repositories/All")); } return(this.Redirect("/Users/Login")); }
public HttpResponse Login(LoginUserInputModel model) { var userId = this.usersService.GetUserId(model); if (userId == null) { return(this.Error("Invalid username or password.")); } this.SignIn(userId); return(this.Redirect("/")); }
public IActionResult Login(LoginUserInputModel model) { if (ModelState.IsValid) { this.accountService.LoginUser(model); return(this.Redirect("/")); } else { var result = this.View("Error", this.ModelState); result.StatusCode = (int)HttpStatusCode.BadRequest; return(result); } }
public HttpResponse Login(LoginUserInputModel model) { if (this.IsUserSignedIn()) { return(this.Redirect("/")); } var userId = this.usersService.GetUserId(model.Username, model.Password); if (userId == null) { return(this.Error("Invalid username or password.")); } this.SignIn(userId); return(this.Redirect("/Trips/All")); }
public HttpResponse Login(LoginUserInputModel model) { if (this.IsUserSignedIn()) { return(this.Error("Why are you trying to do a forced post request on a non-available page?")); } var user = this.usersService.GetUserId(model); if (user == null) { return(this.Error("Invalid login.")); } this.SignIn(user); return(this.Redirect("/Trips/All")); }
public HttpResponse Login(LoginUserInputModel login) { if (login.Username.Length < 5 || login.Username.Length > 20) { return(this.Redirect("/Users/Login")); } if (login.Password.Length < 6 || login.Password.Length > 20) { return(this.Redirect("/Users/Login")); } var user = this.usersService.GetUser(login.Username, login.Password); this.SignIn(user.Id, user.Username, user.Email); return(this.Redirect("/")); }
public async Task <UserTokensViewModel> LoginAsync(LoginUserInputModel model) { User user = await this.GetUserByEmailAsync(model.Email); SignInResult result = await this.signInManager.CheckPasswordSignInAsync(user, model.Password, false); if (result.Succeeded) { return(new UserTokensViewModel() { AccessToken = await this.GenerateJwtTokenAsync(user), RefreshToken = this.GenerateRefreshToken(user), Role = user.RoleId, }); } throw new ArgumentException("WRONG_CREDENTIALS"); }
public async Task LoginFailWithInvalidPassword(string email, string password) { var user = new LoginUserInputModel { Email = email, Password = password, }; var json = new StringContent( JsonConvert.SerializeObject(user), Encoding.UTF8, "application/json"); var response = await client.PostAsync(LoginEndpoint, json); var content = JsonConvert.DeserializeObject <ReturnMessage>(await response.Content.ReadAsStringAsync()); Assert.Equal(LoginErrorMessage, content.Message); Assert.Equal(StatusCodes.Status400BadRequest, content.Status); }
protected async Task <string> Login(string email, string password) { var user = new LoginUserInputModel { Email = email, Password = password, }; var json = new StringContent( JsonConvert.SerializeObject(user), Encoding.UTF8, "application/json"); var response = await this.client.PostAsync(LoginEndpoint, json); var content = JsonConvert.DeserializeObject <LoginViewModel>(await response.Content.ReadAsStringAsync()); response.EnsureSuccessStatusCode(); return(content.Token); }
public async Task <IActionResult> Login(LoginUserInputModel loginUserInputModel) { if (!ModelState.IsValid) { return(this.View(loginUserInputModel)); } //await this.userService.LogoutUserAsync(); bool success = await this.userService.LoginUserAsync(loginUserInputModel.Username, loginUserInputModel.Password); if (!success) { ModelState.AddModelError(string.Empty, StringConstants.WrongUsernameOrPasswordErrorMessage); return(this.View(loginUserInputModel)); } //If we have reached this point, it is more or less safe to assume that the user exists, hence we next check to which area we are to redirect him - Administration, Customer or Technician if (TempData[StringConstants.TempDataKeyHoldingUserRole].ToString().Equals(StringConstants.AdminUserRole, StringComparison.OrdinalIgnoreCase)) //Checks whether the user is trying to reach the Administration's area { return(this.RedirectToAction( StringConstants.ActionNameIndex, //Action's name StringConstants.HomeControllerName, //Controller's name new { area = StringConstants.AreaNameAdministration })); //Area's name } else if (TempData[StringConstants.TempDataKeyHoldingUserRole].ToString().Equals(StringConstants.CustomerUserRole, StringComparison.OrdinalIgnoreCase)) //Checks whether the user is trying to reach the Customer's area { return(this.RedirectToAction( StringConstants.ActionNameIndex, //Action's name StringConstants.HomeControllerName, //Controller's name new { area = StringConstants.AreaNameCustomer })); // Area's name } else if (TempData[StringConstants.TempDataKeyHoldingUserRole].ToString().Equals(StringConstants.TechnicianUserRole, StringComparison.OrdinalIgnoreCase)) //Checks whether the user is trying to reach the Technician's area { return(this.RedirectToAction( StringConstants.ActionNameIndex, //Action's name StringConstants.HomeControllerName, //Controller's name new { area = StringConstants.AreaNameTechnician })); //Area's name } throw new NotImplementedException(); //TODO: If we are to reach this point, some unauthorised routing is used, hence an error is thrown and the user should be redirected to a generic error page }
public IActionResult Login(LoginUserInputModel model) { var user = this.mapper.Map <EventureUser>(model); if (ModelState.IsValid) { var result = this.accountsService.Login(user, model.Password); if (result == true) { return(this.Redirect("/")); } else { return(this.View(model)); } } else { return(this.View(model)); } }
public async Task <UserTokensViewModel> LoginAsync(LoginUserInputModel model) { User user = await this.GetUserByEmailAsync(model.Email); if (!user.IsActive) { throw new InvalidOperationException(); } SignInResult result = await this.signInManager.CheckPasswordSignInAsync(user, model.Password, false); if (result.Succeeded) { return(new UserTokensViewModel() { AccessToken = await this.GenerateJwtTokenAsync(user), RefreshToken = this.GenerateRefreshToken(user), Roles = user.UserRoles.Select(r => r.Role.Name).ToList(), }); } throw new WrongCredentialsException(); }
public async Task <object> Login([FromBody] LoginUserInputModel model) { try { var token = await this.accountService.Login(model); return(this.Ok(new LoginViewModel { Message = "You have successfully logged in!", Token = token })); } catch (UnauthorizedAccessException e) { return(this.Unauthorized(new ReturnMessage { Message = e.Message })); } catch (Exception e) { return(this.BadRequest(new ReturnMessage { Message = "Invalid e-mail or password!" })); } }
public async Task <ActionResult> Login(LoginUserInputModel inputModel) { await this.HttpContext.SignOutAsync(IdentityConstants.ExternalScheme); try { var registerUserIdentityResult = await this.userService.LoginUser( inputModel.Username, inputModel.Password, inputModel.RememberMe); if (registerUserIdentityResult.Succeeded) { return(this.Ok()); } return(this.Unauthorized()); } catch (Exception ex) { this.loggerService.LogException(ex); return(this.BadRequest()); } }
public async Task <IActionResult> LoginAsync(LoginUserInputModel model) { var result = await this.service.LoginAsync(model); return(this.Ok(result)); }
public LoginUserModel LoginUser(LoginUserInputModel loginUserInputModel) { return(Post <LoginUserModel, LoginUserInputModel>("mod_chat_login_user", loginUserInputModel)); }