Add JWT authentication and authorization infrastructure
This commit is contained in:
@@ -0,0 +1,47 @@
|
||||
using Microsoft.AspNetCore.Http;
|
||||
|
||||
namespace Distribution.Infra.Auth
|
||||
{
|
||||
public class CurrentUserService : ICurrentUserService
|
||||
{
|
||||
private readonly IHttpContextAccessor _httpContextAccessor;
|
||||
|
||||
public CurrentUserService(IHttpContextAccessor httpContextAccessor)
|
||||
{
|
||||
_httpContextAccessor = httpContextAccessor;
|
||||
}
|
||||
|
||||
private System.Security.Claims.ClaimsPrincipal? User => _httpContextAccessor.HttpContext?.User;
|
||||
|
||||
public bool IsAuthenticated => User?.Identity?.IsAuthenticated ?? false;
|
||||
|
||||
public Guid? UserId
|
||||
{
|
||||
get
|
||||
{
|
||||
var value = User?.FindFirst("sub")?.Value ?? User?.FindFirst(System.Security.Claims.ClaimTypes.NameIdentifier)?.Value;
|
||||
return Guid.TryParse(value, out var id) ? id : null;
|
||||
}
|
||||
}
|
||||
|
||||
public Guid? RoleId
|
||||
{
|
||||
get
|
||||
{
|
||||
var value = User?.FindFirst("role_id")?.Value;
|
||||
return Guid.TryParse(value, out var id) ? id : null;
|
||||
}
|
||||
}
|
||||
|
||||
public string? Username => User?.FindFirst("username")?.Value;
|
||||
|
||||
public int RoleLevel
|
||||
{
|
||||
get
|
||||
{
|
||||
var value = User?.FindFirst("role_level")?.Value;
|
||||
return int.TryParse(value, out var level) ? level : 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user