Hierarchical Role Based Access Control for Node.js
npm install rbacimport{RBAC}from'rbac';constrbac=newRBAC({roles: ['superadmin','admin','user','guest'],permissions: {user: ['create','delete'],password: ['change','forgot'],article: ['create'],rbac: ['update'],},grants: {guest: ['create_user','forgot_password'],user: ['change_password'],admin: ['user','delete_user','update_rbac'],superadmin: ['admin'],},});awaitrbac.init();constcan=awaitrbac.can('admin','create','article');if(can){console.log('Admin is able to create article');}Or use a role instance:
constadmin=awaitrbac.getRole('admin');if(!admin){console.log('Role does not exist');}else{constcan=awaitadmin.can('create','article');if(can){console.log('Admin is able to create article');}}RBAC uses in-memory storage by default. You can implement custom storage by extending the Storage class:
import{Storage}from'rbac';classMyStorageextendsStorage{asyncadd(item){/* ... */}asyncremove(item){/* ... */}asyncgrant(role,child){/* ... */}asyncrevoke(role,child){/* ... */}asyncget(name){/* ... */}asyncgetRoles(){/* ... */}asyncgetPermissions(){/* ... */}asyncgetGrants(role){/* ... */}}constrbac=newRBAC({storage: newMyStorage()});npm testMIT