fix(backend): update middleware ordering and interceptors for RLS
Update TenantValidationMiddleware, Program.cs startup sequence, SaveChangesTenantInterceptor, and TenantProvider to ensure proper middleware ordering and tenant context initialization before database access. Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
This commit is contained in:
@@ -5,14 +5,17 @@ namespace WorkClub.Api.Middleware;
|
||||
public class TenantValidationMiddleware
|
||||
{
|
||||
private readonly RequestDelegate _next;
|
||||
private readonly ILogger<TenantValidationMiddleware> _logger;
|
||||
|
||||
public TenantValidationMiddleware(RequestDelegate next)
|
||||
public TenantValidationMiddleware(RequestDelegate next, ILogger<TenantValidationMiddleware> logger)
|
||||
{
|
||||
_next = next;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
public async Task InvokeAsync(HttpContext context)
|
||||
{
|
||||
_logger.LogInformation("TenantValidationMiddleware: Processing request for {Path}", context.Request.Path);
|
||||
if (!context.User.Identity?.IsAuthenticated ?? true)
|
||||
{
|
||||
await _next(context);
|
||||
@@ -37,25 +40,22 @@ public class TenantValidationMiddleware
|
||||
return;
|
||||
}
|
||||
|
||||
Dictionary<string, string>? clubsDict;
|
||||
try
|
||||
{
|
||||
clubsDict = JsonSerializer.Deserialize<Dictionary<string, string>>(clubsClaim);
|
||||
}
|
||||
catch (JsonException)
|
||||
{
|
||||
context.Response.StatusCode = StatusCodes.Status403Forbidden;
|
||||
await context.Response.WriteAsJsonAsync(new { error = "Invalid clubs claim format" });
|
||||
return;
|
||||
}
|
||||
// Parse comma-separated club UUIDs
|
||||
var clubIds = clubsClaim.Split(',', StringSplitOptions.RemoveEmptyEntries)
|
||||
.Select(id => id.Trim())
|
||||
.ToArray();
|
||||
|
||||
if (clubsDict == null || !clubsDict.ContainsKey(requestedTenantId))
|
||||
if (clubIds.Length == 0 || !clubIds.Contains(requestedTenantId))
|
||||
{
|
||||
context.Response.StatusCode = StatusCodes.Status403Forbidden;
|
||||
await context.Response.WriteAsJsonAsync(new { error = $"User is not a member of tenant {requestedTenantId}" });
|
||||
return;
|
||||
}
|
||||
|
||||
// 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);
|
||||
|
||||
await _next(context);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user