Skip to content

Latest commit

 

History

History
125 lines (113 loc) · 3.65 KB

File metadata and controls

125 lines (113 loc) · 3.65 KB

rbacjs

Role base access control

Build Status NPM version dependencies Status devDependencies Status contributions welcome codecov.io Code Coverage

NPM

Super simple role base access control library. The easiest API and implementation. 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
    )
);