@yikesable/rbac
v0.1.0
Published
Vanilla role-base access control library
Downloads
4
Readme
@yikesable/rbac
Vanilla role-base access control library
Usage
import { addRolePermission } from '@yikesable/rbac';
const { hasPermission } =
addRolePermission('admin:foo', '*')
.addRolePermission('editor:bar', 'wow')
.done();
if (hasPermission('admin', 'foo', 'create') === true) {
// "create" operation allowed for "foo" for role "admin"
}
API
addRolePermission()
Adds operations that a role is allowed to do on a role.
Each role / context combination can only be set once.
Syntax
addRolePermission('role:context', 'create', 'update', 'delete') => { addRolePermission, done }
Arguments
roleWithContext
–string
– a role / context combination...operations
–string
– the options to be permitted for the combination. If'*'
is set then all operations will be permitted.
Returns
An object with these properties:
addRolePermission()
– chaining that adds operations for another role / context combinationdone()
– completes the creation chain and returns an object with ahasPermission()
property
hasPermission()
Syntax
hasPermission('role', 'context', 'operation') => boolean
Arguments
role
–string[] | string
– the role to check permission for. If an array is given then as long as one of the roles has permissiontrue
will be returnedcontext
–string
– the context to check permission for, egblogpost
operation
–string | '*'
– the operation that should be permitted by therole
in thecontext
– eg.create
,update
,update-own
or similar
Returns
A boolean
that indicates whether the role has permission or not.
Types
import type { PermissionCrudOperation } from '@yikesable/rbac';
declare module '@yikesable/rbac' {
interface PermissionRoleList {
admin: true;
editor: true;
}
interface PermissionContextOperations {
foo: PermissionCrudOperation; // 'create' | 'read' | 'update' | 'delete'
bar: 'wow' | 'yay';
}
}
PermissionRoleList
– extendable interface where keys representrole
names and should bestring
, value can be whatever buttrue
is recommendedPermissionContextOperations
– extendable interface where representcontext
names and should bestring
, value represents possibleoperations
for thatcontext
and should be a union ofstring
values
role
and context
in addRolePermission()
and hasPermission
are limited to the values derived from above interfaces and operations
gets limited to the operations
defined in PermissionContextOperations
for the context
used in those functions.