├── .dimerdb ├── .editorconfig ├── .gitignore ├── .npmignore ├── .travis.yml ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── LICENSE.md ├── README.md ├── dimer.json ├── docs ├── assets │ ├── favicon.png │ ├── imperium.svg │ └── logo.svg └── master │ ├── 01_introduction │ └── 01_what_is_imperium.md │ ├── 02_getting_started │ ├── 01_installation.md │ ├── 02_defining_authorizations.md │ └── 03_protecting_routes.md │ └── 03_integrations │ ├── 01_adonisjs.md │ └── 02_expressjs.md ├── package-lock.json ├── package.json ├── src ├── Door │ └── index.js ├── Role │ └── index.js └── index.js └── test └── api.js /.dimerdb: -------------------------------------------------------------------------------- 1 | {"config":{"path":"dimer.json","mtime":"2019-04-25T10:51:29.337Z","assets":["12319b7aeb8a4e9925ddf50d9ba7b7695aef0e3f.svg","55350260a54e34555c111d6dae5199a679775961.png"]},"master":{"path":"docs/master","mtime":"2019-04-25T10:51:25.185Z","assets":[]}} -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | root = true 2 | 3 | [*] 4 | indent_style = space 5 | indent_size = 2 6 | end_of_line = lf 7 | charset = utf-8 8 | trim_trailing_whitespace = true 9 | insert_final_newline = true 10 | 11 | [{package.json,*.yml}] 12 | indent_style = space 13 | indent_size = 2 14 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Dependencies 2 | node_modules 3 | 4 | # Logs 5 | npm-debug.log 6 | 7 | # Coverage 8 | coverage 9 | .nyc_output 10 | 11 | # Editors 12 | .vscode 13 | .idea 14 | -------------------------------------------------------------------------------- /.npmignore: -------------------------------------------------------------------------------- 1 | test 2 | .editorconfig 3 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: node_js 2 | node_js: 3 | - "10" 4 | install: 5 | - npm install 6 | script: 7 | - npm run test 8 | after_success: 9 | - npm run coverage 10 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation. 6 | 7 | ## Our Standards 8 | 9 | Examples of behavior that contributes to creating a positive environment include: 10 | 11 | * Using welcoming and inclusive language 12 | * Being respectful of differing viewpoints and experiences 13 | * Gracefully accepting constructive criticism 14 | * Focusing on what is best for the community 15 | * Showing empathy towards other community members 16 | 17 | Examples of unacceptable behavior by participants include: 18 | 19 | * The use of sexualized language or imagery and unwelcome sexual attention or advances 20 | * Trolling, insulting/derogatory comments, and personal or political attacks 21 | * Public or private harassment 22 | * Publishing others' private information, such as a physical or electronic address, without explicit permission 23 | * Other conduct which could reasonably be considered inappropriate in a professional setting 24 | 25 | ## Our Responsibilities 26 | 27 | Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. 28 | 29 | Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. 30 | 31 | ## Scope 32 | 33 | This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers. 34 | 35 | ## Enforcement 36 | 37 | Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at team@terrajs.org. The project team will review and investigate all complaints, and will respond in a way that it deems appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately. 38 | 39 | Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership. 40 | 41 | ## Attribution 42 | 43 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version] 44 | 45 | [homepage]: http://contributor-covenant.org 46 | [version]: http://contributor-covenant.org/version/1/4/ 47 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing to Imperium 2 | 3 | 1. [Fork](https://help.github.com/articles/fork-a-repo/) this repository to your own GitHub account and then [clone](https://help.github.com/articles/cloning-a-repository/) it to your local environment 4 | 2. Install the dependencies with `npm install` 5 | 3. Write your changes into `src/` 6 | 4. Add your tests into `test/` 7 | 5. Run `npm test` and make sure you have `100%` of coverage 8 | 9 | Enjoy hacking :) 10 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2018 CMTY 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |


Imperium Logo

Imperium

