0.1.0 • Published 1 year ago
@yikesable/rbac v0.1.0
@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') => booleanArguments
role–string[] | string– the role to check permission for. If an array is given then as long as one of the roles has permissiontruewill be returnedcontext–string– the context to check permission for, egblogpostoperation–string | '*'– the operation that should be permitted by therolein thecontext– eg.create,update,update-ownor 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 representrolenames and should bestring, value can be whatever buttrueis recommendedPermissionContextOperations– extendable interface where representcontextnames and should bestring, value represents possibleoperationsfor thatcontextand should be a union ofstringvalues
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.
0.1.0
1 year ago