Build / Build (push) Successful in 36s
Every answer of the Mastodon API and the client API now has its JSON shape generated when the server is built, instead of worked out by reflection while it runs; the bytes sent are unchanged. The small answers that were anonymous objects (the instance documents, notification policies, reports, lists, tags, trends, errors and the empty answers) are named types. A type without generated metadata fails at once in development and on the pasture, and in production is logged and still answered. Three lists that were sent as lazy sequences (moderation reports, the published domain blocks and the languages) are now built first. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01W4YtEJrgxG12Pc39Fai8Bd
83 lines
3.0 KiB
C#
83 lines
3.0 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(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(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()");
|
|
}
|
|
}
|
|
}
|
|
} |