50 lines
1.4 KiB
C#
50 lines
1.4 KiB
C#
using System.Security.Claims;
|
|
using AspNetCore.Authentication.ApiKey;
|
|
using Microsoft.AspNetCore.Authorization;
|
|
using Microsoft.EntityFrameworkCore;
|
|
|
|
namespace NejCommon.Authorization;
|
|
|
|
public partial class PermissionHandler : AuthorizationHandler<PermissionRequirement>
|
|
{
|
|
protected override async Task HandleRequirementAsync(
|
|
AuthorizationHandlerContext context,
|
|
PermissionRequirement requirement)
|
|
{
|
|
if (context.Resource is not HttpContext http)
|
|
return;
|
|
|
|
var companyId = http.GetRouteValue("companyId")?.ToString();
|
|
if (companyId == null)
|
|
{
|
|
context.Succeed(requirement);
|
|
return;
|
|
}
|
|
|
|
var authType = context.User.Identity?.AuthenticationType;
|
|
if (authType == null)
|
|
return;
|
|
|
|
bool allowed;
|
|
|
|
if (authType == ApiKeyDefaults.AuthenticationScheme)
|
|
{
|
|
var id = context.User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
|
|
if (id == null)
|
|
return;
|
|
|
|
allowed = await CheckApiKeyPermission(id, companyId, requirement.Permission);
|
|
}
|
|
else
|
|
{
|
|
var sub = context.User.FindFirst("sub")?.Value;
|
|
if (sub == null)
|
|
return;
|
|
|
|
allowed = await CheckUserPermission(sub, companyId, requirement.Permission);
|
|
}
|
|
|
|
if (allowed)
|
|
context.Succeed(requirement);
|
|
}
|
|
} |