2026-03-03 14:32:21 +01:00
|
|
|
using System.Text.Json;
|
|
|
|
|
|
|
|
|
|
namespace WorkClub.Api.Middleware;
|
|
|
|
|
|
|
|
|
|
public class TenantValidationMiddleware
|
|
|
|
|
{
|
|
|
|
|
private readonly RequestDelegate _next;
|
2026-03-05 19:22:21 +01:00
|
|
|
private readonly ILogger<TenantValidationMiddleware> _logger;
|
2026-03-03 14:32:21 +01:00
|
|
|
|
2026-03-05 19:22:21 +01:00
|
|
|
public TenantValidationMiddleware(RequestDelegate next, ILogger<TenantValidationMiddleware> logger)
|
2026-03-03 14:32:21 +01:00
|
|
|
{
|
|
|
|
|
_next = next;
|
2026-03-05 19:22:21 +01:00
|
|
|
_logger = logger;
|
2026-03-03 14:32:21 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public async Task InvokeAsync(HttpContext context)
|
|
|
|
|
{
|
2026-03-05 19:22:21 +01:00
|
|
|
_logger.LogInformation("TenantValidationMiddleware: Processing request for {Path}", context.Request.Path);
|
2026-03-03 14:32:21 +01:00
|
|
|
if (!context.User.Identity?.IsAuthenticated ?? true)
|
|
|
|
|
{
|
|
|
|
|
await _next(context);
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
|
2026-03-20 10:42:31 +01:00
|
|
|
// Exempt bootstrap, admin, debug, and Keycloak OIDC endpoints from tenant validation
|
2026-03-20 09:42:16 +01:00
|
|
|
if (context.Request.Path.StartsWithSegments("/api/clubs/me") ||
|
|
|
|
|
context.Request.Path.StartsWithSegments("/api/admin") ||
|
2026-03-20 10:42:31 +01:00
|
|
|
context.Request.Path.StartsWithSegments("/api/debug") ||
|
|
|
|
|
context.Request.Path.StartsWithSegments("/realms"))
|
2026-03-20 09:42:16 +01:00
|
|
|
{
|
|
|
|
|
_logger.LogInformation("TenantValidationMiddleware: Exempting {Path} from tenant validation", context.Request.Path);
|
|
|
|
|
await _next(context);
|
|
|
|
|
return;
|
|
|
|
|
}
|
2026-03-05 21:32:34 +01:00
|
|
|
|
2026-03-05 11:07:19 +01:00
|
|
|
if (!context.Request.Headers.TryGetValue("X-Tenant-Id", out var tenantIdHeader) ||
|
2026-03-03 14:32:21 +01:00
|
|
|
string.IsNullOrWhiteSpace(tenantIdHeader))
|
|
|
|
|
{
|
|
|
|
|
context.Response.StatusCode = StatusCodes.Status400BadRequest;
|
|
|
|
|
await context.Response.WriteAsJsonAsync(new { error = "X-Tenant-Id header is required" });
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
var requestedTenantId = tenantIdHeader.ToString();
|
|
|
|
|
var clubsClaim = context.User.FindFirst("clubs")?.Value;
|
|
|
|
|
|
|
|
|
|
if (string.IsNullOrEmpty(clubsClaim))
|
|
|
|
|
{
|
2026-03-19 22:13:40 +01:00
|
|
|
// NEW: Skip check if user is a global admin
|
|
|
|
|
var realmAccess = context.User.FindFirst("realm_access")?.Value;
|
|
|
|
|
if (!string.IsNullOrEmpty(realmAccess) && IsAdminUser(realmAccess))
|
|
|
|
|
{
|
|
|
|
|
await _next(context);
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
static bool IsAdminUser(string realmAccess)
|
|
|
|
|
{
|
|
|
|
|
try
|
|
|
|
|
{
|
|
|
|
|
using var doc = System.Text.Json.JsonDocument.Parse(realmAccess);
|
|
|
|
|
if (doc.RootElement.TryGetProperty("roles", out var rolesElement) &&
|
|
|
|
|
rolesElement.ValueKind == System.Text.Json.JsonValueKind.Array)
|
|
|
|
|
{
|
|
|
|
|
foreach (var role in rolesElement.EnumerateArray())
|
|
|
|
|
{
|
|
|
|
|
if (role.GetString()?.Equals("admin", StringComparison.OrdinalIgnoreCase) == true)
|
|
|
|
|
return true;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
catch
|
|
|
|
|
{
|
|
|
|
|
// If JSON parsing fails, fallback to string contains check
|
|
|
|
|
return realmAccess.Contains("admin", StringComparison.OrdinalIgnoreCase);
|
|
|
|
|
}
|
|
|
|
|
return false;
|
|
|
|
|
}
|
2026-03-19 21:36:06 +01:00
|
|
|
|
2026-03-03 14:32:21 +01:00
|
|
|
context.Response.StatusCode = StatusCodes.Status403Forbidden;
|
|
|
|
|
await context.Response.WriteAsJsonAsync(new { error = "User does not have clubs claim" });
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
|
2026-03-05 19:22:21 +01:00
|
|
|
// Parse comma-separated club UUIDs
|
|
|
|
|
var clubIds = clubsClaim.Split(',', StringSplitOptions.RemoveEmptyEntries)
|
|
|
|
|
.Select(id => id.Trim())
|
|
|
|
|
.ToArray();
|
2026-03-03 14:32:21 +01:00
|
|
|
|
2026-03-05 19:22:21 +01:00
|
|
|
if (clubIds.Length == 0 || !clubIds.Contains(requestedTenantId))
|
2026-03-03 14:32:21 +01:00
|
|
|
{
|
|
|
|
|
context.Response.StatusCode = StatusCodes.Status403Forbidden;
|
|
|
|
|
await context.Response.WriteAsJsonAsync(new { error = $"User is not a member of tenant {requestedTenantId}" });
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
|
2026-03-05 19:22:21 +01:00
|
|
|
// Store validated tenant ID in HttpContext.Items for downstream middleware/services
|
|
|
|
|
context.Items["TenantId"] = requestedTenantId;
|
|
|
|
|
_logger.LogInformation("TenantValidationMiddleware: Set TenantId={TenantId} in HttpContext.Items", requestedTenantId);
|
|
|
|
|
|
2026-03-03 14:32:21 +01:00
|
|
|
await _next(context);
|
|
|
|
|
}
|
|
|
|
|
}
|