File size: 1,028 Bytes
6dd9bad | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | 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;
};
|