- Add EF Core migrations for initial schema (clubs, members, work_items, shifts, shift_signups) - Implement RLS policies with SET LOCAL for tenant isolation - Add Finbuckle multi-tenant middleware with ClaimStrategy + HeaderStrategy fallback - Create TenantValidationMiddleware to enforce JWT claims match X-Tenant-Id header - Add tenant-aware DB interceptors (SaveChangesTenantInterceptor, TenantDbConnectionInterceptor) - Configure AppDbContext with tenant scoping and RLS support - Add test infrastructure: CustomWebApplicationFactory, TestAuthHandler, DatabaseFixture - Write TDD integration tests for multi-tenant isolation and RLS enforcement - Add health check null safety for connection string Tasks: 7 (PostgreSQL schema + migrations + RLS), 8 (Finbuckle multi-tenancy + validation), 12 (test infrastructure)
59 lines
1.9 KiB
C#
59 lines
1.9 KiB
C#
using System.Security.Claims;
|
|
using System.Text.Json;
|
|
using Finbuckle.MultiTenant;
|
|
using Finbuckle.MultiTenant.Abstractions;
|
|
using Microsoft.AspNetCore.Http;
|
|
using WorkClub.Application.Interfaces;
|
|
|
|
namespace WorkClub.Infrastructure.Services;
|
|
|
|
public class TenantProvider : ITenantProvider
|
|
{
|
|
private readonly IMultiTenantContextAccessor<TenantInfo> _multiTenantContextAccessor;
|
|
private readonly IHttpContextAccessor _httpContextAccessor;
|
|
|
|
public TenantProvider(
|
|
IMultiTenantContextAccessor<TenantInfo> multiTenantContextAccessor,
|
|
IHttpContextAccessor httpContextAccessor)
|
|
{
|
|
_multiTenantContextAccessor = multiTenantContextAccessor;
|
|
_httpContextAccessor = httpContextAccessor;
|
|
}
|
|
|
|
public string GetTenantId()
|
|
{
|
|
var tenantInfo = _multiTenantContextAccessor.MultiTenantContext?.TenantInfo;
|
|
if (tenantInfo == null || string.IsNullOrEmpty(tenantInfo.Identifier))
|
|
{
|
|
throw new InvalidOperationException("Tenant context is not available");
|
|
}
|
|
|
|
return tenantInfo.Identifier;
|
|
}
|
|
|
|
public string GetUserRole()
|
|
{
|
|
var httpContext = _httpContextAccessor.HttpContext;
|
|
if (httpContext?.User == null)
|
|
{
|
|
throw new InvalidOperationException("User context is not available");
|
|
}
|
|
|
|
var tenantId = GetTenantId();
|
|
var clubsClaim = httpContext.User.FindFirst("clubs")?.Value;
|
|
|
|
if (string.IsNullOrEmpty(clubsClaim))
|
|
{
|
|
throw new InvalidOperationException("User does not have clubs claim");
|
|
}
|
|
|
|
var clubsDict = JsonSerializer.Deserialize<Dictionary<string, string>>(clubsClaim);
|
|
if (clubsDict == null || !clubsDict.TryGetValue(tenantId, out var role))
|
|
{
|
|
throw new InvalidOperationException($"User is not a member of tenant {tenantId}");
|
|
}
|
|
|
|
return role;
|
|
}
|
|
}
|