@pstl/perms
TypeScript icon, indicating that this package has built-in type declarations

1.2.0 • Public • Published

Permwise

Lightweight permissions handler purely using bitwise operations written in TypeScript.


Usage

import { Role, Shift } from "@pstl/perms";

// Create permission numbers
const PERMISSION_1: number = Shift( 0 ); // 1 << 0
const PERMISSION_2: number = Shift( 1 ); // 1 << 1
const PERMISSION_3: number = Shift( 2 ); // 1 << 2

// Create new Role object
const role: Role = new Role()
    .addPermissions( [ PERMISSION_1, PERMISSION_2, PERMISSION_3 ] )
    .removePermission( PERMISSION_2 );

console.log( role.has( PERMISSION_2 ) ); // false
console.log( role.has( PERMISSION_1 ) ); // true

role.addPermission( PERMISSION_2 );

console.log( role.has( PERMISSION_2 ) ); // true

NOTE: BigInt only allows for up to 2^52 or else bitwise operations are inaccurate. This means there are a maximum of 53 permissions supported in this method. If you wish to expand that, you could create "subgroup" permissions. For example:

...

// Where group is an isolated set of permissions
const Permissions = [
    group_1, group_2, group_3, ..., group_n
]

Role Class

Methods

Method Parameters Description Return Type
has perm: number Checks if this Role has a permission boolean
hasExplicit perm: number Checks if this Role explicitly has a permission (without Administrator override option) boolean
has
static perms: number
perm: number
Checks if a given permissions number contains a permission boolean
addPermission perms: number Adds a permission to a Role Role
addPermissions perms: Array<number> Adds a list of permissions to a Role Role
removePermission perm: number Removes a permission from a Role Role
removePermissions perms: Array<number> Removes a list of permissions from a Role Role

Properties

Property Type Default Description
name string null An optional property that describes the Role
permissions number 0 A number that contains all bitwise-calculated permission numbers (default=0)
override number null A permission override that gives a user access to all permissions (Administrator override)

Math

Checking if a permissions number contains a permission:

( X & Y === Y )

Given permissions X: 1 0 1 1
Checking for Y: 1 0 0 0

1 0 1 1 & 1 0 0 0 = 1 0 0 0


Package Sidebar

Install

npm i @pstl/perms

Weekly Downloads

4

Version

1.2.0

License

ISC

Unpacked Size

36.9 kB

Total Files

21

Last publish

Collaborators

  • danieladamce
  • ethanzs