guantr
TypeScript icon, indicating that this package has built-in type declarations

1.0.0 • Public • Published

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 install guantr

# bun
bun install guantr

# deno
deno install guantr

Import:

ESM (Node.js, Bun, Deno)

import { createGuantr } from "guantr";

CommonJS (Legacy Node.js)

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

CDN (Deno, Bun 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

Readme

Keywords

none

Package Sidebar

Install

npm i guantr

Weekly Downloads

6

Version

1.0.0

License

MIT

Unpacked Size

101 kB

Total Files

16

Last publish

Collaborators

  • hrdtr