Convert Figma logo to code with AI

onury logoaccesscontrol

Role and Attribute based Access Control for Node.js

2,190
178
2,190
46

Top Related Projects

17,484

An authorization library that supports access control models like ACL, RBAC, ABAC in Golang: https://discord.gg/S5UjpzGZjN

Access control lists for node applications

The authorization Gem for Ruby on Rails.

Role and Attribute based Access Control for Nestjs 🔐

Quick Overview

AccessControl is a role and attribute-based access control library for Node.js. It provides a flexible and powerful way to manage permissions and access rights in applications, allowing developers to define granular access rules based on roles, resources, and actions.

Pros

  • Lightweight and easy to integrate into existing projects
  • Supports both role-based and attribute-based access control
  • Highly customizable with support for inheritance and grant/deny operations
  • Well-documented with comprehensive API reference

Cons

  • Limited built-in support for database integration (requires custom implementation)
  • May have a steeper learning curve for complex permission structures
  • No built-in user authentication (focuses solely on authorization)

Code Examples

  1. Creating roles and granting permissions:
const ac = new AccessControl();

ac.grant('user')
  .createOwn('profile')
  .readOwn('profile')
  .updateOwn('profile');

ac.grant('admin')
  .extend('user')
  .createAny('profile')
  .readAny('profile')
  .updateAny('profile')
  .deleteAny('profile');
  1. Checking permissions:
const permission = ac.can('user').createOwn('profile');
console.log(permission.granted); // true
console.log(permission.attributes); // ['*']

const adminPermission = ac.can('admin').deleteAny('profile');
console.log(adminPermission.granted); // true
  1. Using attribute-based conditions:
ac.grant('user').condition({Fn:'EQUALS', args:{'requester':'$.owner'}}).readOwn('account');

const permission = ac.can('user').readOwn('account');
console.log(permission.granted); // true
console.log(permission.attributes); // ['*']
console.log(permission.filter(data)); // filtered data based on the condition

Getting Started

  1. Install the package:
npm install accesscontrol
  1. Import and initialize AccessControl:
const AccessControl = require('accesscontrol');
const ac = new AccessControl();
  1. Define roles and permissions:
ac.grant('user')
  .createOwn('profile')
  .readOwn('profile')
  .updateOwn('profile');

ac.grant('admin')
  .extend('user')
  .createAny('profile')
  .readAny('profile')
  .updateAny('profile')
  .deleteAny('profile');
  1. Use in your application:
function checkPermission(role, action, resource) {
  return ac.can(role)[action](resource).granted;
}

console.log(checkPermission('user', 'readOwn', 'profile')); // true
console.log(checkPermission('user', 'deleteAny', 'profile')); // false
console.log(checkPermission('admin', 'deleteAny', 'profile')); // true

Competitor Comparisons

17,484

An authorization library that supports access control models like ACL, RBAC, ABAC in Golang: https://discord.gg/S5UjpzGZjN

Pros of Casbin

  • Supports multiple access control models (ACL, RBAC, ABAC, etc.)
  • Provides policy enforcement for various programming languages and frameworks
  • Offers a flexible, adaptable rule syntax for complex scenarios

Cons of Casbin

  • Steeper learning curve due to its more complex configuration
  • May be overkill for simpler access control needs
  • Requires additional setup and integration compared to AccessControl

Code Comparison

AccessControl:

const ac = new AccessControl();
ac.grant('user').createOwn('article');
ac.can('user').createOwn('article').granted; // true

Casbin:

e := casbin.NewEnforcer("model.conf", "policy.csv")
sub, obj, act := "alice", "data1", "read"
ok, _ := e.Enforce(sub, obj, act)

AccessControl provides a more straightforward API for simple RBAC scenarios, while Casbin offers a more flexible and powerful approach for complex access control needs across multiple languages and frameworks. AccessControl is JavaScript-specific, whereas Casbin supports various programming languages. Casbin's versatility comes at the cost of increased complexity, making it potentially more challenging to implement and maintain for simpler use cases.

Access control lists for node applications

Pros of node_acl

  • Supports backend storage options (e.g., Redis, MongoDB)
  • Provides middleware for Express.js integration
  • Allows for more granular resource-level permissions

Cons of node_acl

  • Less active development and maintenance
  • More complex setup and configuration
  • Limited documentation and examples

Code Comparison

node_acl:

acl.allow('guest', 'blogs', 'view')
acl.isAllowed('joed', 'blogs', 'view', function(err, res){
    if(res){
        console.log("User joed is allowed to view blogs");
    }
});

accesscontrol:

const ac = new AccessControl();
ac.grant('user').createOwn('blog');
ac.can('user').createOwn('blog').granted;    // true
ac.can('user').deleteAny('blog').granted;    // false

node_acl offers more flexibility in defining permissions for specific resources, while accesscontrol provides a simpler and more intuitive API for defining and checking permissions. accesscontrol uses a more declarative approach, making it easier to understand and maintain complex permission structures. However, node_acl's support for various backend storage options can be advantageous for larger applications with specific infrastructure requirements.

The authorization Gem for Ruby on Rails.

