import type { HttpContext } from '@adonisjs/core/http' import type { NextFn } from '@adonisjs/core/types/http' import TenantAccessService, { type ResolvedTenant, } from '#base_modules/Tenant/services/tenant_access_service' type TenantContext = ResolvedTenant export default class ResolveTenantMiddleware { async handle(ctx: HttpContext, next: NextFn) { const header = ctx.request.header('x-tenant-id') if (!header) return ctx.response.badRequest({ code: 'E_TENANT_REQUIRED', message: 'The X-Tenant-Id header is required.', }) const tenantId = Number(header) if (!Number.isSafeInteger(tenantId) || tenantId < 1) { return ctx.response.badRequest({ code: 'E_INVALID_TENANT_ID', message: 'The X-Tenant-Id header must be a positive integer.', }) } const tenant = await new TenantAccessService().resolveForAdmin(ctx.auth.user!.id, tenantId) if (!tenant) return ctx.response.forbidden({ code: 'E_TENANT_ACCESS_DENIED', message: 'You do not have access to this tenant.', }) ctx.tenant = tenant return next() } } declare module '@adonisjs/core/http' { export interface HttpContext { tenant: TenantContext } }