RBAC Permission Check With Roles
Implement role-based access control with role hierarchy inheritance and permission resolution for authorization decisions.
Code
export function rbac(rolePermissions,roleHierarchy={}){function resolve(role){const direct=rolePermissions[role]??[];const inherited=(roleHierarchy[role]??[]).flatMap(resolve);return[...new Set([...direct,...inherited])];}function can(role,perm){return resolve(role).includes(perm);}function checkMiddleware(perm){return(ctx,next)=>{if(!can(ctx.user.role,perm)){ctx.status=403;ctx.body={error:'forbidden'};return;}return next();};}return{can,resolve,checkMiddleware};}How the snippet works
RBAC Permission Check With Roles keeps everything in the functions inherited, rbac, resolve and can.
The result comes back as an object carrying can, resolve.
Applying it
The main signature reads export function rbac(rolePermissions,roleHierarchy={})
rbac is what another module would consume; nothing else here is load-bearing for callers.
The call returns can, resolve — destructure what you need at the call site.
Interactive Tools for This Topic
Basic & Bearer Auth Header ToolEncode and decode HTTP Authorization Basic and Bearer headers locally with UTF-8 Base64 validation and automatic JWT claim and expiry inspection.JWT Expiry CalculatorDecode a JWT payload and convert its exp, iat, and nbf claims into UTC ISO timestamps, with an expired-or-valid verdict.JWT Token DecoderDecode JSON Web Token (JWT) headers and payloads safely in the browser. Inspect expiration, issuer, and claims without sending tokens to any external server.JWT Signature InspectorInspect a JWT signature: decode the header and payload, show the algorithm and signature bytes, and verify HS256/384/512 HMAC signatures with a secret.
FAQ
- Does the runtime need any help from npm, pip, cargo, or the like?
- No — the package manager has nothing to do here; nothing is declared. The file defines `inherited`, `rbac`, `resolve` at load time.
- What does `rbac` return?
- An object carrying `can`, `resolve`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.