using System.Security.Claims;
using SurveyBackend.Core.Contexts;
using SurveyBackend.Services.Exceptions;
namespace SurveyBackend.Contexts;
///
/// Упрощает получение UserId из JWT-токена
///
public class UserContext : IUserContext
{
private readonly IHttpContextAccessor _httpContextAccessor;
///
/// Добавьте HttpContextAccessor в DI и будет счастье
///
///
public UserContext(IHttpContextAccessor httpContextAccessor)
{
_httpContextAccessor = httpContextAccessor;
}
///
/// Возвращает UserId из токена, при отсуствии кидает Unauthorized
///
///
public int UserId =>
int.Parse(
_httpContextAccessor.HttpContext?.User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.NameIdentifier)
?.Value ?? throw new UnauthorizedException("Where's your token mister"));
}