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

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

Add user-related entities and enforce one-to-one mappings

Enhanced the User model with new entities: ContactInfo,
EnrollmentInfo, and HighSchool, establishing one-to-one
relationships. Updated UserDTO with additional fields and
introduced enums for type, quota, and major. Modified
UserRepository and AuthService to handle new entities.

Updated database schema with unique constraints on UserId
for related tables and added EF Core migration
20251027191028_dbRelations. Adjusted JSON serialization
to prevent circular references.

  • Property mode set to 100644
File size: 3.9 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 int userId = user.Id;
43 var contactInfo = new ContactInfo
44 {
45 UserId = userId,
46 city = registerDto.city,
47 address = registerDto.address,
48 municipality = registerDto.municipality,
49 phoneNumber = registerDto.phoneNumber,
50 microsoftEmail = registerDto.microsoftEmail
51 };
52 await _userRepository.AddContactAsync(contactInfo);
53 var enrollmentInfo = new EnrollmentInfo
54 {
55 UserId = userId,
56 enrollmentYear = registerDto.enrollmentYear,
57 quota = (Models.quota)registerDto.quotaType,
58 major = (Models.major)registerDto.majorType
59 };
60 await _userRepository.AddEnrollmentAsync(enrollmentInfo);
61 await _userRepository.AddHighSchoolAsync(new HighSchool
62 {
63 UserId = userId,
64 GPA = registerDto.gpa,
65 tip = (Models.type)registerDto.tip
66 });
67 return true;
68 }
69
70 public async Task<string?> LoginAsync(LoginDto loginDto)
71 {
72 var user = await _userRepository.GetUserByUsernameAsync(loginDto.Email);
73 if (user == null || !BCrypt.Net.BCrypt.Verify(loginDto.Password, user.PasswordHash))
74 return null;
75
76 return CreateToken(user);
77 }
78
79 public async Task<int> GetUsersCountAsync()
80 {
81 return await _userRepository.GetUsersCountAsync();
82 }
83
84 private string CreateToken(User user)
85 {
86 var claims = new[]
87 {
88 new Claim("id", user.Id.ToString()),
89 new Claim("email", user.Email ?? string.Empty),
90 new Claim("role", user.Role.ToString())
91 };
92
93 var keyString = _configuration["Jwt:Key"];
94 if (string.IsNullOrEmpty(keyString))
95 throw new Exception("JWT Key is missing in configuration!");
96
97 var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(keyString));
98 var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
99
100 var token = new JwtSecurityToken(
101 issuer: "iknow-api",
102 audience: "iknow-api",
103 claims: claims,
104 expires: DateTime.UtcNow.AddHours(1),
105 signingCredentials: creds
106 );
107
108 return new JwtSecurityTokenHandler().WriteToken(token);
109 }
110 }
111}
Note: See TracBrowser for help on using the repository browser.