31 lines
898 B
TypeScript
31 lines
898 B
TypeScript
|
|
import { NextFunction, Response } from "express";
|
||
|
|
import { RequestWithAuth } from "./auth-types";
|
||
|
|
|
||
|
|
/**
|
||
|
|
* Middleware que exige presencia de usuario y companyId.
|
||
|
|
* Debe ir DESPUÉS del middleware de autenticación.
|
||
|
|
*/
|
||
|
|
export function enforceTenant() {
|
||
|
|
return (req: RequestWithAuth, res: Response, next: NextFunction) => {
|
||
|
|
// Validación básica del tenant
|
||
|
|
if (!req.user || !req.user.companyId) {
|
||
|
|
return res.status(401).json({ error: "Unauthorized" });
|
||
|
|
}
|
||
|
|
next();
|
||
|
|
};
|
||
|
|
}
|
||
|
|
|
||
|
|
/**
|
||
|
|
* Mezcla el companyId del usuario en el criteria de listados, ignorando cualquier companyId entrante.
|
||
|
|
* Evita evasión de tenant por parámetros manipulados.
|
||
|
|
*/
|
||
|
|
export function scopeCriteriaWithCompany<T extends Record<string, any>>(
|
||
|
|
criteria: T | undefined,
|
||
|
|
companyId: string
|
||
|
|
): T & { companyId: string } {
|
||
|
|
return {
|
||
|
|
...(criteria ?? ({} as T)),
|
||
|
|
companyId, // fuerza el scope
|
||
|
|
};
|
||
|
|
}
|