UNPKG

@bodheesh/create-bodhi-node-app

Version:

Create a production-ready Node.js REST API with zero configuration

31 lines (24 loc) 807 B
import { newEnforcer } from 'casbin'; import { Request, Response, NextFunction } from 'express'; import path from 'path'; export const generateRBACMiddleware = async (modelPath: string, policyPath: string) => { const enforcer = await newEnforcer(modelPath, policyPath); return async (req: Request, res: Response, next: NextFunction) => { try { const { user } = req as any; if (!user) { return res.status(401).json({ error: 'Unauthorized' }); } const { role } = user; const path = req.path; const method = req.method; const allowed = await enforcer.enforce(role, path, method); if (!allowed) { return res.status(403).json({ error: 'Forbidden' }); } next(); } catch (error) { next(error); } }; };