source: iknow-api/Services/Implementations/AuthService.cs@ cab02ad

Last change on this file since cab02ad was e49c3ed, checked in by stefansaveski <stefansaveski19@…>, 11 months ago

Add JWT authentication and refactor namespaces

Introduced JWT-based authentication and authorization:

  • Configured JWT authentication in Program.cs with token validation.
  • Added [Authorize] attribute to a new getstring endpoint.

Refactored namespaces for consistency:

  • Updated namespaces from iknow_api.Core.* to iknow_api.*.

Enhanced middleware and dependency injection:

  • Registered IAuthService and IUserRepository.
  • Added app.UseAuthentication() and app.UseAuthorization().

Removed unused code and dependencies:

  • Deleted WeatherForecast class.
  • Cleaned up redundant imports.

Updated project dependencies to include JWT authentication library.

  • Property mode set to 100644
File size: 2.8 KB
Line 
1using System.IdentityModel.Tokens.Jwt;
2using System.Security.Claims;
3using System.Text;
4using BCrypt.Net;
5using iknow_api.Controllers;
6using iknow_api.Models;
7using iknow_api.DTOs;
8using iknow_api.Repositories;
9using Microsoft.IdentityModel.Tokens;
10
11namespace iknow_api.Services
12{
13 public class AuthService : IAuthService
14 {
15 private readonly IUserRepository _userRepository;
16 private readonly IConfiguration _configuration;
17
18 public AuthService(IUserRepository userRepository, IConfiguration configuration)
19 {
20 _userRepository = userRepository;
21 _configuration = configuration;
22 }
23
24 public async Task<bool> RegisterAsync(RegisterDto registerDto)
25 {
26 if (await _userRepository.UserExistsAsync(registerDto.Email))
27 return false;
28
29 var user = new User
30 {
31 Name = registerDto.Name,
32 Surname = registerDto.Surname,
33 Index = registerDto.Index,
34 Email = registerDto.Email,
35 PasswordHash = BCrypt.Net.BCrypt.HashPassword(registerDto.Password),
36 Bday = DateTime.SpecifyKind(registerDto.Bday, DateTimeKind.Utc),
37 CreatedAt = DateTime.UtcNow,
38 Role = (Models.UserRole)registerDto.Role
39 };
40
41 await _userRepository.AddUserAsync(user);
42 return true;
43 }
44
45 public async Task<string?> LoginAsync(LoginDto loginDto)
46 {
47 var user = await _userRepository.GetUserByUsernameAsync(loginDto.Email);
48 if (user == null || !BCrypt.Net.BCrypt.Verify(loginDto.Password, user.PasswordHash))
49 return null;
50
51 return CreateToken(user);
52 }
53
54 public async Task<int> GetUsersCountAsync()
55 {
56 return await _userRepository.GetUsersCountAsync();
57 }
58
59 private string CreateToken(User user)
60 {
61 var claims = new[]
62 {
63 new Claim("id", user.Id.ToString()),
64 new Claim("email", user.Email ?? string.Empty),
65 new Claim("role", user.Role.ToString())
66 };
67
68 var keyString = _configuration["Jwt:Key"];
69 if (string.IsNullOrEmpty(keyString))
70 throw new Exception("JWT Key is missing in configuration!");
71
72 var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(keyString));
73 var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
74
75 var token = new JwtSecurityToken(
76 issuer: "iknow-api",
77 audience: "iknow-api",
78 claims: claims,
79 expires: DateTime.UtcNow.AddHours(1),
80 signingCredentials: creds
81 );
82
83 return new JwtSecurityTokenHandler().WriteToken(token);
84 }
85 }
86}
Note: See TracBrowser for help on using the repository browser.