diff --git a/SurveyBackend/SurveyBackend.API/Contexts/UserContext.cs b/SurveyBackend/SurveyBackend.API/Contexts/UserContext.cs index de5e7f1..337e9e1 100644 --- a/SurveyBackend/SurveyBackend.API/Contexts/UserContext.cs +++ b/SurveyBackend/SurveyBackend.API/Contexts/UserContext.cs @@ -24,8 +24,19 @@ public class UserContext : IUserContext /// Возвращает 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")); + //public int UserId => + // int.Parse( + // _httpContextAccessor.HttpContext?.User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.NameIdentifier)?.Value ?? throw new UnauthorizedException("Where's your token mister")); + private string? ClaimValue + => _httpContextAccessor.HttpContext?.User?.FindFirstValue(ClaimTypes.NameIdentifier); + + public int UserId + => int.TryParse(ClaimValue, out var id) + ? id + : throw new UnauthorizedException("User ID claim missing or malformed"); + + public int? NullableUserId + => int.TryParse(ClaimValue, out var id) + ? id + : null; } \ No newline at end of file diff --git a/SurveyBackend/SurveyBackend.Core/Contexts/IUserContext.cs b/SurveyBackend/SurveyBackend.Core/Contexts/IUserContext.cs index 4cd9127..2cc0cfa 100644 --- a/SurveyBackend/SurveyBackend.Core/Contexts/IUserContext.cs +++ b/SurveyBackend/SurveyBackend.Core/Contexts/IUserContext.cs @@ -3,4 +3,5 @@ namespace SurveyBackend.Core.Contexts; public interface IUserContext { int UserId { get; } + int? NullableUserId { get; } } \ No newline at end of file