Skip to content

Hrdtr/guantr

Repository files navigation

Guantr

npm version npm downloads

Flexible, type-safe JavaScript library for efficient authorization and permission checking. Easily manage permissions, and context-aware access control with minimal overhead and a simple API.

Usage

Install package:

# ✨ Auto-detect
npx nypm install guantr

# npm
npm install guantr

# yarn
yarn add guantr

# pnpm
pnpm add guantr

# bun
bun install guantr

# deno
deno install npm:guantr

Import:

ESM (Node.js, Bun, Deno)

import { createGuantr } from 'guantr';

CommonJS (Legacy Node.js)

const { createGuantr } = require('guantr');

CDN (Deno and Browsers)

import { createGuantr } from 'https://esm.sh/guantr';

Initialize:

const guantr = await createGuantr();

// With Typescript Meta:
type Meta = GuantrMeta<{
  post: {
    action: 'create' | 'read' | 'update' | 'delete';
    model: {
      id: number;
      title: string;
      published: boolean;
    };
  };
}>;

const guantr = await createGuantr<Meta>();

// Contextual
const user = {
  id: number,
  name: 'John Doe',
  roles: ['admin'],
};
const guantrWithContext = await createGuantr<Meta, { user: typeof user }>({
  getContext: () => ({ user }),
});

Setting rules:

await guantr.setRules((can, cannot) => {
  can('read', 'post');
  cannot('read', ['post', { published: ['eq', false] }]);
});
// Or
await guantr.setRules([
  {
    resource: 'post',
    action: 'read',
    condition: null,
    effect: 'allow',
  },
  {
    resource: 'post',
    action: 'read',
    condition: {
      published: ['eq', false],
    },
    effect: 'deny',
  },
]);

Rules also can be set on instance creation:

const guantr = await createGuantr<Meta>([
  {
    resource: 'post',
    action: 'read',
    condition: {
      published: ['eq', false],
    },
    effect: 'deny',
  },
]);

Authorize:

await guantr.can('read', 'post'); // true

const post = {
  id: 1,
  title: 'Hello World',
  published: false,
};
await guantr.can('read', ['post', post]); // false

Development

local development
  • Clone this repository
  • Install latest LTS version of Node.js
  • Enable Corepack using corepack enable
  • Install dependencies using pnpm install
  • Run interactive tests using pnpm dev

License

Published under the MIT license. Made by community 💛


🤖 auto updated with automd

About

Flexible, type-safe JavaScript library for efficient authorization and permission checking

Topics

Resources

License

Stars

Watchers

Forks

Sponsor this project

 

Packages

 
 
 

Contributors