import { FastifyRequest, FastifyReply } from 'fastify'; /** * Middleware to enforce organization isolation. * Ensures the requested organization ID matches the user's organization ID. * Injects the organization ID into the request object. */ export const enforceOrgIsolation = async (request: FastifyRequest, reply: FastifyReply) => { const user = request.user; const requestedOrgId = request.headers['x-organization-id'] as string; if (user && user.role !== 'SUPER_ADMIN') { if (requestedOrgId && requestedOrgId !== user.organizationId) { return reply.code(403).send({ error: 'Forbidden', message: 'Organization mismatch' }); } // Inject organization ID from token if missing in headers if (!requestedOrgId) { request.headers['x-organization-id'] = user.organizationId; } } // Set the canonical organizationId property for subsequent hooks/routes request.organizationId = request.headers['x-organization-id'] as string; };