public async Task <IActionResult> Login([FromBody] LoginDTO payload) { var count = await _userService.Count(); if (count <= 0) { return(NotFound()); } User user; try { user = await _userService.FindOneAsync(payload.Email); } catch (ArgumentException) { return(NotFound()); } if (!PasswordsMatch(user.Password, payload.Password)) { return(BadRequest()); } var u = new UserDTO(); Copier.CopyPropertiesTo(user, u); var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config.GetValue <string>("JwtSecret"))); var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256Signature); var header = new JwtHeader(credentials); //Some PayLoad that contain information about the customer var date = DateTime.UtcNow; var descriptor = new SecurityTokenDescriptor() { SigningCredentials = credentials, IssuedAt = date, Expires = date.AddDays(1), Subject = new ClaimsIdentity(new[] { new Claim(ClaimTypes.Name, u.Name), new Claim(ClaimTypes.NameIdentifier, u.Id.ToString()), new Claim(ClaimTypes.UserData, JsonConvert.SerializeObject(u)) }) }; var handler = new JwtSecurityTokenHandler(); // Token to String so you can use it in your client var token = handler.CreateToken(descriptor); var tokenString = handler.WriteToken(token); return(new JsonResult(new Dictionary <string, object>() { { "user", u }, { "token", tokenString } })); }
public async Task <IEnumerable <UserDTO> > GetUsers() { var users = await _service.FindAsync(); return(users.Select(user => { var dto = new UserDTO(); Copier.CopyPropertiesTo(user, dto); return dto; })); }
public async Task <IActionResult> SignUp([FromBody] User user) { user.Password = HashPassword(user.Password); try { await _userService.CreateAsync(user); } catch (DbUpdateException updateEx) { if (updateEx.InnerException.Message.ToLower().Contains("duplicate")) { return(BadRequest(updateEx.InnerException.Message)); } return(StatusCode(StatusCodes.Status500InternalServerError)); } UserDTO usr = new UserDTO(); Copier.CopyPropertiesTo(user, usr); return(CreatedAtAction("SignUp", usr)); }