rbacjs
TypeScript icon, indicating that this package has built-in type declarations

2.0.3 • Public • Published

rbacjs

Role base access control

Build Status codecov contributions welcome

NPM

Simple in-memory role-based access control library. Can be used on the client and server side.

Examples:

Basic example

Redux

ExpressJS

API:

Initialize RBAC with config:

interface IRBACConfig {
    rolesConfig: [                      // array with roles configurations
        {
            roles: string[],
            permissions: string[]
        }
    ];
    debug?: boolean;               // do not print warnings in console, by default true
}

const rbacConfig: IRBACConfig = {
    rolesConfig: [
        {
            roles: ['ROLE'],
            permissions: ['PERMISSION_ID']
        }
    ]
};
const rbac = new RBAC(rbacConfig);

Get roles list for user:

rbac.getUserRoles(userId: string) => string[] | Error;

Add user to RBAC with roles:

rbac.addUserRoles(userId: string, roles: string[]) => void | Error;

Remove users roles (in case if roles parameter is not defined, will be removed all roles for userId):

rbac.removeUserRoles(userId: string, roles?: string[]) => void | Error;

Check permission for user:

rbac.isAllowed(userId: string, permissionId: string) => boolead | Error;

Extend role:

rbac.extendRole(role: string, extendingRoles: string[]) => void | Error;

// example, expand manager role with viewers and users permissions:
rbac.extendRole('manager', extendingRoles: ['viewer', 'user']);

Middleware method, invoke success callback in case if user have permission or error callback if not:

rbac.middleware(
    params: {
        userId: string;
        permissionId: string;
    },
    error: () => void,
    success: () => void
)
Express middleware example:
app.use((req, res, next) => {
    rbac.middleware(
        {
            userId: req.body.userId,
            permissionId: req.body.permissionId
        },
        () => {
            res.status(403).send('access denied');
        },
        next
    );
});
Redux middleware example:
const rbacMiddleware = store => next => action => {
    rbac.middleware(
        {
            userId: action.payload.userId,
            permissionId: action.payload.permissionId
        },
        () => {
            next({
               type: ACTION_ACCESS_DENIED,
               payload: action
            });
        },
        () => {
            next(action);
        }
    );
};

const store = createStore(
    // ...
    applyMiddleware(
        // ...
        rbacMiddleware
    )
);

Package Sidebar

Install

npm i rbacjs

Weekly Downloads

6

Version

2.0.3

License

MIT

Unpacked Size

117 kB

Total Files

19

Last publish

Collaborators

  • a.zahorovskyi