23 lines
690 B
TypeScript
23 lines
690 B
TypeScript
import { Request, Response, NextFunction } from 'express';
|
|
|
|
export type AccessRule = { role: string; product?: string };
|
|
|
|
export function requireAccess( rules: AccessRule[] )
|
|
{
|
|
return ( req: Request, res: Response, next: NextFunction ): void =>
|
|
{
|
|
const auth = req.auth;
|
|
if ( !auth ) { res.status( 401 ).json( { error: 'Not authenticated' } ); return; }
|
|
|
|
if ( auth.roles.includes( 'superadmin' ) ) { next(); return; }
|
|
|
|
const allowed = rules.some( rule =>
|
|
auth.roles.includes( rule.role ) &&
|
|
( !rule.product || auth.products.includes( rule.product ) )
|
|
);
|
|
|
|
if ( allowed ) { next(); return; }
|
|
res.status( 403 ).json( { error: 'Forbidden' } );
|
|
};
|
|
}
|