- Use consolidated Finbuckle.MultiTenant namespace instead of separate imports - Switch TenantProvider to use untyped IMultiTenantContextAccessor (Finbuckle 9.x pattern) - Register TenantDbConnectionInterceptor and SaveChangesTenantInterceptor as singletons - Add interceptors to DbContext configuration for RLS tenant context support - Update evidence files for Task 7 and Task 8 verification
59 lines
1.8 KiB
C#
59 lines
1.8 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 _multiTenantContextAccessor;
|
|
private readonly IHttpContextAccessor _httpContextAccessor;
|
|
|
|
public TenantProvider(
|
|
IMultiTenantContextAccessor 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;
|
|
}
|
|
}
|