[b66b3ac] | 1 | namespace backend.Services;
|
---|
| 2 |
|
---|
| 3 | using backend.Entities;
|
---|
| 4 | using backend.Helpers;
|
---|
| 5 | using backend.Models;
|
---|
| 6 | using Microsoft.Extensions.Options;
|
---|
| 7 | using Microsoft.IdentityModel.Tokens;
|
---|
| 8 | using System.IdentityModel.Tokens.Jwt;
|
---|
| 9 | using System.Security.Claims;
|
---|
| 10 | using System.Text;
|
---|
| 11 |
|
---|
| 12 | public interface IUserService
|
---|
| 13 | {
|
---|
| 14 | AuthenticateResponse Authenticate(AuthenticateRequest model);
|
---|
| 15 | User GetById(int id);
|
---|
| 16 | }
|
---|
| 17 |
|
---|
| 18 | public class UserService : IUserService
|
---|
| 19 | {
|
---|
| 20 | // users hardcoded for simplicity, store in a db with hashed passwords in production applications
|
---|
| 21 | private List<User> _users = new List<User>
|
---|
| 22 | {
|
---|
| 23 | new User { Id = 1, Username = "test", Password = "test" }
|
---|
| 24 | };
|
---|
| 25 |
|
---|
| 26 | private readonly AppSettings _appSettings;
|
---|
| 27 |
|
---|
| 28 | public UserService(IOptions<AppSettings> appSettings)
|
---|
| 29 | {
|
---|
| 30 | _appSettings = appSettings.Value;
|
---|
| 31 | }
|
---|
| 32 |
|
---|
| 33 | public AuthenticateResponse Authenticate(AuthenticateRequest model)
|
---|
| 34 | {
|
---|
| 35 | var user = _users.SingleOrDefault(x => x.Username == model.Username && x.Password == model.Password);
|
---|
| 36 |
|
---|
| 37 | // return null if user not found
|
---|
| 38 | if (user == null) return null;
|
---|
| 39 |
|
---|
| 40 | // authentication successful so generate jwt token
|
---|
| 41 | var token = generateJwtToken(user);
|
---|
| 42 |
|
---|
| 43 | return new AuthenticateResponse(user, token);
|
---|
| 44 | }
|
---|
| 45 |
|
---|
| 46 | public User GetById(int id)
|
---|
| 47 | {
|
---|
| 48 | return _users.FirstOrDefault(x => x.Id == id);
|
---|
| 49 | }
|
---|
| 50 |
|
---|
| 51 | private string generateJwtToken(User user)
|
---|
| 52 | {
|
---|
| 53 | // generate token that is valid for 7 days
|
---|
| 54 | var tokenHandler = new JwtSecurityTokenHandler();
|
---|
| 55 | var key = Encoding.ASCII.GetBytes(_appSettings.Secret);
|
---|
| 56 | var tokenDescriptor = new SecurityTokenDescriptor
|
---|
| 57 | {
|
---|
| 58 | Subject = new ClaimsIdentity(new[] { new Claim("id", user.Id.ToString()) }),
|
---|
| 59 | Expires = DateTime.UtcNow.AddDays(7),
|
---|
| 60 | SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
|
---|
| 61 | };
|
---|
| 62 | var token = tokenHandler.CreateToken(tokenDescriptor);
|
---|
| 63 | return tokenHandler.WriteToken(token);
|
---|
| 64 | }
|
---|
| 65 | } |
---|