2024-12-09 21:11:46 +01:00
|
|
|
// Copyright (C) 2023-present sam/u1f320 (vulpine.solutions)
|
|
|
|
//
|
|
|
|
// 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/>.
|
2024-08-22 15:13:46 +02:00
|
|
|
using Foxnouns.Backend.Database.Models;
|
2024-05-28 15:29:18 +02:00
|
|
|
using Foxnouns.Backend.Utils;
|
|
|
|
|
|
|
|
namespace Foxnouns.Backend.Middleware;
|
|
|
|
|
|
|
|
public class AuthorizationMiddleware : IMiddleware
|
|
|
|
{
|
|
|
|
public async Task InvokeAsync(HttpContext ctx, RequestDelegate next)
|
|
|
|
{
|
2024-12-08 15:07:25 +01:00
|
|
|
Endpoint? endpoint = ctx.GetEndpoint();
|
2024-12-17 17:52:32 +01:00
|
|
|
AuthorizeAttribute? attribute = endpoint?.Metadata.GetMetadata<AuthorizeAttribute>();
|
2024-05-28 15:29:18 +02:00
|
|
|
|
2024-12-17 17:52:32 +01:00
|
|
|
if (attribute == null || attribute.Scopes.Length == 0)
|
2024-05-28 15:29:18 +02:00
|
|
|
{
|
|
|
|
await next(ctx);
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2024-12-08 15:07:25 +01:00
|
|
|
Token? token = ctx.GetToken();
|
2024-12-17 17:52:32 +01:00
|
|
|
|
2024-05-28 15:29:18 +02:00
|
|
|
if (token == null)
|
2024-12-08 15:07:25 +01:00
|
|
|
{
|
2024-10-02 00:28:07 +02:00
|
|
|
throw new ApiError.Unauthorized(
|
|
|
|
"This endpoint requires an authenticated user.",
|
|
|
|
ErrorCode.AuthenticationRequired
|
|
|
|
);
|
2024-12-08 15:07:25 +01:00
|
|
|
}
|
|
|
|
|
2024-12-17 17:52:32 +01:00
|
|
|
if (attribute.Scopes.Except(token.Scopes.ExpandScopes()).Any())
|
2024-12-08 15:07:25 +01:00
|
|
|
{
|
2024-10-02 00:28:07 +02:00
|
|
|
throw new ApiError.Forbidden(
|
|
|
|
"This endpoint requires ungranted scopes.",
|
2024-12-17 17:52:32 +01:00
|
|
|
attribute.Scopes.Except(token.Scopes.ExpandScopes()),
|
2024-10-02 00:28:07 +02:00
|
|
|
ErrorCode.MissingScopes
|
|
|
|
);
|
2024-12-08 15:07:25 +01:00
|
|
|
}
|
|
|
|
|
2024-05-28 15:29:18 +02:00
|
|
|
await next(ctx);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
|
|
|
|
public class AuthorizeAttribute(params string[] scopes) : Attribute
|
|
|
|
{
|
2024-12-11 16:54:06 +01:00
|
|
|
public readonly string[] Scopes = scopes.Except([":admin", ":moderator", ":deleted"]).ToArray();
|
|
|
|
}
|