add UserContext summary
This commit is contained in:
parent
cd1f98f575
commit
d8968ce557
1 changed files with 13 additions and 1 deletions
|
|
@ -1,19 +1,31 @@
|
|||
using System.Security.Claims;
|
||||
using SurveyBackend.Core.Contexts;
|
||||
using SurveyBackend.Services.Exceptions;
|
||||
|
||||
namespace SurveyBackend.Contexts;
|
||||
|
||||
/// <summary>
|
||||
/// Упрощает получение UserId из JWT-токена
|
||||
/// </summary>
|
||||
public class UserContext : IUserContext
|
||||
{
|
||||
private readonly IHttpContextAccessor _httpContextAccessor;
|
||||
|
||||
/// <summary>
|
||||
/// Добавьте HttpContextAccessor в DI и будет счастье
|
||||
/// </summary>
|
||||
/// <param name="httpContextAccessor"></param>
|
||||
public UserContext(IHttpContextAccessor httpContextAccessor)
|
||||
{
|
||||
_httpContextAccessor = httpContextAccessor;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Возвращает UserId из токена, при отсуствии кидает Unauthorized
|
||||
/// </summary>
|
||||
/// <exception cref="UnauthorizedAccessException"></exception>
|
||||
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"));
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue