@diaskappassov/casbin-js
TypeScript icon, indicating that this package has built-in type declarations

0.4.0Β β€’Β PublicΒ β€’Β Published

casbin-js

πŸ” Simple library that supports access control models like ACL, RBAC, ABAC in Frontend Javascript.

ts Visit the NPM page Visit package GitHub page

See more about casbin here.

Installation

npm i @diaskappassov/casbin-js

Usage

You can see all usage examples in examples directory.

Initialize Authorizer

To understand what the model and policy read https://casbin.org/docs/syntax-for-models/

import { CAuthorizer } from "@diaskappassov/casbin-js";

const model = `
# Request definition
[request_definition]
# Can subject, do_action, on_object
r = sub, act, obj

# Policy definition
[policy_definition]
p = sub, act, obj

# Role definition
[role_definition]
g = _, _

# Policy effect
[policy_effect]
e = some(where (p.eft == allow))

# Matchers
[matchers]
m = g(r.sub, p.sub) && r.obj == p.obj && r.act == p.act
`;

const policy = [
  ["p", "cat", "walk", "ground"],
  ["p", "cat", "run", "ground"],
  ["p", "cat", "swim", "water"],
  ["p", "cat", "breathe", "air"],

  ["p", "bird", "fly", "air"],
  ["p", "bird", "breathe", "air"],
  ["p", "bird", "walk", "ground"],

  ["p", "fish", "swim", "water"],
  ["p", "fish", "breathe", "water"],
];

const Authorizer = new CAuthorizer();

Authorizer.init(model, policy);

Check permissions

You can check permissions with can, canAll, canAny methods, but before that YOU MUST INITIALIZE Authorizer.

!Important: The order of your request elements must follow the rules which you set in model. See more: https://casbin.org/docs/syntax-for-models#request-definition

Check permissions with can method

Throws error if Authorizer not initialized

await Authorizer.can(["fish", "fly", "air"]); // false
await Authorizer.can(["fish", "swim", "ground"]); // false
await Authorizer.can(["fish", "swim", "water"]); // true
await Authorizer.can(["cat", "swim", "water"]); // true
await Authorizer.can(["bird", "run", "ground"]); // false
await Authorizer.can(["cat", "run", "ground"]); // true

Check permissions with canAll method

// returns `false` cause one of conditions returned `false`
await Authorizer.canAll([
  ["cat", "breathe", "air"],
  ["fish", "breathe", "air"],
]);

// returns `true` cause all conditions returned `true`
await Authorizer.canAll([
  ["cat", "breathe", "air"],
  ["bird", "breathe", "air"],
]);

Check permissions with canAny method

// returns `true` cause one of conditions returned `true`
await authorizer.canAny([
  ["cat", "breathe", "air"],
  ["fish", "breathe", "air"],
]);

// returns `false` cause all conditions returned `false`
await authorizer.canAny([
  ["cat", "fly", "air"],
  ["fish", "fly", "air"],
]);

Author

Package Sidebar

Install

npm i @diaskappassov/casbin-js

Weekly Downloads

5

Version

0.4.0

License

MIT

Unpacked Size

39.9 kB

Total Files

15

Last publish

Collaborators

  • diaskappassov