38 lines
1.3 KiB
C#
38 lines
1.3 KiB
C#
using Microsoft.AspNetCore.Http;
|
|
using System.Security.Claims;
|
|
using Vortex.Shared.Kernel;
|
|
using System.IdentityModel.Tokens.Jwt;
|
|
|
|
namespace Vortex.Shared.Infrastructure;
|
|
|
|
public sealed class UserContext : IUserContext
|
|
{
|
|
private readonly IHttpContextAccessor _httpContextAccessor;
|
|
|
|
public UserContext(IHttpContextAccessor httpContextAccessor)
|
|
{
|
|
_httpContextAccessor = httpContextAccessor;
|
|
}
|
|
|
|
public Guid UserId
|
|
{
|
|
get
|
|
{
|
|
var userIdClaim = _httpContextAccessor.HttpContext?.User?.FindFirstValue(ClaimTypes.NameIdentifier)
|
|
?? _httpContextAccessor.HttpContext?.User?.FindFirstValue("sub")
|
|
?? _httpContextAccessor.HttpContext?.User?.FindFirstValue(JwtRegisteredClaimNames.Sub); // Modified
|
|
|
|
if (userIdClaim is null || !Guid.TryParse(userIdClaim, out Guid userId))
|
|
{
|
|
// Вместо исключения возвращаем пустой Guid или обрабатываем иначе,
|
|
// но в защищенных эндпоинтах это не должно случаться
|
|
return Guid.Empty; // Modified
|
|
}
|
|
|
|
return userId;
|
|
}
|
|
}
|
|
|
|
public bool IsAuthenticated => _httpContextAccessor.HttpContext?.User?.Identity?.IsAuthenticated ?? false;
|
|
}
|