public async Task <IActionResult> PostUser([Required][FromBody] Users body) { try { if (body.Password.Length < 8) { return(new BadRequestObjectResult("Password is too short")); } if (_context.Users.FirstOrDefault(x => x.Email == body.Email) != null) { return(new BadRequestObjectResult("Given email is already used")); } body.Password = SecurePasswordHasher.Hash(body.Password); var user = _context.Users.Add(body).Entity; _context.SaveChanges(); IAuthContainerModel model = JwtFunctions.GetJwtContainerModel(user.Id, user.Email); IAuthService authService = new JwtService(model.SecretKey); var token = authService.GenerateToken(model); return(new OkObjectResult(new { token, expiresIn = model.ExpireMinutes, user = _mapper.Map <DTOUserModel>(user) })); } catch (Exception ex) { return(new BadRequestObjectResult(new { error = ex, body })); } }
public async Task <IActionResult> GetTokenAsync([Required][FromBody] LoginModel body) { try { if (string.IsNullOrEmpty(body.Email) || string.IsNullOrEmpty(body.Password)) { throw new UnauthorizedAccessException(); } var user = _context.Users.FirstOrDefault(x => x.Email == body.Email); if (user == null) { throw new UnauthorizedAccessException(); } if (SecurePasswordHasher.Verify(body.Password, user.Password)) { IAuthContainerModel model = JwtFunctions.GetJwtContainerModel(user.Id, user.Email); IAuthService authService = new JwtService(model.SecretKey); var token = authService.GenerateToken(model); return(new OkObjectResult(new { token, expiresIn = model.ExpireMinutes, user = _mapper.Map <DTOUserModel>(user) })); } return(new UnauthorizedResult()); } catch (UnauthorizedAccessException) { return(new UnauthorizedResult()); } catch (Exception ex) { return(new BadRequestObjectResult(new { error = ex })); } }