Catalogger.NET/Catalogger.Backend/Api/Middleware/AuthenticationMiddleware.cs

86 lines
2.7 KiB
C#
Raw Permalink Normal View History

2024-10-18 22:13:23 +02:00
// 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 <https://www.gnu.org/licenses/>.
using System.Net;
using Catalogger.Backend.Database.Models;
using Catalogger.Backend.Database.Repositories;
2024-10-18 22:13:23 +02:00
using NodaTime;
namespace Catalogger.Backend.Api.Middleware;
public class AuthenticationMiddleware(ApiTokenRepository tokenRepository, IClock clock)
: IMiddleware
2024-10-18 22:13:23 +02:00
{
public async Task InvokeAsync(HttpContext ctx, RequestDelegate next)
{
var endpoint = ctx.GetEndpoint();
var supportAuth = endpoint?.Metadata.GetMetadata<AuthenticateAttribute>() != null;
var requireAuth = endpoint?.Metadata.GetMetadata<AuthorizeAttribute>() != null;
if (!supportAuth)
{
await next(ctx);
return;
}
var token = ctx.Request.Headers.Authorization.ToString();
var apiToken = await tokenRepository.GetAsync(token);
2024-10-18 22:13:23 +02:00
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;