// Copyright (C) 2021-present sam (starshines.gay) // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as published // by the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see . using System.Net; using Catalogger.Backend.Database.Models; using Catalogger.Backend.Database.Repositories; using NodaTime; namespace Catalogger.Backend.Api.Middleware; public class AuthenticationMiddleware(ApiTokenRepository tokenRepository, IClock clock) : IMiddleware { public async Task InvokeAsync(HttpContext ctx, RequestDelegate next) { var endpoint = ctx.GetEndpoint(); var supportAuth = endpoint?.Metadata.GetMetadata() != null; var requireAuth = endpoint?.Metadata.GetMetadata() != null; if (!supportAuth) { await next(ctx); return; } var token = ctx.Request.Headers.Authorization.ToString(); var apiToken = await tokenRepository.GetAsync(token); if (apiToken == null) { if (requireAuth) throw new ApiError( HttpStatusCode.Forbidden, ErrorCode.AuthRequired, "Authentication required" ); await next(ctx); return; } ctx.SetToken(apiToken); await next(ctx); } } public static class HttpContextExtensions { private const string Key = "token"; public static void SetToken(this HttpContext ctx, ApiToken token) => ctx.Items.Add(Key, token); public static ApiToken GetTokenOrThrow(this HttpContext ctx) => ctx.GetToken() ?? throw new ApiError( HttpStatusCode.Forbidden, ErrorCode.AuthRequired, "No token in HttpContext" ); public static ApiToken? GetToken(this HttpContext ctx) { if (ctx.Items.TryGetValue(Key, out var token)) return token as ApiToken; return null; } } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)] public class AuthenticateAttribute : Attribute; [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)] public class AuthorizeAttribute : Attribute;