First Commit
This commit is contained in:
57
Helpers/ADS.Helpers.Middleware/Tenant/TenantMiddleware.cs
Normal file
57
Helpers/ADS.Helpers.Middleware/Tenant/TenantMiddleware.cs
Normal file
@@ -0,0 +1,57 @@
|
||||
using System.Threading.Tasks;
|
||||
using ADS.Helpers.Base.Abstractions;
|
||||
using ADS.Helpers.MultiTenant.Abstractions;
|
||||
using ADS.Helpers.MultiTenant.Context;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
|
||||
namespace ADS.Helpers.Middleware.Tenant;
|
||||
|
||||
public sealed class TenantMiddleware
|
||||
{
|
||||
private readonly RequestDelegate _next;
|
||||
|
||||
public TenantMiddleware(RequestDelegate next)
|
||||
{
|
||||
_next = next;
|
||||
}
|
||||
|
||||
// Scoped dependencies se resuelven aquí (por request)
|
||||
public async Task InvokeAsync(
|
||||
HttpContext context,
|
||||
ITenantResolver tenantResolver,
|
||||
ITenantStore tenantStore,
|
||||
ITenantContextAccessor tenantContextAccessor,
|
||||
IAppLogger log)
|
||||
{
|
||||
var tenantKey = tenantResolver.Resolve(context);
|
||||
|
||||
if (string.IsNullOrWhiteSpace(tenantKey))
|
||||
{
|
||||
log.Warn("ADS.MultiTenant", "TENANT_NOT_RESOLVED", "Tenant key could not be resolved.");
|
||||
context.Response.StatusCode = StatusCodes.Status400BadRequest;
|
||||
await context.Response.WriteAsync("Tenant not resolved.");
|
||||
return;
|
||||
}
|
||||
|
||||
var tenant = await tenantStore.GetAsync(tenantKey);
|
||||
|
||||
if (tenant is null)
|
||||
{
|
||||
log.Warn("ADS.MultiTenant", "TENANT_NOT_FOUND", $"Tenant '{tenantKey}' not found.");
|
||||
context.Response.StatusCode = StatusCodes.Status404NotFound;
|
||||
await context.Response.WriteAsync("Tenant not found.");
|
||||
return;
|
||||
}
|
||||
|
||||
tenantContextAccessor.SetCurrent(tenant);
|
||||
|
||||
try
|
||||
{
|
||||
await _next(context);
|
||||
}
|
||||
finally
|
||||
{
|
||||
tenantContextAccessor.SetCurrent(null);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user