Pros of CanCanCan

  • Deeply integrated with Ruby on Rails, providing seamless authorization for Rails applications
  • Offers a more declarative syntax for defining permissions, which can be easier to read and maintain
  • Supports database-backed permissions, allowing for dynamic rule changes without code updates

Cons of CanCanCan

  • Limited to Ruby/Rails ecosystem, not suitable for other programming languages or frameworks
  • Can become complex and harder to manage for large applications with intricate permission structures
  • May have a steeper learning curve for developers not familiar with Ruby on Rails conventions

Code Comparison

CanCanCan:

class Ability
  include CanCan::Ability
  def initialize(user)
    can :read, Post
    can :manage, Post, user_id: user.id
  end
end

AccessControl:

ac.grant('user').createOwn('post')
  .readAny('post')
  .updateOwn('post')
  .deleteOwn('post');

Summary

CanCanCan is a powerful authorization library for Ruby on Rails applications, offering tight integration and a declarative syntax. It excels in Rails projects but is limited to that ecosystem. AccessControl, on the other hand, provides a more flexible and language-agnostic approach to access control, making it suitable for various programming environments. The choice between the two depends on the specific project requirements and the development stack being used.

Role and Attribute based Access Control for Nestjs 🔐

Pros of nest-access-control

  • Specifically designed for NestJS, providing seamless integration with the framework
  • Offers decorators for easy implementation in NestJS controllers and services
  • Supports role-based access control (RBAC) out of the box

Cons of nest-access-control

  • Limited to NestJS applications, reducing flexibility for other frameworks or vanilla JavaScript
  • Less extensive documentation compared to accesscontrol
  • Smaller community and fewer updates, potentially leading to slower issue resolution

Code Comparison

nest-access-control:

@UseGuards(ACGuard)
@UseRoles({
  resource: 'article',
  action: 'read',
  possession: 'any',
})
@Get()
findAll() {
  return this.articleService.findAll();
}

accesscontrol:

const ac = new AccessControl();
ac.grant('user').readAny('article');

if (ac.can('user').readAny('article').granted) {
  // User can read any article
}

Both libraries provide role-based access control, but nest-access-control offers tighter integration with NestJS through decorators. accesscontrol is more versatile and can be used in various JavaScript environments. The choice between them depends on whether you're specifically working with NestJS or need a more general-purpose solution.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

AccessControl.js

Build Status Coverage Status Dependencies Known Vulnerabilities Maintained
npm Release Downloads/mo. License TypeScript Documentation
© 2019, Onur Yıldırım (@onury).


Role and Attribute based Access Control for Node.js

Many RBAC (Role-Based Access Control) implementations differ, but the basics is widely adopted since it simulates real life role (job) assignments. But while data is getting more and more complex; you need to define policies on resources, subjects or even environments. This is called ABAC (Attribute-Based Access Control).

With the idea of merging the best features of the two (see this NIST paper); this library implements RBAC basics and also focuses on resource and action attributes.

Install Examples Roles Actions Resources Permissions More F.A.Q. API Reference

Core Features

  • Chainable, friendly API.
    e.g. ac.can(role).create(resource)
  • Role hierarchical inheritance.
  • Define grants at once (e.g. from database result) or one by one.
  • Grant/deny permissions by attributes defined by glob notation (with nested object support).
  • Ability to filter data (model) instance by allowed attributes.
  • Ability to control access on own or any resources.
  • Ability to lock underlying grants model.
  • No silent errors.
  • Fast. (Grants are stored in memory, no database queries.)
  • Brutally tested.
  • TypeScript support.

In order to build on more solid foundations, this library (v1.5.0+) is completely re-written in TypeScript.

Installation

with npm: npm i accesscontrol --save
with yarn: yarn add accesscontrol

Guide

const AccessControl = require('accesscontrol');
// or:
// import { AccessControl } from 'accesscontrol';

Basic Example

Define roles and grants one by one.

const ac = new AccessControl();
ac.grant('user')                    // define new or modify existing role. also takes an array.
    .createOwn('video')             // equivalent to .createOwn('video', ['*'])
    .deleteOwn('video')
    .readAny('video')
  .grant('admin')                   // switch to another role without breaking the chain
    .extend('user')                 // inherit role capabilities. also takes an array
    .updateAny('video', ['title'])  // explicitly defined attributes
    .deleteAny('video');

const permission = ac.can('user').createOwn('video');
console.log(permission.granted);    // —> true
console.log(permission.attributes); // —> ['*'] (all attributes)

permission = ac.can('admin').updateAny('video');
console.log(permission.granted);    // —> true
console.log(permission.attributes); // —> ['title']

Express.js Example

Check role permissions for the requested resource and action, if granted; respond with filtered attributes.

const ac = new AccessControl(grants);
// ...
router.get('/videos/:title', function (req, res, next) {
    const permission = ac.can(req.user.role).readAny('video');
    if (permission.granted) {
        Video.find(req.params.title, function (err, data) {
            if (err || !data) return res.status(404).end();
            // filter data by permission attributes and send.
            res.json(permission.filter(data));
        });
    } else {
        // resource is forbidden for this user/role
        res.status(403).end();
    }
});

