From d8968ce557c404f306040dc2c95c047ae92cbc43 Mon Sep 17 00:00:00 2001 From: shept Date: Sun, 27 Apr 2025 15:44:31 +0500 Subject: [PATCH] add UserContext summary --- .../SurveyBackend.API/Contexts/UserContext.cs | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/SurveyBackend/SurveyBackend.API/Contexts/UserContext.cs b/SurveyBackend/SurveyBackend.API/Contexts/UserContext.cs index 298cc59..de5e7f1 100644 --- a/SurveyBackend/SurveyBackend.API/Contexts/UserContext.cs +++ b/SurveyBackend/SurveyBackend.API/Contexts/UserContext.cs @@ -1,19 +1,31 @@ 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 UnauthorizedAccessException()); + ?.Value ?? throw new UnauthorizedException("Where's your token mister")); } \ No newline at end of file