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

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

Implement JWT Authentication and Update User Schema

Replaced repository interface with FinXaccesApi.Repositories in UsersControllers.cs. Updated database schema to use PasswordHash instead of Password. Added new migration files reflecting these changes. Updated service registration in Program.cs to include IAuthService and IUserRepository. Refactored UserRepository.cs and IUserRepository.cs with new methods and namespace changes. Commented out UserService.cs. Updated appsettings with new connection strings and JWT settings. Added BCrypt.Net-Next and System.IdentityModel.Tokens.Jwt packages. Introduced AuthController, UserDTO, AuthService, and IAuthService for handling authentication and user management.

  • Property mode set to 100644
File size: 2.5 KB
Line 
1using System.IdentityModel.Tokens.Jwt;
2using System.Security.Claims;
3using System.Text;
4using BCrypt.Net;
5using FinXaccesApi.Controllers;
6using iknow_api.Core.Models;
7using FinXaccesApi.DTOs;
8using FinXaccesApi.Repositories;
9using Microsoft.IdentityModel.Tokens;
10
11namespace FinXaccesApi.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(UserDto userDto)
25 {
26 if (await _userRepository.UserExistsAsync(userDto.Username))
27 return false;
28
29 var user = new User
30 {
31 Email = userDto.Username,
32 PasswordHash = BCrypt.Net.BCrypt.HashPassword(userDto.Password)
33 };
34
35 await _userRepository.AddUserAsync(user);
36 return true;
37 }
38
39 public async Task<string?> LoginAsync(UserDto userDto)
40 {
41 var user = await _userRepository.GetUserByUsernameAsync(userDto.Username);
42 if (user == null || !BCrypt.Net.BCrypt.Verify(userDto.Password, user.PasswordHash))
43 return null;
44
45 return CreateToken(user);
46 }
47
48 public async Task<int> GetUsersCountAsync()
49 {
50 return await _userRepository.GetUsersCountAsync();
51 }
52
53 private string CreateToken(User user)
54 {
55 var claims = new[]
56 {
57 new Claim("id", user.Id.ToString()),
58 new Claim("username", user.Email)
59 };
60
61 var keyString = _configuration["Jwt:Key"];
62 if (string.IsNullOrEmpty(keyString))
63 throw new Exception("JWT Key is missing in configuration!");
64
65 var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(keyString));
66 var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
67
68 var token = new JwtSecurityToken(
69 issuer: "finxacces-api",
70 audience: "finxacces-api",
71 claims: claims,
72 expires: DateTime.Now.AddHours(1),
73 signingCredentials: creds
74 );
75
76 return new JwtSecurityTokenHandler().WriteToken(token);
77 }
78 }
79}
Note: See TracBrowser for help on using the repository browser.