| 1 | using iknow_api.Repositories;
|
|---|
| 2 | using iknow_api.Services;
|
|---|
| 3 | using iknow_api.DTOs;
|
|---|
| 4 | using Microsoft.AspNetCore.Http.HttpResults;
|
|---|
| 5 | using System.IdentityModel.Tokens.Jwt;
|
|---|
| 6 | using System.Security.Claims;
|
|---|
| 7 | using System.Text;
|
|---|
| 8 | using Microsoft.IdentityModel.Tokens;
|
|---|
| 9 | using iknow_api.Models;
|
|---|
| 10 |
|
|---|
| 11 | namespace 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 | }
|
|---|