mirror of
https://github.com/whoswhip/Sharpbin.git
synced 2026-12-06 02:48:43 +00:00
44 lines
1.5 KiB
C#
44 lines
1.5 KiB
C#
using System.Security.Claims;
|
|
using Microsoft.AspNetCore.Authorization;
|
|
using SharpbinV3.Server.Extensions;
|
|
|
|
namespace SharpbinV3.Server.Authorization
|
|
{
|
|
public sealed class NotBannedHandler(bool requireAuth = false) : AuthorizationHandler<NotBannedRequirement>
|
|
{
|
|
private readonly bool _requireAuth = requireAuth;
|
|
|
|
protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, NotBannedRequirement requirement)
|
|
{
|
|
var httpContext = context.Resource as HttpContext;
|
|
var isAuthenticated = context.User.Identity?.IsAuthenticated ?? false;
|
|
|
|
if (!isAuthenticated && httpContext != null)
|
|
{
|
|
var apiKey = httpContext.GetApiKeyFromContext();
|
|
if (apiKey != null)
|
|
{
|
|
isAuthenticated = true;
|
|
}
|
|
}
|
|
|
|
if (_requireAuth && !isAuthenticated)
|
|
return Task.CompletedTask;
|
|
|
|
var isBanned = bool.TryParse(context.User.Claims.FirstOrDefault(c => c.Type == "is_banned")?.Value, out var parsedIsBanned)
|
|
&& parsedIsBanned;
|
|
|
|
if (!isBanned && httpContext?.GetJwtUser()?.IsBanned == true)
|
|
isBanned = true;
|
|
|
|
if (httpContext?.GetApiKeyFromContext()?.User?.IsBanned == true)
|
|
isBanned = true;
|
|
|
|
if (!isBanned)
|
|
context.Succeed(requirement);
|
|
|
|
return Task.CompletedTask;
|
|
}
|
|
}
|
|
}
|