RBAC Permission Check With Roles

Implement role-based access control with role hierarchy inheritance and permission resolution for authorization decisions.

JavascriptAuth Jwt

Code

javascriptsnippet
1 line
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

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`.