feat(api): add tenant middleware for multi-tenant schema isolation

This commit is contained in:
Consultoria AS
2026-01-22 02:17:15 +00:00
parent 7cc8842f8d
commit 5bd5f9cef9

View File

@@ -0,0 +1,37 @@
import type { Request, Response, NextFunction } from 'express';
import { prisma } from '../config/database.js';
import { AppError } from './error.middleware.js';
declare global {
namespace Express {
interface Request {
tenantSchema?: string;
}
}
}
export async function tenantMiddleware(req: Request, res: Response, next: NextFunction) {
if (!req.user) {
return next(new AppError(401, 'No autenticado'));
}
try {
const tenant = await prisma.tenant.findUnique({
where: { id: req.user.tenantId },
select: { schemaName: true, active: true },
});
if (!tenant || !tenant.active) {
return next(new AppError(403, 'Tenant no encontrado o inactivo'));
}
req.tenantSchema = tenant.schemaName;
// Set search_path for this request
await prisma.$executeRawUnsafe(`SET search_path TO "${tenant.schemaName}", public`);
next();
} catch (error) {
next(new AppError(500, 'Error al configurar tenant'));
}
}