In progress
This commit is contained in:
@@ -0,0 +1,34 @@
|
||||
using ColaFlow.Modules.Identity.Domain.Aggregates.Tenants;
|
||||
|
||||
namespace ColaFlow.Modules.Identity.Infrastructure.Services;
|
||||
|
||||
/// <summary>
|
||||
/// Tenant context interface - provides current request tenant information
|
||||
/// </summary>
|
||||
public interface ITenantContext
|
||||
{
|
||||
/// <summary>
|
||||
/// Current tenant ID
|
||||
/// </summary>
|
||||
TenantId? TenantId { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Current tenant slug
|
||||
/// </summary>
|
||||
string? TenantSlug { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Whether tenant is set
|
||||
/// </summary>
|
||||
bool IsSet { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Set current tenant
|
||||
/// </summary>
|
||||
void SetTenant(TenantId tenantId, string tenantSlug);
|
||||
|
||||
/// <summary>
|
||||
/// Clear tenant information
|
||||
/// </summary>
|
||||
void Clear();
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
using ColaFlow.Modules.Identity.Domain.Aggregates.Tenants;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
|
||||
namespace ColaFlow.Modules.Identity.Infrastructure.Services;
|
||||
|
||||
/// <summary>
|
||||
/// Tenant context implementation (Scoped lifetime - one instance per request)
|
||||
/// </summary>
|
||||
public class TenantContext : ITenantContext
|
||||
{
|
||||
private readonly IHttpContextAccessor _httpContextAccessor;
|
||||
private TenantId? _tenantId;
|
||||
private string? _tenantSlug;
|
||||
|
||||
public TenantContext(IHttpContextAccessor httpContextAccessor)
|
||||
{
|
||||
_httpContextAccessor = httpContextAccessor;
|
||||
InitializeFromHttpContext();
|
||||
}
|
||||
|
||||
public TenantId? TenantId => _tenantId;
|
||||
public string? TenantSlug => _tenantSlug;
|
||||
public bool IsSet => _tenantId != null;
|
||||
|
||||
public void SetTenant(TenantId tenantId, string tenantSlug)
|
||||
{
|
||||
_tenantId = tenantId;
|
||||
_tenantSlug = tenantSlug;
|
||||
}
|
||||
|
||||
public void Clear()
|
||||
{
|
||||
_tenantId = null;
|
||||
_tenantSlug = null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initialize from HTTP Context (extract tenant info from JWT Claims)
|
||||
/// </summary>
|
||||
private void InitializeFromHttpContext()
|
||||
{
|
||||
var httpContext = _httpContextAccessor.HttpContext;
|
||||
if (httpContext?.User?.Identity?.IsAuthenticated == true)
|
||||
{
|
||||
// Extract tenant_id from JWT Claims
|
||||
var tenantIdClaim = httpContext.User.FindFirst("tenant_id");
|
||||
var tenantSlugClaim = httpContext.User.FindFirst("tenant_slug");
|
||||
|
||||
if (tenantIdClaim != null && Guid.TryParse(tenantIdClaim.Value, out var tenantIdGuid))
|
||||
{
|
||||
_tenantId = TenantId.Create(tenantIdGuid);
|
||||
_tenantSlug = tenantSlugClaim?.Value;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user