Skip to content

Vanilla role-base access control library

License

Notifications You must be signed in to change notification settings

yikesable/rbac

Repository files navigation

@yikesable/rbac

Vanilla role-base access control library

npm version npm downloads neostandard javascript style Module type: ESM Types in JS Follow @voxpelli@mastodon.social

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

  • roleWithContextstring – a role / context combination
  • ...operationsstring – 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 combination
  • done() – completes the creation chain and returns an object with a hasPermission() property

hasPermission()

Syntax

hasPermission('role', 'context', 'operation') => boolean

Arguments

  • rolestring[] | string – the role to check permission for. If an array is given then as long as one of the roles has permission true will be returned
  • contextstring – the context to check permission for, eg blogpost
  • operationstring | '*' – the operation that should be permitted by the role in the context – 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 represent role names and should be string, value can be whatever but true is recommended
  • PermissionContextOperations – extendable interface where represent context names and should be string, value represents possible operations for that context and should be a union of string 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.

About

Vanilla role-base access control library

Resources

License

Stars

Watchers

Forks

Sponsor this project

 

Packages

No packages published