public async Task <IActionResult> Login(ApplicationUserVM applicationUser) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } var user = await _userManager.FindByNameAsync(applicationUser.Email); if (user == null) { return(Unauthorized("USERNAME_OR_PASSWORD_INVALID")); } var signInResult = await _signInManager.CheckPasswordSignInAsync(user, applicationUser.Password, false); if (signInResult.Succeeded == false) { return(Unauthorized("USERNAME_OR_PASSWORD_INVALID")); } var roles = await _userManager.GetRolesAsync(user); var token = JWTUtils.GenerateJWT(user, roles, _configuration["Jwt:Key"], _configuration["Jwt:Issuer"]); var response = new { Token = token, User = user }; return(Ok(response)); }
public async Task <IActionResult> Login([FromBody] UserLoginDto user) { //throw new System.Exception("Error Test"); var userFromRepo = await repo.Login(user.Username.ToLower(), user.Password); if (userFromRepo == null) { return(Unauthorized()); } var tokenString = JWTUtils.CreateToken(userFromRepo, conf); return(Ok(new { tokenString })); }
public async Task <ActionResult <UserReadDto> > CreateUserAsync([FromBody] UserCreateDto user) { // hash password for securoty reasons user.Password = BCrypt.Net.BCrypt.HashPassword(user.Password); var userModel = _mapper.Map <User>(user); await _repository.CreateUserAsync(userModel); await _repository.SaveChangesAsync(); var tokenString = JWTUtils.SignKey(_configuration, userModel); var loginDto = new LoginDto() { Username = userModel.Username, Id = userModel.Id.ToString(), Token = tokenString }; return(CreatedAtRoute(nameof(GetUserByIdAsync), new { Id = loginDto.Id }, loginDto)); }
public async Task <ActionResult <LoginDto> > Login(UserCreateDto userData) { if (userData != null && userData.Username != null && userData.Password != null) { var user = await _repository.GetUserByUsernameAndPasswordAsync(userData.Username); if (user != null) { // verify password in the database with coming in request body bool verified = BCrypt.Net.BCrypt.Verify(userData.Password, user.Password); if (!verified) { ModelState.AddModelError("message", "Invalid password"); return(BadRequest(ModelState)); } // sign JWT token if ok var tokenString = JWTUtils.SignKey(_configuration, user); var loginDto = new LoginDto() { Username = user.Username, Token = tokenString, Id = user.Id.ToString() }; return(Ok(loginDto)); } else { ModelState.AddModelError("message", "Invalid credentials"); return(BadRequest(ModelState)); } } else { return(BadRequest()); } }