Files
SocialPub/PrivaPub/Services/JwtEvents.cs
T
thepraandClaude Opus 5.5 c2f439d1e9
Build / Build (push) Successful in 34s
Deploy / privapub.thepra.dev (push) Successful in 57s
Deploy / Release notes on the Releases tab (push) Successful in 3s
Every failure the server answers with names its own error code
Each refusal and failure the client API sends now starts with a code no other failure uses, such as "[ERR0030006] That
code is not valid.", so a screenshot or a report points at the exact place it came from. Nothing another program reads
changes: ActivityPub, the Mastodon API's errors, sign-in tokens and the error kinds decePubClient branches on stay as they
were. The house-rules checks move to 1.1.0.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01W4YtEJrgxG12Pc39Fai8Bd
2026-11-10 08:11:24 +01:00

83 lines
3.1 KiB
C#

using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.Extensions.Localization;
using PrivaPub.ClientModels;
using PrivaPub.Extensions;
using PrivaPub.Infrastructure.Json;
using PrivaPub.Resources;
using PrivaPub.StaticServices;
using System.Security.Claims;
using System.Text;
using System.Text.Json;
namespace PrivaPub.Services
{
public class JwtEvents : JwtBearerEvents
{
static readonly string[] PolicyClaims = { Policies.IsUser, Policies.IsModerator, Policies.IsAdmin };
static readonly JsonSerializerOptions Web = PrivaPubJson.Web;
ILogger<JwtEvents> _logger { get; set; }
const string contentType = "application/json";
//a token outlives a ban, a removal or a demotion, so every request asks the database who the root is now
public override async Task TokenValidated(TokenValidatedContext context)
{
var rootId = context.Principal.GetUserId();
var root = string.IsNullOrEmpty(rootId)
? default
: await context.HttpContext.RequestServices.GetRequiredService<DbEntities>().RootUsers.MatchID(rootId)
.ExecuteFirstAsync(context.HttpContext.RequestAborted);
var refusal = RootJwt.Refusal(root, context.Principal);
if (refusal != default)
{
context.Fail(refusal);
return;
}
if (context.Principal.Identity is not ClaimsIdentity identity)
return;
foreach (var policy in PolicyClaims)
{
foreach (var claim in identity.FindAll(policy).ToList())
identity.TryRemoveClaim(claim);
identity.AddClaim(new Claim(policy, root.Policies.Contains(policy) ? "true" : "false"));
}
}
public override async Task Challenge(JwtBearerChallengeContext context)
{
context.HandleResponse();
context.Response.StatusCode = StatusCodes.Status401Unauthorized;
context.Response.Headers.WWWAuthenticate = context.AuthenticateFailure == default ? "Bearer" : "Bearer error=\"invalid_token\"";
try
{
var localizer = context.HttpContext.RequestServices.GetRequiredService<IStringLocalizer<GenericRes>>();
var webResult = new WebResult().Invalidate(28001.ToCodedError(localizer["Unauthorized."]), StatusCodes.Status401Unauthorized);
context.Response.ContentType = contentType;
await context.Response.BodyWriter.WriteAsync(Encoding.UTF8.GetBytes(JsonSerializer.Serialize(webResult, Web)));
}
catch (Exception ex)
{
_logger = context.HttpContext.RequestServices.GetRequiredService<ILogger<JwtEvents>>();
_logger.LogError(ex, "Error at Challenge()");
}
}
public override async Task Forbidden(ForbiddenContext context)
{
try
{
var localizer = context.HttpContext.RequestServices.GetRequiredService<IStringLocalizer<GenericRes>>();
var webResult = new WebResult().Invalidate(28002.ToCodedError(localizer["Forbidden."]), StatusCodes.Status403Forbidden);
context.Response.ContentType = contentType;
await context.Response.BodyWriter.WriteAsync(Encoding.UTF8.GetBytes(JsonSerializer.Serialize(webResult, Web)));
}
catch (Exception ex)
{
_logger = context.HttpContext.RequestServices.GetRequiredService<ILogger<JwtEvents>>();
_logger.LogError(ex, "Error at Forbidden()");
}
}
}
}