rbacjs
v2.0.3
Published
Role based access control.
Downloads
39
Maintainers
Readme
rbacjs
Role base access control
Simple in-memory role-based access control library. Can be used on the client and server side.
Examples:
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
)
);