source: resTools_backend/backend/Services/UserService.cs@ cc4db18

Last change on this file since cc4db18 was 7a983b0, checked in by Danilo <danilo.najkov@…>, 3 years ago

move files

  • Property mode set to 100644
File size: 2.5 KB
Line 
1namespace backend.Services;
2
3using backend.Data;
4using backend.DTOs;
5using backend.Entities;
6using backend.Helpers;
7using backend.Models;
8using Microsoft.EntityFrameworkCore;
9using Microsoft.Extensions.Options;
10using Microsoft.IdentityModel.Tokens;
11using System.IdentityModel.Tokens.Jwt;
12using System.Security.Claims;
13
14public interface IUserService
15{
16 Task<AuthenticateResponse> Authenticate(AuthenticateRequest model);
17 Task<AuthenticateResponse> Register(CreateUserRequest req);
18 Task<User> GetById(int id);
19}
20
21public class UserService : IUserService
22{
23 private readonly AppSettings _appSettings;
24 private readonly DataContext _context = null;
25
26 public UserService(IOptions<AppSettings> appSettings, DataContext context)
27 {
28 _appSettings = appSettings.Value;
29 _context = context;
30 }
31
32 public async Task<AuthenticateResponse> Authenticate(AuthenticateRequest model)
33 {
34 User user = await _context.Users.FirstOrDefaultAsync(x => x.Email == model.Email && x.Password == model.Password);
35
36 // return null if user not found
37 if (user == null) return null;
38
39 // authentication successful so generate jwt token
40 var token = generateJwtToken(user);
41
42 return new AuthenticateResponse { Email = user.Email, Id = user.Id, Token = token};
43 }
44
45 public async Task<User> GetById(int id)
46 {
47 return await _context.Users.FindAsync(id);
48 }
49
50 public async Task<AuthenticateResponse> Register(CreateUserRequest req)
51 {
52 User user = new User() { Email = req.Email, Password = req.Password };
53 await _context.Users.AddAsync(user);
54 await _context.SaveChangesAsync();
55 var token = generateJwtToken(user);
56 return new AuthenticateResponse { Email = user.Email, Id = user.Id, Token = token };
57 }
58
59 private string generateJwtToken(User user)
60 {
61 // generate token that is valid for 7 days
62 var tokenHandler = new JwtSecurityTokenHandler();
63 var key = System.Text.Encoding.ASCII.GetBytes(_appSettings.Secret);
64 var tokenDescriptor = new SecurityTokenDescriptor
65 {
66 Subject = new ClaimsIdentity(new[] { new Claim("id", user.Id.ToString()) }),
67 Expires = DateTime.UtcNow.AddDays(7),
68 SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
69 };
70 var token = tokenHandler.CreateToken(tokenDescriptor);
71 return tokenHandler.WriteToken(token);
72 }
73}
Note: See TracBrowser for help on using the repository browser.