source: iknow-api/Services/Implementations/UserService.cs@ 4f5d8fd

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

Add user-related models, services, and JWT validation

Added ContactInfo, EnrollmentInfo, and HighSchool models with relationships to the User entity. Updated AppDbContext and migrations to reflect these changes. Introduced UserService and IUserService for handling user data retrieval via JWT validation. Added UserController with a getUser endpoint to fetch user data based on JWT.

Enhanced IUserRepository and UserRepository with a method to fetch users by ID. Registered UserService in the DI container. Defined enums for EnrollmentInfo and HighSchool. Removed outdated migration files and performed general refactoring and cleanup.

  • Property mode set to 100644
File size: 2.5 KB
Line 
1using iknow_api.Repositories;
2using iknow_api.Services;
3using iknow_api.DTOs;
4using Microsoft.AspNetCore.Http.HttpResults;
5using System.IdentityModel.Tokens.Jwt;
6using System.Security.Claims;
7using System.Text;
8using Microsoft.IdentityModel.Tokens;
9using iknow_api.Models;
10
11namespace iknow_api.Services
12{
13 public class UserService : IUserService
14 {
15
16 private readonly IUserRepository _userRepository;
17 private readonly IConfiguration _configuration;
18 public UserService(IUserRepository userRepository, IConfiguration configuration)
19 {
20 _userRepository = userRepository;
21 _configuration = configuration;
22 }
23 public async Task<User> GetUserData(string JWT)
24 {
25 var userId = ExtractUserIdFromJwt(JWT);
26 if (userId == null)
27 return null;
28
29 // Now you can use userId to fetch user data
30 var user = await _userRepository.GetUserByIdAsync(userId.Value);
31 if(user == null)
32 return null;
33 else
34 return user;
35 }
36
37 private int? ExtractUserIdFromJwt(string token)
38 {
39 try
40 {
41 var tokenHandler = new JwtSecurityTokenHandler();
42 var keyString = _configuration["Jwt:Key"];
43
44 if (string.IsNullOrEmpty(keyString))
45 return null;
46
47 var key = Encoding.UTF8.GetBytes(keyString);
48
49 var validationParameters = new TokenValidationParameters
50 {
51 ValidateIssuerSigningKey = true,
52 IssuerSigningKey = new SymmetricSecurityKey(key),
53 ValidateIssuer = true,
54 ValidIssuer = "iknow-api",
55 ValidateAudience = true,
56 ValidAudience = "iknow-api",
57 ValidateLifetime = true,
58 ClockSkew = TimeSpan.Zero
59 };
60
61 var principal = tokenHandler.ValidateToken(token, validationParameters, out SecurityToken validatedToken);
62
63 // Extract the "id" claim that was set in AuthService.CreateToken
64 var userIdClaim = principal.FindFirst("id");
65
66 if (userIdClaim != null && int.TryParse(userIdClaim.Value, out int userId))
67 {
68 return userId;
69 }
70
71 return null;
72 }
73 catch
74 {
75 return null;
76 }
77 }
78 }
79}
Note: See TracBrowser for help on using the repository browser.