edtech / apps /api /src /middleware /enforceOrgIsolation.ts
CognxSafeTrack
feat: backlog P0→P3 — toast system, payments, tenant isolation, feedback handler, i18n parity
6dd9bad
raw
history blame
1.03 kB
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;
};