35 lines
1.1 KiB
C#
35 lines
1.1 KiB
C#
|
|
using System.Security.Claims;
|
||
|
|
|
||
|
|
namespace Books.Api.Authentication;
|
||
|
|
|
||
|
|
public static class UserExtensions
|
||
|
|
{
|
||
|
|
public static UserContext? GetUserContext(this ClaimsPrincipal? principal)
|
||
|
|
{
|
||
|
|
if (principal?.Identity?.IsAuthenticated != true)
|
||
|
|
return null;
|
||
|
|
|
||
|
|
return new UserContext(
|
||
|
|
Id: principal.FindFirst(ClaimTypes.NameIdentifier)?.Value,
|
||
|
|
Email: principal.FindFirst(ClaimTypes.Email)?.Value
|
||
|
|
?? principal.FindFirst("preferred_username")?.Value,
|
||
|
|
Name: principal.FindFirst(ClaimTypes.GivenName)?.Value
|
||
|
|
?? principal.FindFirst(ClaimTypes.Name)?.Value,
|
||
|
|
CompanyId: principal.FindFirst("company_id")?.Value,
|
||
|
|
IsApiKey: principal.FindFirst(ClaimTypes.AuthenticationMethod)?.Value == "api_key"
|
||
|
|
);
|
||
|
|
}
|
||
|
|
|
||
|
|
public static string? GetClaimValue(this ClaimsPrincipal principal, string claimType)
|
||
|
|
{
|
||
|
|
return principal.FindFirst(claimType)?.Value;
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
public record UserContext(
|
||
|
|
string? Id,
|
||
|
|
string? Email,
|
||
|
|
string? Name,
|
||
|
|
string? CompanyId,
|
||
|
|
bool IsApiKey);
|