- AuthMiddleware: X-Api-Key Header-Prüfung für /api/images/* Routen - Neues Config-Feld KreaApiKey in appsettings.json - Bei gültigem API-Key wird Request ohne Cookie-Auth durchgelassen - Normaler User-Auth funktioniert weiterhin als Fallback - ARCHITECTURE.md + ARCHITECTURE_QUICK.md aktualisiert
62 lines
1.9 KiB
C#
62 lines
1.9 KiB
C#
using System.Threading.Tasks;
|
|
using Gott.Services;
|
|
using Microsoft.AspNetCore.Http;
|
|
using Microsoft.Extensions.Configuration;
|
|
|
|
namespace Gott.Middleware;
|
|
|
|
public class AuthMiddleware
|
|
{
|
|
private readonly RequestDelegate _next;
|
|
private readonly string _kreaApiKey;
|
|
|
|
public AuthMiddleware(RequestDelegate next, IConfiguration config)
|
|
{
|
|
_next = next;
|
|
_kreaApiKey = config["KreaApiKey"] ?? "";
|
|
}
|
|
|
|
public async Task InvokeAsync(HttpContext ctx, AuthService auth, DatabaseService db)
|
|
{
|
|
var path = ctx.Request.Path.Value ?? "";
|
|
|
|
// Static files, login and telegram webhook don't require auth
|
|
var isTelegramWebhook = path.StartsWith("/api/telegram/webhook/") && ctx.Request.Method == "POST";
|
|
var isSharedGet = path.StartsWith("/api/shared/") && ctx.Request.Method == "GET";
|
|
var isAutologin = path == "/api/auth/autologin" && ctx.Request.Method == "GET";
|
|
if (!path.StartsWith("/api/") || path == "/api/auth/login" || isTelegramWebhook || isSharedGet || isAutologin)
|
|
{
|
|
await _next(ctx);
|
|
return;
|
|
}
|
|
|
|
// Krea API-Key auth (for automation without user context)
|
|
if (path.StartsWith("/api/images/") && !string.IsNullOrEmpty(_kreaApiKey))
|
|
{
|
|
var apiKey = ctx.Request.Headers["X-Api-Key"].ToString();
|
|
if (!string.IsNullOrEmpty(apiKey) && apiKey == _kreaApiKey)
|
|
{
|
|
await _next(ctx);
|
|
return;
|
|
}
|
|
}
|
|
|
|
var token = ctx.Request.Cookies["gott_token"];
|
|
var userId = auth.ValidateToken(token);
|
|
|
|
if (userId == null)
|
|
{
|
|
ctx.Response.StatusCode = 401;
|
|
await ctx.Response.WriteAsJsonAsync(new { error = "Not authenticated" });
|
|
return;
|
|
}
|
|
|
|
ctx.Items["UserId"] = userId;
|
|
|
|
var user = await db.GetUser(userId);
|
|
ctx.Items["IsAdmin"] = user?.IsAdmin ?? false;
|
|
|
|
await _next(ctx);
|
|
}
|
|
}
|