2 | 3 | > A role-based authorizations library for Node.js. 4 | 5 | [![npm version](https://img.shields.io/npm/v/imperium.svg)](https://www.npmjs.com/package/imperium) 6 | [![Travis](https://img.shields.io/travis/cmty/imperium/master.svg)](https://travis-ci.org/cmty/imperium) 7 | [![Coverage](https://img.shields.io/codecov/c/github/cmty/imperium/master.svg)](https://codecov.io/gh/cmty/imperium) 8 | [![license](https://img.shields.io/github/license/cmty/imperium.svg)](https://github.com/cmty/imperium/blob/master/LICENSE.md) 9 | 10 | ## Documentation 11 | 12 | [http://imperium.dimerapp.com](http://imperium.dimerapp.com) 13 | 14 | ## Getting Started 15 | 16 | ```bash 17 | npm install --save imperium 18 | ``` 19 | 20 | Learn more in the [docs](http://imperium.dimerapp.com/docs/master/installation). 21 | 22 | ## License 23 | 24 | [MIT](https://github.com/cmty/imperium/blob/master/LICENSE.md) 25 | -------------------------------------------------------------------------------- /dimer.json: -------------------------------------------------------------------------------- 1 | { 2 | "subdomain": "imperium", 3 | "cname": "", 4 | "defaultVersion": "master", 5 | "versions": { 6 | "master": "docs/master" 7 | }, 8 | "theme": "default", 9 | "themeSettings": { 10 | "headerBg": "#FFFFFF", 11 | "logoUrl": "./docs/assets/logo.svg", 12 | "favUrl": "./docs/assets/favicon.png", 13 | "navbar": { 14 | "Community": { 15 | "Github": "https://github.com/cmty/imperium" 16 | } 17 | } 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /docs/assets/favicon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/benjamincanac/imperium/b114b88573a65eea1ccc4a84144511d278be4e17/docs/assets/favicon.png -------------------------------------------------------------------------------- /docs/assets/imperium.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | imperium 5 | Created with Sketch. 6 | 7 | 8 | 9 | 10 | 11 | IMPERIUM 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | -------------------------------------------------------------------------------- /docs/assets/logo.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | imperium-logo 5 | Created with Sketch. 6 | 7 | 8 | 22 | 23 | -------------------------------------------------------------------------------- /docs/master/01_introduction/01_what_is_imperium.md: -------------------------------------------------------------------------------- 1 | --- 2 | permalink: index 3 | category: Introduction 4 | title: What is Imperium? 5 | --- 6 | 7 | Imperium is a role-based authorizations library for Node.js. 8 | 9 | ## Introduction 10 | 11 | Node.js REST APIs often need to control what users can do. Imperium help developers to build complex role-based APIs in seconds. 12 | 13 | [note] 14 | Imperium doesn't depend on any framework or database, so you can plug it in any existing Node.js application. 15 | [/note] 16 | 17 | ## Code 18 | 19 | Checkout our [GitHub](https://github.com/cmty/imperium) to see Imperium source code. 20 | -------------------------------------------------------------------------------- /docs/master/02_getting_started/01_installation.md: -------------------------------------------------------------------------------- 1 | --- 2 | permalink: installation 3 | category: Getting Started 4 | title: Installation 5 | --- 6 | 7 | ## Requirements 8 | 9 | You need [Node.js](https://nodejs.org/) 8.0 or greater since it uses native `async`/`await`. 10 | 11 | ## Installation 12 | 13 | ```bash 14 | npm install --save imperium 15 | ``` 16 | 17 | That's all you need to do to use Imperium. You can now learn how to define your acls [here](/docs/master/defining-authorizations). 18 | -------------------------------------------------------------------------------- /docs/master/02_getting_started/02_defining_authorizations.md: -------------------------------------------------------------------------------- 1 | --- 2 | permalink: defining-authorizations 3 | category: Getting Started 4 | title: Defining Authorizations 5 | --- 6 | 7 | ## Usage 8 | 9 | ```js 10 | const imperium = require('imperium') 11 | ``` 12 | 13 | ## Roles 14 | 15 | Define the different roles of your applications. 16 | 17 | Use `imperium.role('...', (ctx) => {})` to create a role. 18 | 19 | The function will be used to determine if your user has the role (it can be `asynchronous` by returning a `Promise`). 20 | 21 | This function needs to return: 22 | 23 | - a `boolean` (`true` if user has the corresponding role, otherwise `false`) 24 | - an `object` to compare against route actions 25 | - an `array` of objects, in this case at least one needs to match 26 | 27 | ```js 28 | imperium.role('admin', async ({ session }) => { 29 | return session.role === 'admin' 30 | }) 31 | 32 | imperium.role('user', async ({ session }) => { 33 | return { user: session.user.id } 34 | }) 35 | 36 | imperium.role('author', async ({ session }) => { 37 | // Fetch posts from DB which belongs to current session 38 | const posts = await Posts.find({ author_id: session.user.id }) 39 | // Returns an array of posts 40 | return posts.map((post) => ({ post: post.id })) 41 | }) 42 | ``` 43 | 44 | When returning an `object` or an `array`, the keys will be compared against user actions params. 45 | 46 | ## Actions 47 | 48 | Use `imperium.role('...')` to get a role, and use `can` or `is` methods to give actions or inherit from another role. 49 | 50 | ### `can(actionName, [params])` 51 | 52 | Define a user action with its params to match against. 53 | 54 | ```js 55 | imperium.role('user') 56 | .can('seeUser', { user: '@' }) 57 | .can('manageUser', { user: '@' }) // '@' means itself 58 | ``` 59 | 60 | ### `is(roleName, [params])` 61 | 62 | Inherit role's actions and overwrite its params. 63 | 64 | ```js 65 | imperium.role('admin') 66 | .is('user', { user: '*' }) // '*' means all, so admin can see and manage all users 67 | ``` 68 | 69 | Once your ACLs are defined, you can learn how to protect your routes [here](/docs/master/protecting-routes). 70 | -------------------------------------------------------------------------------- /docs/master/02_getting_started/03_protecting_routes.md: -------------------------------------------------------------------------------- 1 | --- 2 | permalink: protecting-routes 3 | category: Getting Started 4 | title: Protecting Routes 5 | --- 6 | 7 | ## Door 8 | 9 | In order to protect your route, you need to get an instance of `ImperiumDoor` with the context of the current route by using the `door` method: 10 | 11 | Example with an Express middleware: 12 | 13 | ```js 14 | const imperium = require('imperium') 15 | 16 | function (req, res, next) { 17 | req.imperium = imperium.door(req) 18 | 19 | next() 20 | } 21 | ``` 22 | 23 | The context passed to the door, in our example `req`, will be used to process the role functions defined earlier. 24 | 25 | Once your door is created you can use the `can` and `is` methods to validate your route: 26 | 27 | ### `can(actionName, [params])` 28 | 29 | Check if a user can do this action. 30 | 31 | Example with an Express controller: 32 | 33 | ```js 34 | function (req, res, next) { 35 | if (req.imperium.cannot('seeUser', { user: req.params.userId })) throw ... 36 | } 37 | ``` 38 | 39 | ### `cannot(actionName, [params])` 40 | 41 | Inverse of `can` method, it can be used to ensure that your code is affirmative. 42 | 43 | ### `is(roleName)` 44 | 45 | Check if a user has the role. 46 | 47 | Example with an Express controller: 48 | 49 | ```js 50 | function (req, res, next) { 51 | if (req.imperium.isnot('admin')) throw ... 52 | } 53 | ``` 54 | 55 | ### `isnot(roleName)` 56 | 57 | Inverse of `is` method, it can be used to ensure that your code is affirmative. 58 | -------------------------------------------------------------------------------- /docs/master/03_integrations/01_adonisjs.md: -------------------------------------------------------------------------------- 1 | --- 2 | permalink: adonisjs 3 | category: Integrations 4 | title: AdonisJs 5 | --- 6 | 7 | [AdonisJs](https://adonisjs.com) is a Node.js web framework with a breath of fresh air and drizzle of elegant syntax on top of it. 8 | 9 | ## Getting Started 10 | 11 | Install the package using the `adonis` CLI. 12 | 13 | ```bash 14 | > adonis install adonis-imperium 15 | ``` 16 | 17 | Follow instructions that are displayed ([or read them here](https://github.com/cmty/adonis-imperium/blob/master/instructions.md)). 18 | 19 | ## Defining your authorization 20 | 21 | Authorization must be defined inside the `start/acl.js` file. This file will be loaded only once when the server is launched. 22 | 23 | ### Roles 24 | 25 | The documentation is available [here](/docs/master/defining-authorizations#roles). 26 | 27 | Example: 28 | 29 | ```js 30 | const Imperium = use('Imperium') 31 | 32 | const Post = use('App/Models/Post') 33 | 34 | Imperium.role('Admin', ({ auth }) => { 35 | return auth.user.role === 'admin' 36 | }) 37 | 38 | Imperium.role('Author', async ({ auth }) => { 39 | const posts = await Post.query() 40 | .where('author_id', auth.user.id) 41 | .fetch() 42 | 43 | return posts.toJSON().map((post) => ({ post: post.id })) 44 | }) 45 | 46 | Imperium.role('User', async ({ auth }) => { 47 | return { user: auth.user.id } 48 | }) 49 | ``` 50 | 51 | ### Actions 52 | 53 | The documentation is available [here](/docs/master/defining-authorizations#actions). 54 | 55 | Example: 56 | 57 | ```js 58 | Imperium.role('User') 59 | .can('seeUser', { user: '@' }) 60 | 61 | Imperium.role('Admin') 62 | .is('User', { user: '*' }) 63 | ``` 64 | 65 | ## Protecting your routes 66 | 67 | Adonis Imperium automaticaly share an `imperium` instance in the context of each request with the `ImperiumInit` middleware. 68 | 69 | To validate the authorization of a user you simply need to extract it from the context. 70 | 71 | ```js 72 | // Controller 73 | async show ({ imperium, params }) { 74 | const post = await Post.find(params.id) 75 | 76 | const can = await imperium.can('showPost', { post: params.id }) 77 | 78 | if (!can) { 79 | // abort 401 80 | } 81 | } 82 | ``` 83 | 84 | ```js 85 | // RouteValidator 86 | async authorize () { 87 | const { imperium, params } = this.ctx 88 | 89 | const can = await imperium.can('showPost', { post: params.id }) 90 | 91 | if (!can) { 92 | // abort 401 93 | } 94 | } 95 | ``` 96 | 97 | ### Middleware 98 | 99 | You can also use the middlewares `is` and `can` in your routes. 100 | 101 | ```js 102 | Route.put('/posts/:id', 'PostController.update') 103 | .middleware(['auth', 'can:updatePost']) 104 | 105 | Route.delete('/posts/:id', 'PostController.destroy') 106 | .middleware(['auth', 'is:Admin']) 107 | ``` 108 | 109 | You can also use Adonis resources: 110 | 111 | ```js 112 | Route.resource('posts', 'PostController') 113 | .only(['index', 'show', 'store', 'update', 'destroy']) // .apiOnly() 114 | .middleware(new Map([ 115 | [['store', 'update', 'destroy'], ['auth']], 116 | [['store'], ['can:storePost']], 117 | [['update'], ['can:updatePost']], 118 | [['destroy'], ['is:Admin']] 119 | ])) 120 | .validator(new Map([ 121 | [['store'], ['StorePost']], 122 | [['update'], ['UpdatePost']] 123 | ])) 124 | ``` 125 | 126 | ### Config 127 | 128 | In order to configure how the `can` middleware will process the route context (like in validators or controllers) you can define functions in `config/acl.js`: 129 | 130 | ```js 131 | module.exports = { 132 | updatePost: ({ params }) => ({ post: params.id }), 133 | destroyPost: ({ params }) => ({ post: params.id }), 134 | storePost: ({ params, request }) => { 135 | const { type } = request.post() 136 | 137 | return { 138 | type 139 | } 140 | } 141 | } 142 | ``` 143 | -------------------------------------------------------------------------------- /docs/master/03_integrations/02_expressjs.md: -------------------------------------------------------------------------------- 1 | --- 2 | permalink: expressjs 3 | category: Integrations 4 | title: Express.js 5 | --- 6 | 7 | [Express](http://expressjs.com/) is a minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications. 8 | 9 | > Integration coming soon 10 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "imperium", 3 | "version": "3.1.1", 4 | "description": "Imperium is a role-based user's authorizations (ACL) library for Node.js.", 5 | "main": "src/index.js", 6 | "files": [ 7 | "src" 8 | ], 9 | "nyc": { 10 | "include": [ 11 | "src/" 12 | ] 13 | }, 14 | "scripts": { 15 | "lint": "standard src/**", 16 | "test": "npm run lint && nyc ava --verbose --serial --fail-fast test/ && nyc report --reporter=html", 17 | "test:watch": "ava --watch test/", 18 | "coverage": "nyc report --reporter=text-lcov > coverage.lcov && codecov", 19 | "preversion": "npm test" 20 | }, 21 | "contributors": [ 22 | { 23 | "name": "Benjamin Canac (@benjamincanac)" 24 | }, 25 | { 26 | "name": "Sebastien Chopin (@Atinux)" 27 | } 28 | ], 29 | "license": "MIT", 30 | "repository": { 31 | "type": "git", 32 | "url": "git+https://github.com/terrajs/imperium" 33 | }, 34 | "keywords": [ 35 | "node acl", 36 | "acl", 37 | "auth", 38 | "authorization", 39 | "user acl", 40 | "security", 41 | "imperium" 42 | ], 43 | "dependencies": { 44 | "lodash": "^4.17.11" 45 | }, 46 | "devDependencies": { 47 | "ava": "0.25.0", 48 | "codecov": "3.1.0", 49 | "nyc": "13.0.1", 50 | "rimraf": "2.6.2", 51 | "standard": "12.0.1", 52 | "std-mocks": "1.0.1" 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /src/Door/index.js: -------------------------------------------------------------------------------- 1 | 'use strict' 2 | 3 | const { map, find, compact, forIn, chain, keys, some } = require('lodash') 4 | 5 | class ImperiumDoor { 6 | constructor (imperium, ctx) { 7 | this.imperium = imperium 8 | this.ctx = ctx 9 | } 10 | 11 | /** 12 | * Check if action matches any of user roles action 13 | * 14 | * @param name Name of the action 15 | * @param params Params of the action 16 | * 17 | * @return {boolean} 18 | */ 19 | async can (name, params) { 20 | const routeAction = { name, ...params } 21 | 22 | // Transform imperium stored roles object into an array with only matching action 23 | const roles = compact(map(this.imperium._roles, ({ process, actions }, role) => { 24 | const action = find(actions, { name }) 25 | if (!action) return null 26 | 27 | return { 28 | role, 29 | action, 30 | process 31 | } 32 | })) 33 | 34 | for (const role of roles) { 35 | /* istanbul ignore else */ 36 | if (await this._roleMatchRouteAction(role, routeAction)) return true 37 | } 38 | 39 | return false 40 | } 41 | 42 | /** 43 | * Inverse of `can` method (code should always be affirmative) 44 | * 45 | * @param name Name of the action 46 | * @param params Params of the action 47 | * 48 | * @return {boolean} 49 | */ 50 | async cannot (name, params) { 51 | return !(await this.can(name, params)) 52 | } 53 | 54 | /** 55 | * Check if user has role 56 | * 57 | * @param name Name of the role 58 | * 59 | * @return {boolean} 60 | */ 61 | async is (name, params = {}) { 62 | const role = this.imperium._roles[name] 63 | /* istanbul ignore if */ 64 | if (!role) return false 65 | 66 | const processedRole = await role.process(this.ctx) 67 | if (!processedRole) return false 68 | if (typeof processedRole === 'boolean') return processedRole 69 | 70 | const processedRoles = Array.isArray(processedRole) ? processedRole : [processedRole] 71 | 72 | return some(processedRoles, (processedRoleParams) => { 73 | return this._matchActions(processedRoleParams, params) 74 | }) 75 | } 76 | 77 | /** 78 | * Inverse of `is` method (code should always be affirmative) 79 | * 80 | * @param name Name of the role 81 | * @param params Params of the action 82 | * 83 | * @return {boolean} 84 | */ 85 | async isnot (name, params) { 86 | return !(await this.is(name, params)) 87 | } 88 | 89 | /** 90 | * Check if processed role matches route action 91 | * The role is processed using the current route context (auth) 92 | * 93 | * @private 94 | * 95 | * @param role Role to check 96 | * @param routeAction Action required by the route 97 | * 98 | * @return {boolean} 99 | */ 100 | async _roleMatchRouteAction (role, routeAction) { 101 | const processedRole = await role.process(this.ctx) 102 | if (!processedRole) return false 103 | if (typeof processedRole === 'boolean') return processedRole 104 | 105 | const processedRoles = Array.isArray(processedRole) ? processedRole : [processedRole] 106 | 107 | return some(processedRoles, (params) => { 108 | const roleAction = { name: role.action.name } 109 | 110 | forIn(role.action.params, (value, key) => { 111 | if (value === '@') roleAction[key] = params[key] 112 | else roleAction[key] = value 113 | }) 114 | 115 | return this._matchActions(roleAction, routeAction) 116 | }) 117 | } 118 | 119 | /** 120 | * Check if roleAction matches routeAction 121 | * 122 | * @private 123 | * 124 | * @param roleAction Action of the current role loop 125 | * @param routeAction Action required by the route 126 | * 127 | * @return {boolean} 128 | */ 129 | _matchActions (roleAction, routeAction) { 130 | const actionsKeys = chain(keys(routeAction)).concat(keys(roleAction)).uniq().value() 131 | 132 | for (const key of actionsKeys) { 133 | const roleActionValue = roleAction[key] 134 | const routeActionValue = routeAction[key] || '*' 135 | 136 | if (roleActionValue !== '*') { 137 | if (Array.isArray(roleActionValue)) { 138 | if (roleActionValue.indexOf(routeActionValue) === -1) return false 139 | } else if (roleActionValue !== routeActionValue) return false 140 | } 141 | } 142 | 143 | return true 144 | } 145 | } 146 | 147 | module.exports = ImperiumDoor 148 | -------------------------------------------------------------------------------- /src/Role/index.js: -------------------------------------------------------------------------------- 1 | 'use strict' 2 | 3 | const assert = require('assert') 4 | const { cloneDeep } = require('lodash') 5 | 6 | class ImperiumRole { 7 | constructor (imperium, roleName) { 8 | this.imperium = imperium 9 | this.roleName = roleName 10 | 11 | this.role = this.imperium._roles[this.roleName] 12 | 13 | assert(this.role, `Role ${this.roleName} does not exist`) 14 | } 15 | 16 | /** 17 | * Associate action to role 18 | * 19 | * @param name Name of the action 20 | * @param params Params of the action 21 | * 22 | * @return {this} Instance of ImperiumRole (in order to be chained) 23 | */ 24 | can (name, params) { 25 | params = params || {} 26 | 27 | this.role.actions.push({ name, params }) 28 | 29 | return this 30 | } 31 | 32 | /** 33 | * Associate action to role 34 | * 35 | * @param childRoleName Name of the child action to inherit from 36 | * @param params Params to override child action 37 | * 38 | * @return {this} Instance of ImperiumRole (in order to be chained) 39 | */ 40 | is (childRoleName, params) { 41 | params = params || {} 42 | 43 | const childRole = this.imperium._roles[childRoleName] 44 | 45 | assert(childRole, `Role ${childRoleName} does not exist`) 46 | 47 | this.role.actions = this.role.actions.concat(childRole.actions.slice().map((childRoleAction) => { 48 | const action = cloneDeep(childRoleAction) 49 | 50 | // Replace action params only if exists 51 | Object.keys(params).forEach((key) => { 52 | /* istanbul ignore else */ 53 | if (typeof action.params[key] !== 'undefined') action.params[key] = params[key] 54 | }) 55 | 56 | return action 57 | })) 58 | 59 | return this 60 | } 61 | } 62 | 63 | module.exports = ImperiumRole 64 | -------------------------------------------------------------------------------- /src/index.js: -------------------------------------------------------------------------------- 1 | 'use strict' 2 | 3 | const assert = require('assert') 4 | const { map } = require('lodash') 5 | 6 | const ImperiumRole = require('./Role') 7 | const ImperiumDoor = require('./Door') 8 | 9 | class Imperium { 10 | constructor () { 11 | this._roles = {} 12 | } 13 | 14 | /** 15 | * Define new role 16 | * 17 | * @param name Name of the role 18 | * @param process Function to be executed with context 19 | * 20 | * @return {ImperiumRole} Instance of ImperiumRole 21 | */ 22 | role (name, process) { 23 | // Create role if it doesn't exist already and process is defined 24 | if (!this._roles[name] && process) this._addRole(name, process) 25 | 26 | return new ImperiumRole(this, name) 27 | } 28 | 29 | /** 30 | * Create instance of ImperiumDoor 31 | * 32 | * @param ctx Adonis context 33 | * 34 | * @return {ImperiumDoor} Instance of ImperiumDoor with current route context 35 | */ 36 | door (ctx) { 37 | return new ImperiumDoor(this, ctx) 38 | } 39 | 40 | /** 41 | * Returns stored roles. 42 | * 43 | * 44 | * @return {array} 45 | */ 46 | roles () { 47 | return map(this._roles, ({ actions }, name) => ({ name, actions })) 48 | } 49 | 50 | /** 51 | * Store role in Imperium singleton 52 | * 53 | * @private 54 | * 55 | * @param name Name of the role 56 | * @param process Function to be executed with context 57 | */ 58 | _addRole (name, process) { 59 | assert(!this._roles[name], `Role ${name} already exists`) 60 | 61 | this._roles[name] = { actions: [], process } 62 | 63 | return this._roles[name] 64 | } 65 | } 66 | 67 | module.exports = Imperium 68 | -------------------------------------------------------------------------------- /test/api.js: -------------------------------------------------------------------------------- 1 | const test = require('ava') 2 | const assert = require('assert') 3 | 4 | const Imperium = require('../src') 5 | const ImperiumDoor = require('../src/Door') 6 | const ImperiumRole = require('../src/Role') 7 | 8 | test('imperium => instanceof Imperium', (t) => { 9 | const imperium = new Imperium() 10 | 11 | t.true(imperium instanceof Imperium) 12 | }) 13 | 14 | test('imperium.door => instanceof ImperiumDoor', (t) => { 15 | const imperium = new Imperium() 16 | const door = imperium.door() 17 | 18 | t.true(door instanceof ImperiumDoor) 19 | }) 20 | 21 | test('imperium.role() without function (getter) => AssertionError', (t) => { 22 | const imperium = new Imperium() 23 | 24 | const error = t.throws(() => { 25 | imperium.role('user') 26 | }, assert.AssertionError) 27 | 28 | t.is(error.message, 'Role user does not exist') 29 | }) 30 | 31 | test('imperium.role() with function (setter) => instanceof ImperiumRole', (t) => { 32 | const imperium = new Imperium() 33 | const role = imperium.role('user', () => true) 34 | 35 | t.true(role instanceof ImperiumRole) 36 | }) 37 | 38 | test('imperium.role() with function (setter) => valid object', (t) => { 39 | const imperium = new Imperium() 40 | const fn = () => true 41 | const role = imperium.role('user', fn) 42 | 43 | t.is(role.roleName, 'user') 44 | t.is(role.role.process, fn) 45 | t.deepEqual(role.role.actions, []) 46 | t.truthy(role.can) 47 | t.truthy(role.is) 48 | }) 49 | 50 | test('imperium.role() with function (setter) => valid object', (t) => { 51 | const imperium = new Imperium() 52 | const role1 = imperium.role('user', () => true) 53 | const role2 = imperium.role('user') 54 | 55 | t.deepEqual(role1, role2) 56 | }) 57 | 58 | test('imperium.role(...).can(...) add actions', (t) => { 59 | const imperium = new Imperium() 60 | const role = imperium.role('user', () => true) 61 | .can('seeUser') 62 | 63 | t.deepEqual(role.role.actions[0], { name: 'seeUser', params: {} }) 64 | }) 65 | 66 | test('imperium.role(...).is(...) inherits actions', (t) => { 67 | const imperium = new Imperium() 68 | const adminRole = imperium.role('admin', () => true) 69 | const userRole = imperium.role('user', () => true) 70 | .can('seeUser') 71 | 72 | t.deepEqual(userRole.role.actions[0], { name: 'seeUser', params: {} }) 73 | t.notDeepEqual(adminRole.role.actions[0], { name: 'seeUser', params: {} }) 74 | 75 | const role = adminRole.is('user') 76 | 77 | t.deepEqual(adminRole.role.actions[0], { name: 'seeUser', params: {} }) 78 | t.deepEqual(role, adminRole) 79 | }) 80 | 81 | test('imperium.role(...).is(...) inherits actions params', (t) => { 82 | const imperium = new Imperium() 83 | const adminRole = imperium.role('admin', () => true) 84 | const userRole = imperium.role('user', () => true) 85 | .can('seeUser', { user: '@' }) 86 | 87 | t.deepEqual(userRole.role.actions[0], { name: 'seeUser', params: { user: '@' } }) 88 | t.falsy(adminRole.role.actions[0]) 89 | 90 | const role = adminRole.is('user', { user: '*' }) 91 | 92 | t.deepEqual(adminRole.role.actions[0], { name: 'seeUser', params: { user: '*' } }) 93 | t.deepEqual(role, adminRole) 94 | }) 95 | 96 | test('imperium.role(...).is(...) with undefined role => AssertionError', (t) => { 97 | const imperium = new Imperium() 98 | const role = imperium.role('admin', () => true) 99 | 100 | const error = t.throws(() => { 101 | role.is('moderator') 102 | }, assert.AssertionError) 103 | 104 | t.is(error.message, 'Role moderator does not exist') 105 | }) 106 | 107 | test('imperium.roles() function => array of roles', (t) => { 108 | const imperium = new Imperium() 109 | 110 | imperium.role('user', () => true) 111 | .can('seeUser', { user: '@' }) 112 | imperium.role('admin', () => true) 113 | .is('user', { user: '*' }) 114 | 115 | const roles = imperium.roles() 116 | 117 | t.deepEqual(roles, [{ 118 | name: 'user', 119 | actions: [{ 120 | name: 'seeUser', 121 | params: { user: '@' } 122 | }] 123 | }, { 124 | name: 'admin', 125 | actions: [{ 126 | name: 'seeUser', 127 | params: { user: '*' } 128 | }] 129 | }]) 130 | }) 131 | 132 | test('imperium.door().is(...) with invalid role as boolean => false', async (t) => { 133 | const imperium = new Imperium() 134 | 135 | const door = imperium.door() 136 | const is = await door.is('admin') 137 | 138 | t.false(is) 139 | }) 140 | 141 | test('imperium.door().is(...) with valid role as boolean => true', async (t) => { 142 | const imperium = new Imperium() 143 | 144 | imperium.role('admin', () => true) 145 | 146 | const door = imperium.door() 147 | const is = await door.is('admin') 148 | 149 | t.true(is) 150 | }) 151 | 152 | test('imperium.door().is(...) with invalid role as boolean => false', async (t) => { 153 | const imperium = new Imperium() 154 | 155 | imperium.role('admin', () => false) 156 | 157 | const door = imperium.door() 158 | const is = await door.is('admin') 159 | 160 | t.false(is) 161 | }) 162 | 163 | test('imperium.door().is(..., ...) with invalid role as object => false', async (t) => { 164 | const imperium = new Imperium() 165 | 166 | imperium.role('author', () => ({ post: 1 })) 167 | 168 | const door = imperium.door() 169 | const is = await door.is('author', { post: 2 }) 170 | 171 | t.false(is) 172 | }) 173 | 174 | test('imperium.door().is(..., ...) with valid role as object => true', async (t) => { 175 | const imperium = new Imperium() 176 | 177 | imperium.role('author', () => ({ post: 1 })) 178 | 179 | const door = imperium.door() 180 | const is = await door.is('author', { post: 1 }) 181 | 182 | t.true(is) 183 | }) 184 | 185 | test('imperium.door().is(..., ...) as object without params => false', async (t) => { 186 | const imperium = new Imperium() 187 | 188 | imperium.role('author', () => ({ post: 1 })) 189 | 190 | const door = imperium.door() 191 | const is = await door.is('author') 192 | 193 | t.false(is) 194 | }) 195 | 196 | test('imperium.door().is(..., ...) with valid role as object with array => true', async (t) => { 197 | const imperium = new Imperium() 198 | 199 | imperium.role('author', () => ({ post: [1, 2] })) 200 | 201 | const door = imperium.door() 202 | const is = await door.is('author', { post: 2 }) 203 | 204 | t.true(is) 205 | }) 206 | 207 | test('imperium.door().is(..., ...) with invalid role as object with array => false', async (t) => { 208 | const imperium = new Imperium() 209 | 210 | imperium.role('author', () => ({ post: [1, 2] })) 211 | 212 | const door = imperium.door() 213 | const is = await door.is('author', { post: 3 }) 214 | 215 | t.false(is) 216 | }) 217 | 218 | test('imperium.door().is(..., ...) as object with array without params => false', async (t) => { 219 | const imperium = new Imperium() 220 | 221 | imperium.role('author', () => ({ post: [1, 2] })) 222 | 223 | const door = imperium.door() 224 | const is = await door.is('author') 225 | 226 | t.false(is) 227 | }) 228 | 229 | test('imperium.door().is(..., ...) with valid role as array => true', async (t) => { 230 | const imperium = new Imperium() 231 | 232 | imperium.role('author', () => ([{ post: 1 }, { post: 2 }])) 233 | 234 | const door = imperium.door() 235 | const is = await door.is('author', { post: 1 }) 236 | 237 | t.true(is) 238 | }) 239 | 240 | test('imperium.door().is(..., ...) with invalid role as array => false', async (t) => { 241 | const imperium = new Imperium() 242 | 243 | imperium.role('author', () => ([{ post: 1 }])) 244 | 245 | const door = imperium.door() 246 | const is = await door.is('author', { post: 2 }) 247 | 248 | t.false(is) 249 | }) 250 | 251 | test('imperium.door().is(..., ...) as array without params => false', async (t) => { 252 | const imperium = new Imperium() 253 | 254 | imperium.role('author', () => ([{ post: 1 }])) 255 | 256 | const door = imperium.door() 257 | const is = await door.is('author') 258 | 259 | t.false(is) 260 | }) 261 | 262 | test('imperium.door().isnot(...) with valid role => true', async (t) => { 263 | const imperium = new Imperium() 264 | 265 | imperium.role('admin', () => true) 266 | 267 | const door = imperium.door() 268 | const isnot = await door.isnot('admin') 269 | 270 | t.false(isnot) 271 | }) 272 | 273 | test('imperium.door().cannot(...) with valid action => false', async (t) => { 274 | const imperium = new Imperium() 275 | 276 | imperium.role('user', () => true) 277 | 278 | const door = imperium.door() 279 | const cannot = await door.cannot('seeUser') 280 | 281 | t.true(cannot) 282 | }) 283 | 284 | test('imperium.door().can(...) with invalid action => false', async (t) => { 285 | const imperium = new Imperium() 286 | 287 | imperium.role('admin', () => true) 288 | 289 | const door = imperium.door() 290 | const can = await door.can('seeUser') 291 | 292 | t.false(can) 293 | }) 294 | 295 | test('imperium.door().can(...) with valid action => true', async (t) => { 296 | const imperium = new Imperium() 297 | 298 | imperium.role('admin', () => true) 299 | .can('seeUser') 300 | 301 | const door = imperium.door() 302 | const can = await door.can('seeUser') 303 | 304 | t.true(can) 305 | }) 306 | 307 | test('imperium.door().can(...) with invalid process fn => false', async (t) => { 308 | const imperium = new Imperium() 309 | 310 | imperium.role('admin', () => false) 311 | .can('seeUser') 312 | 313 | const door = imperium.door() 314 | const can = await door.can('seeUser') 315 | 316 | t.false(can) 317 | }) 318 | 319 | test('imperium.door().can(...) with invalid process fn => false', async (t) => { 320 | const imperium = new Imperium() 321 | 322 | imperium.role('user', () => false) 323 | .can('seeUser', { user: '@' }) 324 | 325 | const door = imperium.door() 326 | const can = await door.can('seeUser', { user: 1 }) 327 | 328 | t.false(can) 329 | }) 330 | 331 | test('imperium.door().can(...) with valid process fn => true', async (t) => { 332 | const imperium = new Imperium() 333 | 334 | imperium.role('user', (ctx) => ({ user: ctx.user })) 335 | .can('seeUser', { user: '@' }) 336 | imperium.role('admin', () => true) 337 | .is('user', { user: '*' }) 338 | 339 | const door = imperium.door({ user: 1 }) 340 | const can = await door.can('seeUser', { user: 1 }) 341 | 342 | t.true(can) 343 | }) 344 | 345 | test('imperium.door().can(...) with process fn array => true', async (t) => { 346 | const imperium = new Imperium() 347 | 348 | imperium.role('user', () => { 349 | return [{ user: 1 }, { user: 2 }] 350 | }) 351 | .can('seeUser', { user: '@' }) 352 | 353 | const door = imperium.door() 354 | const can1 = await door.can('seeUser', { user: 1 }) 355 | const can2 = await door.can('seeUser', { user: 2 }) 356 | const can3 = await door.can('seeUser', { user: 3 }) 357 | 358 | t.true(can1) 359 | t.true(can2) 360 | t.false(can3) 361 | }) 362 | 363 | test('imperium.door().can(...) with action param * => true', async (t) => { 364 | const imperium = new Imperium() 365 | 366 | imperium.role('admin', () => true) 367 | .can('seeUser', { user: '*' }) 368 | 369 | const door = imperium.door() 370 | const can = await door.can('seeUser', { user: 1 }) 371 | 372 | t.true(can) 373 | }) 374 | 375 | test('imperium.door().can(...) with action param array => true', async (t) => { 376 | const imperium = new Imperium() 377 | 378 | imperium.role('user', () => ({ user: [1, 2] })) 379 | .can('seeUser', { user: '@' }) 380 | 381 | const door = imperium.door() 382 | const can1 = await door.can('seeUser', { user: 1 }) 383 | const can2 = await door.can('seeUser', { user: 2 }) 384 | const can3 = await door.can('seeUser', { user: 3 }) 385 | 386 | t.true(can1) 387 | t.true(can2) 388 | t.false(can3) 389 | }) 390 | 391 | test('imperium.door().can(...) with action param array => true', async (t) => { 392 | const imperium = new Imperium() 393 | 394 | imperium.role('user', () => ({ user: [1, 2] })) 395 | .can('seeUser', { user: '@', bucket: 'front' }) 396 | 397 | const door = imperium.door() 398 | const can1 = await door.can('seeUser', { user: 1, bucket: 'front' }) 399 | const can2 = await door.can('seeUser', { user: 2 }) 400 | 401 | t.true(can1) 402 | t.false(can2) 403 | }) 404 | --------------------------------------------------------------------------------