feat: admin api

This commit is contained in:
CyberL1 2024-05-28 07:54:25 +02:00
parent 28e842b286
commit 820d48b912
4 changed files with 47 additions and 3 deletions

View File

@ -0,0 +1,11 @@
namespace Minecraft_Realms_Emulator.Attributes
{
[AttributeUsage(AttributeTargets.Class)]
public class RequireAdminKeyAttribute : Attribute
{
public bool HasAdminKey(string authorization)
{
return authorization != null && authorization == Environment.GetEnvironmentVariable("ADMIN_KEY");
}
}
}

View File

@ -1,12 +1,14 @@
using Microsoft.AspNetCore.Mvc;
using Minecraft_Realms_Emulator.Attributes;
using Minecraft_Realms_Emulator.Data;
using Minecraft_Realms_Emulator.Entities;
using Minecraft_Realms_Emulator.Helpers;
namespace Minecraft_Realms_Emulator.Controllers
namespace Minecraft_Realms_Emulator.Controllers.Admin
{
[Route("[controller]")]
[Route("api/admin/[controller]")]
[ApiController]
[RequireAdminKey]
public class ConfigurationController : ControllerBase
{
private readonly DataContext _context;

View File

@ -0,0 +1,30 @@
using Minecraft_Realms_Emulator.Attributes;
namespace Minecraft_Realms_Emulator.Middlewares
{
public class AdminKeyMiddleware(RequestDelegate next)
{
private readonly RequestDelegate _next = next;
public async Task Invoke(HttpContext httpContext)
{
var endpoint = httpContext.GetEndpoint();
var attribute = endpoint?.Metadata.GetMetadata<RequireAdminKeyAttribute>();
if (attribute == null)
{
await _next(httpContext);
return;
}
if (!attribute.HasAdminKey(httpContext.Request.Headers.Authorization))
{
httpContext.Response.StatusCode = 403;
await httpContext.Response.WriteAsync("You don't have access to this resource");
return;
}
await _next(httpContext);
}
}
}

View File

@ -90,12 +90,13 @@ if (mode.Value == nameof(WorkModeEnum.REALMS))
}
}
var rewriteOptions = new RewriteOptions().AddRewrite(@"^(?!configuration)(.*)$", $"modes/{mode.Value}/$1", true);
var rewriteOptions = new RewriteOptions().AddRewrite(@"^(?!api)(.*)$", $"modes/{mode.Value}/$1", true);
app.UseRewriter(rewriteOptions);
app.UseMiddleware<MinecraftCookieMiddleware>();
app.UseMiddleware<CheckRealmOwnerMiddleware>();
app.UseMiddleware<ActiveSubscriptionMiddleware>();
app.UseMiddleware<AdminKeyMiddleware>();
Console.WriteLine($"Running in {mode.Value} mode");
app.Run();