38 lines
1.6 KiB
JavaScript
38 lines
1.6 KiB
JavaScript
// FILE: src/middleware/requirePerm.js
|
|
// 03.2 4) เพิ่ม middleware requirePerm (ใหม่)
|
|
// นำ middleware นี้ไปใส่ หลัง loadPrincipal เสมอ เช่น app.use('/api', authJwt(), loadPrincipalMw(), requirePerm('correspondence.create', {scope:'org', getOrgId: req=>...}), routes)
|
|
// หรือใส่ใน route เดี่ยวๆ ก็ได้ เช่น router.post('/', requirePerm('correspondence.create', {scope:'org', getOrgId: req=>...}), (req,res)=>{...})
|
|
// Permission requirement middleware with scope support
|
|
// - Uses canPerform() utility from rbac.js
|
|
// - Supports global, org, and project scopes
|
|
// - Requires req.principal to be populated (e.g. via loadPrincipal middleware)
|
|
|
|
import { canPerform } from "../utils/rbac.js";
|
|
|
|
/**
|
|
* requirePerm('correspondence.create', { scope: 'org', getOrgId: req => ... })
|
|
* scope: 'global' | 'org' | 'project'
|
|
*/
|
|
export function requirePerm(
|
|
permCode,
|
|
{ scope = "global", getOrgId = null, getProjectId = null } = {}
|
|
) {
|
|
return async (req, res, next) => {
|
|
try {
|
|
const orgId = getOrgId ? await getOrgId(req) : null;
|
|
const projectId = getProjectId ? await getProjectId(req) : null;
|
|
|
|
if (canPerform(req.principal, permCode, { scope, orgId, projectId }))
|
|
return next();
|
|
|
|
return res.status(403).json({
|
|
error: "FORBIDDEN",
|
|
message: `Require ${permCode} (${scope}-scoped)`,
|
|
});
|
|
} catch (e) {
|
|
console.error("requirePerm error", e);
|
|
res.status(500).json({ error: "Permission check error" });
|
|
}
|
|
};
|
|
}
|