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; if (!user) return; if (user.role === 'SUPER_ADMIN') { // Super-admins may target any org via the header; fall back to their own org. const headerOrgId = request.headers['x-organization-id'] as string | undefined; request.organizationId = headerOrgId || user.organizationId; } else { // All other roles: org is authoritative from the JWT — never trust the header. request.organizationId = user.organizationId; } };