Roles

You can create/define roles simply by calling .grant(<role>) or .deny(<role>) methods on an AccessControl instance.

  • Roles can extend other roles.
// user role inherits viewer role permissions
ac.grant('user').extend('viewer');
// admin role inherits both user and editor role permissions
ac.grant('admin').extend(['user', 'editor']);
// both admin and superadmin roles inherit moderator permissions
ac.grant(['admin', 'superadmin']).extend('moderator');
  • Inheritance is done by reference, so you can grant resource permissions before or after extending a role.
// case #1
ac.grant('admin').extend('user') // assuming user role already exists
  .grant('user').createOwn('video');

// case #2
ac.grant('user').createOwn('video')
  .grant('admin').extend('user');

// below results the same for both cases
const permission = ac.can('admin').createOwn('video');
console.log(permission.granted); // true

Notes on inheritance:

  • A role cannot extend itself.
  • Cross-inheritance is not allowed.
    e.g. ac.grant('user').extend('admin').grant('admin').extend('user') will throw.
  • A role cannot (pre)extend a non-existing role. In other words, you should first create the base role. e.g. ac.grant('baseRole').grant('role').extend('baseRole')

Actions and Action-Attributes

CRUD operations are the actions you can perform on a resource. There are two action-attributes which define the possession of the resource: own and any.

For example, an admin role can create, read, update or delete (CRUD) any account resource. But a user role might only read or update its own account resource.

Action Possession
Create
Read
Update
Delete
Own The C|R|U|D action is (or not) to be performed on own resource(s) of the current subject.
Any The C|R|U|D action is (or not) to be performed on any resource(s); including own.
ac.grant('role').readOwn('resource');
ac.deny('role').deleteAny('resource');

Note that own requires you to also check for the actual possession. See this for more.

Resources and Resource-Attributes

Multiple roles can have access to a specific resource. But depending on the context, you may need to limit the contents of the resource for specific roles.

This is possible by resource attributes. You can use Glob notation to define allowed or denied attributes.

For example, we have a video resource that has the following attributes: id, title and runtime. All attributes of any video resource can be read by an admin role:

ac.grant('admin').readAny('video', ['*']);
// equivalent to:
// ac.grant('admin').readAny('video');

But the id attribute should not be read by a user role.

ac.grant('user').readOwn('video', ['*', '!id']);
// equivalent to:
// ac.grant('user').readOwn('video', ['title', 'runtime']);

You can also use nested objects (attributes).

ac.grant('user').readOwn('account', ['*', '!record.id']);

Checking Permissions and Filtering Attributes

You can call .can(<role>).<action>(<resource>) on an AccessControl instance to check for granted permissions for a specific resource and action.

const permission = ac.can('user').readOwn('account');
permission.granted;       // true
permission.attributes;    // ['*', '!record.id']
permission.filter(data);  // filtered data (without record.id)

See express.js example.

Defining All Grants at Once

You can pass the grants directly to the AccessControl constructor. It accepts either an Object:

// This is actually how the grants are maintained internally.
let grantsObject = {
    admin: {
        video: {
            'create:any': ['*', '!views'],
            'read:any': ['*'],
            'update:any': ['*', '!views'],
            'delete:any': ['*']
        }
    },
    user: {
        video: {
            'create:own': ['*', '!rating', '!views'],
            'read:own': ['*'],
            'update:own': ['*', '!rating', '!views'],
            'delete:own': ['*']
        }
    }
};
const ac = new AccessControl(grantsObject);

... or an Array (useful when fetched from a database):

// grant list fetched from DB (to be converted to a valid grants object, internally)
let grantList = [
    { role: 'admin', resource: 'video', action: 'create:any', attributes: '*, !views' },
    { role: 'admin', resource: 'video', action: 'read:any', attributes: '*' },
    { role: 'admin', resource: 'video', action: 'update:any', attributes: '*, !views' },
    { role: 'admin', resource: 'video', action: 'delete:any', attributes: '*' },

    { role: 'user', resource: 'video', action: 'create:own', attributes: '*, !rating, !views' },
    { role: 'user', resource: 'video', action: 'read:any', attributes: '*' },
    { role: 'user', resource: 'video', action: 'update:own', attributes: '*, !rating, !views' },
    { role: 'user', resource: 'video', action: 'delete:own', attributes: '*' }
];
const ac = new AccessControl(grantList);

You can set grants any time...

const ac = new AccessControl();
ac.setGrants(grantsObject);
console.log(ac.getGrants());

...unless you lock it:

ac.lock().setGrants({}); // throws after locked

Documentation

You can read the full API reference with lots of details, features and examples.
And more at the F.A.Q. section.

Change-Log

See CHANGELOG.

Contributing

Clone original project:

git clone https://github.com/onury/accesscontrol.git

Install dependencies:

npm install

Add tests to relevant file under /test directory and run:

npm run build && npm run cover

Use included tslint.json and editorconfig for style and linting.
Travis build should pass, coverage should not degrade.

License

MIT.

NPM DownloadsLast 30 Days