feat(api): add tenant middleware for multi-tenant schema isolation
This commit is contained in:
37
apps/api/src/middlewares/tenant.middleware.ts
Normal file
37
apps/api/src/middlewares/tenant.middleware.ts
Normal 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'));
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user