{"id":22489977,"url":"https://github.com/tensult/role-acl","last_synced_at":"2025-08-02T22:31:54.260Z","repository":{"id":56304823,"uuid":"103414511","full_name":"tensult/role-acl","owner":"tensult","description":"Role based access control using actions, attributes and sync and async conditions","archived":true,"fork":false,"pushed_at":"2020-11-15T21:35:32.000Z","size":620,"stargazers_count":503,"open_issues_count":10,"forks_count":34,"subscribers_count":12,"default_branch":"develop","last_synced_at":"2024-11-16T15:07:03.388Z","etag":null,"topics":["access-control","attributes","conditions","nodejs","roles","tests","typescript"],"latest_commit_sha":null,"homepage":"https://www.tensult.com","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"other","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/tensult.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2017-09-13T15:05:15.000Z","updated_at":"2024-10-22T09:51:04.000Z","dependencies_parsed_at":"2022-08-15T16:20:36.028Z","dependency_job_id":null,"html_url":"https://github.com/tensult/role-acl","commit_stats":null,"previous_names":[],"tags_count":73,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/tensult%2Frole-acl","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/tensult%2Frole-acl/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/tensult%2Frole-acl/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/tensult%2Frole-acl/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/tensult","download_url":"https://codeload.github.com/tensult/role-acl/tar.gz/refs/heads/develop","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":228500590,"owners_count":17930096,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["access-control","attributes","conditions","nodejs","roles","tests","typescript"],"created_at":"2024-12-06T17:21:26.164Z","updated_at":"2024-12-06T17:23:45.063Z","avatar_url":"https://github.com/tensult.png","language":"TypeScript","funding_links":["https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick\u0026hosted_button_id=73QY55FZWSPRJ"],"categories":["TypeScript"],"sub_categories":[],"readme":"[![Donate](https://img.shields.io/badge/Donate-PayPal-green.svg)](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick\u0026hosted_button_id=73QY55FZWSPRJ) [![Build Status](https://travis-ci.org/tensult/role-acl.png?branch=master)](https://travis-ci.org/tensult/role-acl) [![Test Coverage](https://api.codeclimate.com/v1/badges/2d748a99b2c54e057cc2/test_coverage)](https://codeclimate.com/github/tensult/role-acl/test_coverage) [![NPM Version](https://badge.fury.io/js/role-acl.svg?style=flat)](https://npmjs.org/package/role-acl) [![contributions welcome](https://img.shields.io/badge/contributions-welcome-brightgreen.svg?style=flat)](https://github.com/tensult/role-acl/issues)\n\nRole, Attribute and conditions based Access Control for Node.js  \n\n`npm i role-acl --save`  \n\nMany [RBAC][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][abac] (Attribute-Based Access Control).\n\nWith the idea of merging the best features of the two (see this [NIST paper][nist-paper]); this library implements RBAC basics and also focuses on *resource*, *action* attributes and conditions.\n\nThis library is an extension of [AccessControl][onury-accesscontrol]. But I removed support for possession and deny statements from orginal implementation.\n\n### Core Features\n\n- Chainable, friendly API.  \ne.g. `ac.can(role).execute('create').on(resource)`\n- Role hierarchical inheritance.\n- Define grants at once (e.g. from database result) or one by one.\n- Grant permissions by resources and actions define by glob notation.\n- Grant permissions by attributes defined by glob notation (with nested object support).\n- Ability to filter data (model) instance by allowed attributes.\n- Ability to control access using conditions.\n- Supports AND, OR, NOT, EQUALS, NOT_EQUALS, STARTS_WITH, LIST_CONTAINS core conditions.\n- You can specify dynamic context values in the core conditions using JSON Paths.\n- Supports your own custom conditions e.g. `custom:isArticleOwner`.\n- You can define your own function conditions too but please note if you use custom functions instead of standard conditions, you won't be able to save them as json in the DB.\n- Policies are JSON compatible so can be stored and retrieved from database.\n- Fast. (Grants are stored in memory, no database queries.)\n- TypeScript support.\n- **Note**: \n  - For versions \u003c 4.0: follow this [ReadMe](https://github.com/tensult/role-acl/blob/6cde220e5d4956270c60f5fe58f84dcd8a257924/README.md).\n\n## Guide\n\n```js\nconst AccessControl = require('role-acl');\n// or:\n// import { AccessControl } from 'role-acl';\n```\n\n## Examples\n### Basic Examples\nDefine roles and grants one by one.\n```js\nconst ac = new AccessControl();\nac.grant('user')                    // define new or modify existing role. also takes an array.\n    .execute('create').on('video')             // equivalent to .execute('create').on('video', ['*'])\n    .execute('delete').on('video')\n    .execute('read').on('video')\n  .grant('admin')                   // switch to another role without breaking the chain\n    .extend('user')                 // inherit role capabilities. also takes an array\n    .execute('update').on('video', ['title'])  // explicitly defined attributes\n    .execute('delete').on('video');\n\nconst permission = ac.can('user').execute('create').sync().on('video'); // \u003c-- Sync Example\nconst permission = await ac.can('user').execute('create').on('video'); // \u003c-- Async Example\nconsole.log(permission.granted);    // —\u003e true\nconsole.log(permission.attributes); // —\u003e ['*'] (all attributes)\n\npermission = ac.can('admin').execute('update').sync().on('video'); // \u003c-- Sync Example\npermission = await ac.can('admin').execute('update').on('video'); // \u003c-- Async Example\nconsole.log(permission.granted);    // —\u003e true\nconsole.log(permission.attributes); // —\u003e ['title']\n```\n\n### Conditions Examples\n\n```js\nconst ac = new AccessControl();\nac.grant('user').condition(\n    {\n        Fn: 'EQUALS',\n        args: {\n            'category': 'sports'\n        }\n    }).execute('create').on('article');\n\nlet permission = ac.can('user').context({ category: 'sports' }).execute('create').sync().on('article'); // \u003c-- Sync Example\nlet permission = await ac.can('user').context({ category: 'sports' }).execute('create').on('article'); // \u003c-- Async Example\nconsole.log(permission.granted);    // —\u003e true\nconsole.log(permission.attributes); // —\u003e ['*'] (all attributes)\n\npermission = ac.can('user').context({ category: 'tech' }).execute('create').sync().on('article'); // \u003c-- Sync Example\npermission = await ac.can('user').context({ category: 'tech' }).execute('create').on('article'); // \u003c-- Async Example\nconsole.log(permission.granted);    // —\u003e false\nconsole.log(permission.attributes); // —\u003e []\n\n// Condition with dynamic context values using JSONPath\n// We can use this to allow only owner of the article to edit it\nac.grant('user').condition(\n    {\n        Fn: 'EQUALS',\n        args: {\n            'requester': '$.owner'\n        }\n    }).execute('edit').on('article');\n\npermission =  ac.can('user').context({ requester: 'dilip', owner: 'dilip' }).execute('edit').sync().on('article'); // \u003c-- Sync Example\npermission =  await ac.can('user').context({ requester: 'dilip', owner: 'dilip' }).execute('edit').on('article'); // \u003c-- Async Example\nconsole.log(permission.granted);    // —\u003e true\n\n// We can use this to prevent someone to approve their own article so that it goes to review \n// by someone else before publishing\nac.grant('user').condition(\n    {\n        Fn: 'NOT_EQUALS',\n        args: {\n            'requester': '$.owner'\n        }\n    }).execute('approve').on('article');\n\npermission = ac.can('user').context({ requester: 'dilip', owner: 'dilip' }).execute('approve').sync().on('article'); // \u003c-- Sync Example\npermission = await ac.can('user').context({ requester: 'dilip', owner: 'dilip' }).execute('approve').on('article'); // \u003c-- Async Example\nconsole.log(permission.granted);    // —\u003e false\n\n// Using custom/own condition functions\nac.grant('user').condition(\n    (context) =\u003e {\n        return context.category !== 'politics'\n    }\n).execute('create').on('article');\npermission = ac.can('user').context({ category: 'sports' }).execute('create').sync().on('article'); // \u003c-- Sync Example\npermission = await ac.can('user').context({ category: 'sports' }).execute('create').on('article'); // \u003c-- Async Example\nconsole.log(permission.granted);    // —\u003e true\n```\n\n### Custom Conditions\n\nYou can declare your own conditions (**requires version \u003e= 4.5.2**). Those declarations should be registerd with the library BEFORE your grants and permission checks. The custom condition declarations are allowing you to extend the library core conditions with your own business logic without sacrificing the abillity to serialize your grants.\n\n**Basic example:**\n```js\n// 1. Define the condition handler\nconst greaterOrEqual = (context, args) =\u003e {\n    if (!args || typeof args.level !== 'number') {\n        throw new Error('custom:gte requires \"level\" argument');\n    }\n\n    return +context.level \u003e= args.level;\n}\n\nconst ac = new AccessControl();\n\n// 2. Register the condition with appropriate name\nac.registerConditionFunction('gte', greaterOrEqual);\n\n// 3. Use it in grants, same as core conditions but with \"custom:\" prefix\nac.grant('user')\n    .condition({\n        Fn: 'custom:gte', \n        args: { level: 2 }\n    })\n    .execute('comment').on('article');\n\n// 4. Evaluate permissions with appropraite context (sync) - same as core conditions\nconst permission1 = ac\n    .can('user')\n    .context({ level: 2 })\n    .execute('comment')\n    .sync()\n    .on('article');\n\n// prints \"LEVEL 2 true\"\nconsole.log('LEVEL 2', permission1.granted);\n\nconst permission2 = ac\n    .can('user')\n    .context({ level: 1 })\n    .execute('comment')\n    .sync()\n    .on('article');\n\n// prints \"LEVEL 1 false\"\nconsole.log('LEVEL 1', permission2.granted);\n```\n\n**Argument is optional:**  \n\nCustom condition argument is optional - same as core conditions. \n\n```js\nconst myConditions = {\n    isArticleOwner: (context) =\u003e {\n        return context.loginUserId \u0026\u0026 context.loginUserId === context.articleOwnerId\n    }\n}\nconst ac = new AccessControl();\nac.registerConditionFunction('isArticleOwner', myConditions.isArticleOwner);\nac.grant(\"user\").condition('custom:isArticleOwner')\n    .execute(['delete', 'update']).on('article');\n\nac.can('user').context({ loginUserId: 1, articleOwnerId: 1 })\n    .execute('update').sync().on('article'); \n// { granted: true }\n```\n\n**Custom condition can be async:**\n```js\nimport { asyncCheckResourceForUser } from './somewhere'; \n\nconst myConditions = {\n    isResourceOwner: (context, args) =\u003e {\n        const { resource } = args || {};\n        const { loginUserId } = context;\n        // your business logic to check resource owner e.g. vs DB\n        // send resource name, currently logged in user ID, record.id \n        return asyncCheckResourceForUser(resource, loginUserId, context[resource]);\n    }\n}\nconst ac = new AccessControl();\nac.registerConditionFunction('isResourceOwner', myConditions.isResourceOwner);\n\nac.grant(\"user\")\n    .condition({ Fn: 'custom:isResourceOwner', args: { resource: 'article' } })\n    .execute(['delete', 'update'])\n    .on('article');\n\n// Provide currently logged in user and article.id in the context\nawait ac.can('user').context({ loginUserId: 1, article: { id: 10 } })\n    .execute('update').on('article'); \n```\n\n**Custom conditions allow security policy serializing and can be registered while initializing (in batch):**\n\n\u003e NOTE: function conditions are not serializeable, so custom conditions are the recommended way to implement your permission policy. You can easiely convert your current function conditions to custom conditions.\n\n```js\nconst myPolicy = {\n    // Serialized policy, can be stored in file, DB, etc\n    grants: [\n        {\n            role: 'user', \n            resource: 'profile', \n            action: ['delete', 'update'], \n            attributes: ['*'],\n            condition: {\n                Fn: 'custom:isResourceOwner',\n                args: { resource: 'profile' }\n            }\n        },\n        {\n            role: 'user', \n            resource: 'article', \n            action: ['delete', 'update'], \n            attributes: ['*'],\n            condition: {\n                Fn: 'custom:isResourceOwner',\n                args: { resource: 'article' }\n            }\n        },\n    ],\n    // Map your custom conditions to the serialized policy\n    myConditions: {\n        isResourceOwner: async ({ user, record }, { resource } = {}) =\u003e {\n            // Your business logic here, e.g. query database...\n            if (resource === 'profile' \u0026\u0026 user.id === 1 \u0026\u0026 record.id === 1) {\n                return true;\n            }\n            if (resource === 'article' \u0026\u0026 user.id === 1 \u0026\u0026 record.id === 2) {\n                return true;\n            }\n            return false;\n        }\n    }\n};\n\n// Register everything on initialization\nconst ac = new AccessControl(myPolicy.grants, myPolicy.myConditions);\n\n// Use it\nawait ac.can('user').context({ user: { id: 1 }, record: { id: 1 } })\n    .execute('update').on('profile'); // { granted: true }\n\nawait ac.can('user').context({ user: { id: 1 }, record: { id: 1 } })\n    .execute('delete').on('article');  // { granted: false }\n\nawait ac.can('user').context({ user: { id: 1 }, record: { id: 2 } })\n    .execute('delete').on('article');  // { granted: true }\n```\n\n**Mix with core conditions, use JSON path helper:**  \n\n\u003e NOTE: `getValueByPath` is available in versions \u003e= 4.5.5\n\n```js\nconst myPolicy = {\n    grants: [\n        {\n            role: 'editor/news',\n            resource: 'article',\n            action: 'approve',\n            attributes: ['*'],\n            // Mix core with custom conditions\n            condition: {\n                Fn: 'AND',\n                args: [\n                    {\n                        Fn: 'custom:categoryMatcher',\n                        args: { type: 'news' }\n                    },\n                    {\n                        Fn: 'custom:isResourceOwner',\n                        args: { resource: 'article' }\n                    }\n                ]\n            }\n        },\n    ],\n    myConditions: {\n        categoryMatcher: (context, { type } = {}) =\u003e {\n            // A naive use of the JSON path util\n            // Keep in mind it comes with performance penalties\n            return type \u0026\u0026 getValueByPath(context, '$.category.type') === type;\n        },\n        isResourceOwner: (context, { resource } = {}) =\u003e {\n            if (!resource) {\n                return false;\n            }\n            return getValueByPath(context, `$.${resource}.owner`) === getValueByPath(context, '$.user.id');\n        },\n    }\n};\nconst ac = new AccessControl(myPolicy.grants, myPolicy.myConditions);\n\n// Evaluate with article.owner equals to user.id, category.type equals to 'news'\nawait ac.can('editor/news').context({ user: { id: 1 }, article: { owner: 1 }, category: { type: 'news' } })\n    .execute('approve').on('article'); // { granted: true }\n\n// Evaluate with article.owner DOESN'T equal to user.id, category.type equals to 'news'\nawait ac.can('editor/news').context({ user: { id: 1 }, article: { owner: 2 }, category: { type: 'news' } })\n    .execute('approve').on('article');  // { granted: false }\n\n// Evaluate with article.owner equals to user.id, category.type DOESN'T equal to 'news'\nawait ac.can('editor/news').context({ user: { id: 1 }, article: { owner: 1 }, category: { type: 'tutorials' } })\n    .execute('approve').on('article');  // { granted: false }\n```\n\n### Wildcard (glob notation) Resource and Actions Examples\n```js\nac.grant({\n    role: 'politics/editor',\n    action: '*',\n    resource: 'article',\n    condition: {Fn: 'EQUALS', args: {category: 'politics'}},\n    attributes: ['*']\n});\nac.grant({\n    role: 'politics/writer',\n    action: ['*', '!publish'],\n    resource: 'article',\n    condition: {Fn: 'EQUALS', args: {category: 'politics'}},\n    attributes: ['*']\n});\n\nac.grant({\n    role: 'admin',\n    action: '*',\n    resource: '*',\n    condition: {Fn: 'EQUALS', args: {category: 'politics'}},\n    attributes: ['*']\n});\npermission = ac.can('politics/editor').execute('publish').with({category: 'politics'}).sync().on('article'); // \u003c-- Sync Example\npermission = await ac.can('politics/editor').execute('publish').with({category: 'politics'}).on('article'); // \u003c-- Async Example\nconsole(permission.attributes); // -\u003e ['*']\nconsole(permission.granted); // -\u003e true\n\npermission = ac.can('admin').execute('publish').with({category: 'politics'}).sync().on('article'); // \u003c-- Sync Example\npermission = await ac.can('admin').execute('publish').with({category: 'politics'}).on('article'); // \u003c-- Async Example\nconsole(permission.attributes); // -\u003e ['*']\nconsole(permission.granted); // -\u003e true\n\npermission = ac.can('admin').execute('publish').with({category: 'politics'}).sync().on('blog'); // \u003c-- Sync Example\npermission = await ac.can('admin').execute('publish').with({category: 'politics'}).on('blog'); // \u003c-- Async Example\nconsole(permission.attributes); // -\u003e ['*']\nconsole(permission.granted); // -\u003e true\n\npermission = ac.can('politics/writer').execute('publish').with({category: 'politics'}).sync().on('arti`cle'); // \u003c-- Sync Example\npermission = await ac.can('politics/writer').execute('publish').with({category: 'politics'}).on('arti`cle'); // \u003c-- Async Example\nconsole(permission.granted); // -\u003e false\n```\n\n### Express.js Example\n\nCheck role permissions for the requested resource and action, if granted; respond with filtered attributes.\n\n```js\nconst ac = new AccessControl(grants);\n// ...\nrouter.get('/videos/:title', function (req, res, next) {\n    const permission = ac.can(req.user.role).execute('read').on('video');\n    if (permission.granted) {\n        Video.find(req.params.title, function (err, data) {\n            if (err || !data) return res.status(404).end();\n            // filter data by permission attributes and send.\n            res.json(permission.filter(data));\n        });\n    } else {\n        // resource is forbidden for this user/role\n        res.status(403).end();\n    }\n});\n```\n\n### Roles\n\nYou can create/define roles simply by calling `.grant(\u003crole\u003e)` method on an `AccessControl` instance.  \n\nRoles can extend other roles.\n\n```js\n// user role inherits viewer role permissions\nac.grant('user').extend('viewer');\n// admin role inherits both user and editor role permissions\nac.grant('admin').extend(['user', 'editor']);\n// both admin and superadmin roles inherit moderator permissions\nac.grant(['admin', 'superadmin']).extend('moderator');\n```\n\n### Actions and Action-Attributes\n\n```js\nac.grant('editor').execute('publish').on('article');\nlet permission = ac.can('editor').execute('publish').sync().on('article'); // \u003c-- Sync Example\nlet permission = await ac.can('editor').execute('publish').on('article'); // \u003c-- Async Example\nconsole(permission.attributes); // —\u003e ['*'] (all attributes)\nconsole(permission.granted); // -\u003e true\n\nac.grant('sports/editor').execute('publish').when({Fn: 'EQUALS', args: {category: 'sports'}}).on('article');\npermission = ac.can('sports/editor').execute('publish').with({category: 'sports'}).sync().on('article'); // \u003c-- Sync Example\npermission = await ac.can('sports/editor').execute('publish').with({category: 'sports'}).on('article'); // \u003c-- Async Example\nconsole(permission.attributes); // —\u003e ['*'] (all attributes)\nconsole(permission.granted); // -\u003e true\n\npermission = ac.can('sports/editor').execute('publish').with({category: 'politics'})).sync().on('article'); // \u003c-- Sync Example\npermission = await ac.can('sports/editor').execute('publish').with({category: 'politics'})).on('article'); // \u003c-- Async Example\nconsole(permission.attributes); // -\u003e []\nconsole(permission.granted); // -\u003e false\n```\n\n### Resources and Resource-Attributes\n\nMultiple 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.  \n\nThis is possible by resource attributes. You can use Glob notation to define allowed or denied attributes.\n\nFor example, we have a `video` resource that has the following attributes: `id`, `title` and `runtime`.\nAll attributes of *any* `video` resource can be read by an `admin` role:\n```js\nac.grant('admin').execute('read').on('video', ['*']);\n// equivalent to:\n// ac.grant('admin').execute('read').on('video');\n```\nBut the `id` attribute should not be read by a `user` role.  \n```js\nac.grant('user').execute('read').on('video', ['*', '!id']);\n// equivalent to:\n// ac.grant('user').execute('read').on('video', ['title', 'runtime']);\n```\n\nYou can also use nested objects (attributes).\n```js\nac.grant('user').execute('read').on('account', ['*', '!record.id']);\n```\n\n### Checking Permissions and Filtering Attributes\n\nYou can call `.can(\u003crole\u003e).\u003caction\u003e(\u003cresource\u003e)` on an `AccessControl` instance to check for granted permissions for a specific resource and action.\n\n```js\nconst permission = ac.can('user').execute('read').on('account');\npermission.granted;       // true\npermission.attributes;    // ['*', '!record.id']\npermission.filter(data);  // filtered data (without record.id)\n```\nSee [express.js example](#expressjs-example).\n\n### Defining All Grants at Once\n\nYou can pass the grants directly to the `AccessControl` constructor.\nIt accepts either an `Object`:\n\n```js\n// This is actually how the grants are maintained internally.\nlet grantsObject = {\n    admin: {\n        grants: [\n            {\n                resource: 'video', action: '*', attributes: ['*']\n            }\n        ]\n    },\n    user: {\n        grants: [\n            {\n                resource: 'video', action: 'create', attributes: ['*']\n            },\n            {\n                resource: 'video', action: 'read', attributes: ['*']\n            },\n            {\n                resource: 'video', action: 'update', attributes: ['*']\n            },\n            {\n                resource: 'video', action: 'delete', attributes: ['*']\n            },\n        ]\n    },\n    \"sports/editor\": {\n        grants: [\n            {\n                resource: 'article',\n                action: '*',\n                attributes: [\"*\"],\n                condition: {\n                    Fn: 'EQUALS',\n                    args: {\n                        'category': 'sports'\n                    }\n                }\n            }   \n        ] \n    },\n    \"sports/writer\": {\n        grants: [\n            {\n                resource: 'article',\n                action: ['create', 'update'],\n                attributes: [\"*\", \"!status\"],\n                condition: {\n                    Fn: 'EQUALS',\n                    args: {\n                        'category': 'sports'\n                    }\n                }\n            }   \n        ] \n    }\n};\n\nconst ac = new AccessControl(grantsObject);\n```\n... or an `Array` (useful when fetched from a database):\n```js\n// grant list fetched from Database (to be converted to a valid grants object, internally)\nlet grantList = [\n    { role: 'admin', resource: 'video', action: 'create', attributes: ['*'] },\n    { role: 'admin', resource: 'video', action: 'read', attributes: ['*'] },\n    { role: 'admin', resource: 'video', action: 'update', attributes: ['*'] },\n    { role: 'admin', resource: 'video', action: 'delete', attributes: ['*'] },\n\n    { role: 'user', resource: 'video', action: 'create', attributes: ['*'] },\n    { role: 'user', resource: 'video', action: 'read', attributes: ['*'] },\n    { role: 'user', resource: 'video', action: 'update', attributes: ['*'] },\n    { role: 'user', resource: 'video', action: 'delete', attributes: ['*'] },\n    { role: 'user', resource: 'photo', action: '*', attributes: ['*'] },\n    { role: 'user', resource: 'article', action: ['*', '!delete'], attributes: ['*'] },\n    { role: 'sports/editor', resource: 'article', action: 'create', attributes: ['*'],\n      condition: { \"Fn\": \"EQUALS\", \"args\": { \"category\": \"sports\" } }\n    },\n    {\n        role: 'sports/editor', resource: 'article', action: 'update', attributes: ['*'],\n        condition: { \"Fn\": \"EQUALS\", \"args\": { \"category\": \"sports\" } }\n    }\n];\nconst ac = new AccessControl(grantList);\n```\nYou can set/get grants any time:\n```js\nconst ac = new AccessControl();\nac.setGrants(grantsObject);\nconsole.log(ac.getGrants());\n// You can save ac.getGrants() to Database\n// Please note: User should be part of your code and wraps calls to User to table/collection.\nawait User.save({permissions: acl.toJSON()}); \n// Retrieve from DB\nconst perms = await User.getBydId(userId);\nac = AccessControl.fromJSON(user.permissions);\n\n// if your DB supports storing JSON natively then you can use following code.\nawait User.save({permissions: acl.getGrants()}); \n// Retrieve from DB\nconst perms = await User.getBydId(userId);\nac.setGrants(user.permissions);\n```\n\n### Extending Roles\n```js\nconst ac = new AccessControl();\nconst editorGrant = {\n    role: 'editor',\n    resource: 'post',\n    action: 'create', // action\n    attributes: ['*'] // grant only\n};\nac.grant(editorGrant);\n// first level of extension (extending with condition)\nac.extendRole('sports/editor', 'editor', {Fn: 'EQUALS', args: {category: 'sports'}});\nac.extendRole('politics/editor', 'editor', {Fn: 'EQUALS', args: {category: 'politics'}}); \n\n\nlet permission = ac.can('sports/editor').context({category: 'sports'}).execute('create').sync().on('post'); // \u003c-- Sync Example\nlet permission = await ac.can('sports/editor').context({category: 'sports'}).execute('create').on('post'); // \u003c-- Async Example\nconsole.log(permission.granted);    // —\u003e true\nconsole.log(permission.attributes); // —\u003e ['*']\n\npermission = ac.can('sports/editor').context({category: 'politics'}).execute('create').sync().on('post'); // \u003c-- Sync Example\npermission = await ac.can('sports/editor').context({category: 'politics'}).execute('create').on('post'); // \u003c-- Async Example\nconsole.log(permission.granted);    // —\u003e false\nconsole.log(permission.attributes); // —\u003e []\n\n// second level of extension (extending without condition)\nac.extendRole('sports-and-politics/editor', ['sports/editor', 'politics/editor']);\npermission = ac.can('sports-and-politics/editor').context({category: 'politics'}).execute('create').sync().on('post'); // \u003c-- Sync Example\npermission = await ac.can('sports-and-politics/editor').context({category: 'politics'}).execute('create').on('post'); // \u003c-- Async Example\nconsole.log(permission.granted);    // —\u003e true\nconsole.log(permission.attributes); // —\u003e ['*']\n\n// third level of extension (extending with condition)\nac.extendRole('conditional/sports-and-politics/editor', 'sports-and-politics/editor', {\n    Fn: 'EQUALS',\n    args: { status: 'draft' }\n}); // \u003c-- Async Example\n\npermission = ac.can('conditional/sports-and-politics/editor').context({category: 'politics', status: 'draft'}).execute('create').sync().on('post'); // \u003c-- Sync Example\npermission = await ac.can('conditional/sports-and-politics/editor').context({category: 'politics', status: 'draft'}).execute('create').on('post'); // \u003c-- Async Example\nconsole.log(permission.granted);    // —\u003e true\nconsole.log(permission.attributes); // —\u003e ['*']\n\npermission = ac.can('conditional/sports-and-politics/editor').context({category: 'politics', status: 'published'}).execute('create').sync().on('post'); // \u003c-- Sync Example\npermission = await ac.can('conditional/sports-and-politics/editor').context({category: 'politics', status: 'published'}).execute('create').on('post'); // \u003c-- Async Example\nconsole.log(permission.granted);    // —\u003e false\nconsole.log(permission.attributes); // —\u003e []\n```\n\n### Allowed Resources and actions\n```js\nconst ac = new AccessControl();\nac.grant('user').condition({Fn: 'EQUALS', args: {category: 'sports'}}).execute('create').on('article');\nac.grant('user').execute('*').on('image');\nac.extendRole('admin', 'user');\n\nac.grant('admin').execute('delete').on('article');        \nac.grant('admin').execute('*').on('category');\nac.extendRole('owner', 'admin'); // \u003c-- Sync Example\n\nac.grant('owner').execute('*').on('video');\n\nconsole.log(ac.allowedResourcesSync({role: 'user'}).sort()); // -\u003e ['article', 'image'] \nconsole.log(await ac.allowedResources({role: 'user'}).sort()); // -\u003e ['article', 'image'] \nconsole.log(ac.allowedResourcesSync({role: 'user', context: {category: 'politics'}}).sort()); // -\u003e ['image']      \nconsole.log(await ac.allowedResources({role: 'user', context: {category: 'politics'}}).sort()); // -\u003e ['image']\nconsole.log(ac.allowedResourcesSync({role: 'admin'}).sort()); // -\u003e ['article', 'category', 'image']\nconsole.log(await ac.allowedResources({role: 'admin'}).sort()); // -\u003e ['article', 'category', 'image']\nconsole.log(ac.allowedResourcesSync({role: 'owner'}).sort()); // -\u003e ['article', 'category', 'image', 'video']\nconsole.log(await ac.allowedResources({role: 'owner'}).sort()); // -\u003e ['article', 'category', 'image', 'video']\nconsole.log(ac.allowedResourcesSync({role: ['admin', 'owner']}).sort()); // -\u003e ['article', 'category', 'image', 'video']\nconsole.log(await ac.allowedResources({role: ['admin', 'owner']}).sort()); // -\u003e ['article', 'category', 'image', 'video']\n\nconsole.log(ac.allowedActionsSync({role: 'user', resource: 'article'}).sort()); // -\u003e ['create']\nconsole.log(await ac.allowedActions({role: 'user', resource: 'article'}).sort()); // -\u003e ['create']\nconsole.log(ac.allowedActionsSync({role: 'user', resource: 'article', context: {category: 'politics'}})); // -\u003e []        \nconsole.log(await ac.allowedActions({role: 'user', resource: 'article', context: {category: 'politics'}})); // -\u003e []        \nconsole.log(ac.allowedActionsSync({role: ['admin', 'user'], resource: 'article'}).sort()); // -\u003e ['create', 'delete']\nconsole.log(await ac.allowedActions({role: ['admin', 'user'], resource: 'article'}).sort()); // -\u003e ['create', 'delete']\nconsole.log(ac.allowedActionsSync({role: 'admin', resource: 'category'}).sort()); // -\u003e ['*']\nconsole.log(await ac.allowedActions({role: 'admin', resource: 'category'}).sort()); // -\u003e ['*']\nconsole.log(ac.allowedActionsSync({role: 'owner', resource: 'video'}).sort()); // -\u003e ['*']\nconsole.log(await ac.allowedActions({role: 'owner', resource: 'video'}).sort()); // -\u003e ['*']\n\n```\n**NOTE:**  allowedResources and allowedActions skip the conditions when context is not passed\n\n### Example for versions \u003e= 4.0.0\n[Take a look at the test cases][tests]\n\n## Upgrading to \u003e= 4.0.0\n* There are many breaking changes so please update the code accordingly.\n* All future updates and bug fixes will happen only to versions \u003e= 4.\n* New features only available in \u003e= 4\n  * Storing and retrieving of custom condition functions.\n  * Promise based conditional functions.\n  * For Sync use cases use function with Sync suffix.\n\n## Licenses\n\n* [role-acl][this]: [MIT][license].\n* [AccessControl][onury-accesscontrol]: [MIT][onury-accesscontrol-license].\n\n[rbac]:https://en.wikipedia.org/wiki/Role-based_access_control\n[abac]:https://en.wikipedia.org/wiki/Attribute-Based_Access_Control\n[crud]:https://en.wikipedia.org/wiki/Create,_read,_update_and_delete\n[nist-paper]:http://csrc.nist.gov/groups/SNS/rbac/documents/kuhn-coyne-weil-10.pdf\n[this]:https://github.com/tensult/role-acl\n[onury-accesscontrol]: https://github.com/onury/accesscontrol\n[license]:https://github.com/tensult/role-acl/blob/master/LICENSE\n[onury-accesscontrol-license]:https://github.com/onury/accesscontrol/blob/master/LICENSE\n[tests]:https://github.com/tensult/role-acl/blob/master/test/acl.spec.ts\n\n## Contact us\nThis product is supported and actively developed by [Tensult](https://wwww/tensult.com). You can contact us at info@tensult.com.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ftensult%2Frole-acl","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Ftensult%2Frole-acl","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ftensult%2Frole-acl/lists"}