2024-04-27 22:36:16 +02:00
|
|
|
|
using System.IdentityModel.Tokens.Jwt;
|
|
|
|
|
|
using System.Security.Claims;
|
|
|
|
|
|
using Microsoft.AspNetCore.Http;
|
|
|
|
|
|
using WatchIt.Database;
|
2024-03-28 19:17:46 +01:00
|
|
|
|
|
2024-04-27 22:36:16 +02:00
|
|
|
|
namespace WatchIt.WebAPI.Services.Utility.User;
|
|
|
|
|
|
|
|
|
|
|
|
public class UserService(DatabaseContext database, IHttpContextAccessor accessor) : IUserService
|
2024-03-28 19:17:46 +01:00
|
|
|
|
{
|
2024-04-27 22:36:16 +02:00
|
|
|
|
#region PUBLIC METHODS
|
2024-03-28 19:17:46 +01:00
|
|
|
|
|
2024-04-27 22:36:16 +02:00
|
|
|
|
public ClaimsPrincipal GetRawUser()
|
|
|
|
|
|
{
|
|
|
|
|
|
if (accessor.HttpContext is null)
|
|
|
|
|
|
{
|
|
|
|
|
|
throw new NullReferenceException();
|
|
|
|
|
|
}
|
|
|
|
|
|
return accessor.HttpContext.User;
|
|
|
|
|
|
}
|
2024-03-28 19:17:46 +01:00
|
|
|
|
|
2024-07-30 16:19:51 +02:00
|
|
|
|
public string? GetRawToken()
|
|
|
|
|
|
{
|
|
|
|
|
|
if (accessor.HttpContext is null)
|
|
|
|
|
|
{
|
|
|
|
|
|
throw new NullReferenceException();
|
|
|
|
|
|
}
|
|
|
|
|
|
return accessor.HttpContext.Request.Headers.Authorization;
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2024-04-27 22:36:16 +02:00
|
|
|
|
public UserValidator GetValidator()
|
|
|
|
|
|
{
|
|
|
|
|
|
ClaimsPrincipal rawUser = GetRawUser();
|
|
|
|
|
|
return new UserValidator(database, rawUser);
|
|
|
|
|
|
}
|
2024-03-28 19:17:46 +01:00
|
|
|
|
|
2024-04-27 22:36:16 +02:00
|
|
|
|
public Guid GetJti()
|
|
|
|
|
|
{
|
|
|
|
|
|
ClaimsPrincipal user = GetRawUser();
|
|
|
|
|
|
Claim jtiClaim = user.FindFirst(JwtRegisteredClaimNames.Jti)!;
|
|
|
|
|
|
Guid guid = Guid.Parse(jtiClaim.Value);
|
|
|
|
|
|
return guid;
|
2024-03-28 19:17:46 +01:00
|
|
|
|
}
|
2024-09-20 23:37:55 +02:00
|
|
|
|
|
|
|
|
|
|
public long GetUserId()
|
|
|
|
|
|
{
|
|
|
|
|
|
ClaimsPrincipal user = GetRawUser();
|
|
|
|
|
|
Claim subClaim = user.FindFirst(JwtRegisteredClaimNames.Sub)!;
|
|
|
|
|
|
long id = long.Parse(subClaim.Value);
|
|
|
|
|
|
return id;
|
|
|
|
|
|
}
|
2024-04-27 22:36:16 +02:00
|
|
|
|
|
|
|
|
|
|
#endregion
|
|
|
|
|
|
}
|