├── .gitignore ├── .npmignore ├── .travis.yml ├── README.md ├── koa-rbac.js ├── package.json └── test └── koa-rbac.test.js /.gitignore: -------------------------------------------------------------------------------- 1 | lib-cov 2 | *.seed 3 | *.log 4 | *.csv 5 | *.dat 6 | *.out 7 | *.pid 8 | *.gz 9 | 10 | npm-debug.log 11 | node_modules 12 | coverage 13 | .idea/ 14 | package-lock.json 15 | -------------------------------------------------------------------------------- /.npmignore: -------------------------------------------------------------------------------- 1 | coverage/ 2 | test/ 3 | .travis.yml -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: node_js 2 | node_js: 3 | - "7" 4 | - "8" 5 | matrix: 6 | fast_finish: true 7 | script: "npm run-script test-cov" 8 | after_script: "npm install coveralls && cat ./coverage/lcov.info | coveralls" 9 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Koa RBAC 2 | 3 | [![Build Status](https://travis-ci.org/yanickrochon/koa-rbac.svg)](https://travis-ci.org/yanickrochon/koa-rbac)[![Coverage Status](https://coveralls.io/repos/yanickrochon/koa-rbac/badge.svg?branch=master)](https://coveralls.io/r/yanickrochon/koa-rbac?branch=master) 4 | 5 | Role-Based Access Control for [Koa](https://github.com/koajs/koa) 6 | 7 | This module follows the [NIST RBAC model](http://en.wikipedia.org/wiki/NIST_RBAC_model) and offer a flexible solution to allow or restrict user operations. 8 | 9 | 10 | ## Install 11 | 12 | ``` 13 | npm install koa-rbac --save 14 | ``` 15 | 16 | 17 | ## API 18 | 19 | * **allow** *(permissions[, params[, redirect]])* - use this when specifying a rule that should only allow the current user with the given permissions. If the rule fails, the user will be redirected to the `redirectl` URL argument value, if specified, or an error `403` ("Forbidden") will be returned. 20 | * **deny** *(permissions[, params[, redirect]])* - use this when specifying a rule that should restrict the current user with the given permissions. If the rule succeed (the user is denied), it will be redirected to the `redirect` URL argument value, if specified, or an error `403` ("Forbidden") will be returned. 21 | * **check** *(objPermissions[, params[, redirect]])* - use this when specifying a combined allow/deny rule with the given permissions. The argument `objPermissions` should be an object declaring one or two keys (`'allow'` and/or `'deny'`) whose values are a set of permissions such as provided for the `allow` and `deny` methods. If the rule fails (i.e. the user is either not allowed, or denied), it will be redirected to the `redirect` URL argument value, if specified, or an error `403` ("Forbidden") will be thrown. 22 | 23 | **Note**: the argument `permissions` (and the values of the `objPermissions` object) are either a string (i.e. a comma-separated list) or an array of permission values. 24 | 25 | 26 | ## Usage 27 | 28 | ```javascript 29 | // index.js 30 | 31 | const rbac = require('koa-rbac'); 32 | const koa = require('koa'); 33 | const app = koa(); 34 | const rules = require('path/to/rules'); 35 | const options = { 36 | rbac: new rbac.RBAC({ 37 | provider: new rbac.RBAC.providers.JsonProvider(rules) 38 | }) 39 | // identity(ctx) { return ctx && ctx.user } // passes `user` to rbac-a provider 40 | // restrictionHandler(ctx, permissions, redirectUrl) { ctx.status = 403; } // manually handle restricted responses 41 | }; 42 | 43 | app.use(rbac.middleware(options)); 44 | app.use(rbac.check({ 45 | 'allow': 'update', 46 | 'deny': 'read' 47 | })); 48 | app.use(function (ctx) { 49 | ctx.body = "Allowed updating but not reading!"; 50 | }); 51 | ``` 52 | 53 | **Note**: the argument `ctx` inside the identity function is the same value as `this` inside koa's middleware functions. For example, if using a session storage, such as [`koa-session`](https://github.com/koajs/session), it can be accessed through `ctx.session`. 54 | 55 | See [rbac-a](https://www.npmjs.com/package/rbac-a) for more information. 56 | 57 | 58 | ## Contribution 59 | 60 | All contributions welcome! Every PR **must** be accompanied by their associated unit tests! 61 | 62 | 63 | ## License 64 | 65 | The MIT License (MIT) 66 | 67 | Copyright (c) 2014 Mind2Soft 68 | 69 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 70 | 71 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 72 | 73 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 74 | -------------------------------------------------------------------------------- /koa-rbac.js: -------------------------------------------------------------------------------- 1 | 2 | const RBAC = require('rbac-a'); 3 | 4 | /** 5 | Define custom error type 6 | */ 7 | class InvalidOptionException extends Error {} 8 | 9 | /** 10 | Koa middleware. 11 | 12 | Options 13 | - rbac {RBAC} (optional) the RBAC-A instance (will create one if omitted) 14 | - identify {Function} (optional) the identity function. By default, a function returning ctx.user will be used. 15 | 16 | @param options {Object} 17 | @return {Function} the middleware function 18 | */ 19 | function middleware (options) { 20 | options = options || {}; 21 | 22 | if (('rbac' in options) && !(options.rbac instanceof RBAC)) { 23 | throw new InvalidOptionException('Invalid RBAC instance'); 24 | } 25 | 26 | if (!('identity' in options)) { 27 | options.identity = defaultIdentity; 28 | } else if (typeof options.identity !== 'function') { 29 | throw new InvalidOptionException('Invalid identity function'); 30 | } 31 | 32 | if (('restrictionHandler' in options) && (typeof options.restrictionHandler !== 'function')) { 33 | throw new InvalidOptionException('Invalid restriction handler'); 34 | } 35 | 36 | return (ctx, next) => { 37 | Object.defineProperty(ctx, 'rbac', { 38 | enumerable: true, 39 | writable: false, 40 | value: Object.create(options.rbac || {}, { 41 | // current allowed priority 42 | check: { 43 | enumerable: true, 44 | writable: false, 45 | value: function (permissions, params) { 46 | return options.rbac && Promise.resolve().then(function () { 47 | return options.identity(ctx); 48 | }).then(function (user) { 49 | return user && options.rbac.check(user, permissions, params) || NaN; 50 | }) || Promise.resolve(NaN); 51 | } 52 | }, 53 | _restrict: { 54 | enumerable: false, 55 | writable: false, 56 | value: function restrict(permissions, redirectUrl) { 57 | if (options.restrictionHandler) { 58 | return options.restrictionHandler(ctx, permissions, redirectUrl); 59 | } else if (redirectUrl) { 60 | return ctx.redirect(redirectUrl); 61 | } else { 62 | ctx.status = 403; 63 | ctx.body = 'Forbidden'; 64 | } 65 | } 66 | } 67 | }) 68 | }); 69 | 70 | return next(); 71 | }; 72 | } 73 | 74 | 75 | /** 76 | Default identity function. 77 | 78 | Try to return most common used user property. 79 | 80 | @param ctx the request context 81 | @return mixed 82 | */ 83 | function defaultIdentity(ctx) { 84 | return ctx && ctx.user; 85 | } 86 | 87 | 88 | /** 89 | Return a middleware to allow only for the given permissions. 90 | 91 | @param permissions {string} the required permissions 92 | @param params {object} (optional) params sent to the RBAC-A instance 93 | @param redirectUrl {string} (optional) if not allowed, try to redirect 94 | */ 95 | function allowMiddleware(permissions, params, redirectUrl) { 96 | if (arguments.length < 3 && typeof params === 'string') { 97 | redirectUrl = params; 98 | params = undefined; 99 | } 100 | 101 | return async (ctx, next) => { 102 | const rbac = ctx.rbac; 103 | 104 | if (rbac) { 105 | const allowedPriority = await rbac.check(permissions, params); 106 | 107 | if (!allowedPriority) { 108 | return rbac._restrict(permissions, redirectUrl); 109 | } 110 | } 111 | 112 | return next(); 113 | }; 114 | } 115 | 116 | 117 | /** 118 | Return a middleware to deny any with the given permissions. 119 | 120 | @param permissions {string} the restricted permissions 121 | @param params {object} (optional) params sent to the RBAC-A instance 122 | @param redirectUrl {string} (optional) if not allowed, try to redirect 123 | */ 124 | function denyMiddleware(permissions, params, redirectUrl) { 125 | if (arguments.length < 3 && typeof params === 'string') { 126 | redirectUrl = params; 127 | params = undefined; 128 | } 129 | 130 | return async (ctx, next) => { 131 | const rbac = ctx.rbac; 132 | 133 | if (rbac) { 134 | const deniedPriority = await rbac.check(permissions, params); 135 | 136 | if (deniedPriority) { 137 | return rbac._restrict(permissions, redirectUrl); 138 | } 139 | } else { 140 | ctx.status = 403; 141 | ctx.body = 'Forbidden'; 142 | return; 143 | } 144 | 145 | return next(); 146 | }; 147 | } 148 | 149 | 150 | /** 151 | Return a middleware to allow and not deny any with the given permissions. 152 | 153 | @param permissions {object} (optional) permissions sent to the RBAC-A instance 154 | @param permissions.allowPermissions {string|Array} the required permissions 155 | @param permissions.deniedPermissions {string|Array} the restricted permissions 156 | @param params {object} (optional) params sent to the RBAC-A instance 157 | @param redirectUrl {string} (optional) if not allowed, try to redirect 158 | */ 159 | function checkMiddleware(permissions, params, redirectUrl) { 160 | if (arguments.length < 3 && typeof params === 'string') { 161 | redirectUrl = params; 162 | params = undefined; 163 | } 164 | 165 | return async (ctx, next) => { 166 | const rbac = ctx.rbac; 167 | 168 | if (rbac) { 169 | let allowedPriority; 170 | let deniedPriority; 171 | 172 | permissions = permissions || {}; 173 | 174 | if ('allow' in permissions) { 175 | allowedPriority = await rbac.check(permissions['allow'], params); 176 | } else { 177 | allowedPriority = Infinity; 178 | } 179 | 180 | if ('deny' in permissions) { 181 | deniedPriority = await rbac.check(permissions['deny'], params); 182 | } else { 183 | deniedPriority = Infinity; 184 | } 185 | 186 | if (isNaN(allowedPriority) || (!isNaN(deniedPriority) && (deniedPriority <= allowedPriority))) { 187 | return rbac._restrict(permissions, redirectUrl); 188 | } 189 | } 190 | 191 | return next(); 192 | }; 193 | } 194 | 195 | 196 | module.exports = middleware; 197 | module.exports.middleware = middleware; 198 | module.exports.allow = allowMiddleware; 199 | module.exports.deny = denyMiddleware; 200 | module.exports.check = checkMiddleware; 201 | module.exports.InvalidOptionException = InvalidOptionException; 202 | module.exports.RBAC = RBAC; 203 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "koa-rbac", 3 | "version": "2.0.1", 4 | "description": "Role-Based Acess Control for Koa 2", 5 | "author": "Yanick Rochon ", 6 | "keywords": [ 7 | "rbac", 8 | "access", 9 | "role" 10 | ], 11 | "main": "koa-rbac.js", 12 | "scripts": { 13 | "test": "jest --forceExit", 14 | "test-cov": "npm run test -- --coverage" 15 | }, 16 | "homepage": "https://github.com/yanickrochon/koa-rbac", 17 | "repository": { 18 | "type": "git", 19 | "url": "https://github.com/yanickrochon/koa-rbac.git" 20 | }, 21 | "bugs": { 22 | "url": "https://github.com/yanickrochon/koa-rbac/issues" 23 | }, 24 | "dependencies": { 25 | "rbac-a": "^0.2.5" 26 | }, 27 | "devDependencies": { 28 | "istanbul": "^0.4.5", 29 | "jest": "^20.0.1", 30 | "koa": "^2.3.0", 31 | "supertest": "^3.0.0" 32 | }, 33 | "engines": { 34 | "node": ">=7.6" 35 | }, 36 | "license": "MIT", 37 | "jest": { 38 | "testMatch": [ 39 | "**/test/**/*.js" 40 | ], 41 | "coverageReporters": [ 42 | "text-summary", 43 | "lcov" 44 | ], 45 | "bail": true, 46 | "testEnvironment": "node" 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /test/koa-rbac.test.js: -------------------------------------------------------------------------------- 1 | 2 | describe('Test RBAC', () => { 3 | 4 | const assert = require('assert'); 5 | const request = require('supertest'); 6 | const koa = require('koa'); 7 | const RBAC = require('rbac-a'); 8 | const JsonProvider = require('rbac-a/lib/providers/json'); 9 | 10 | const middleware = require('../koa-rbac'); 11 | 12 | const RULES = { 13 | roles: { 14 | 'guest': { 15 | //name: 'Guest', 16 | permissions: ['foo'] 17 | }, 18 | 'reader': { 19 | //name: 'Reader', 20 | permissions: ['read'], 21 | inherited: ['guest'] 22 | }, 23 | 'writer': { 24 | //name: 'Writer', 25 | permissions: ['create'], 26 | inherited: ['reader'] 27 | }, 28 | 'editor': { 29 | //name: 'Editor', 30 | permissions: ['update'], 31 | inherited: ['reader'] 32 | }, 33 | 'director': { 34 | //name: 'Director', 35 | permissions: ['delete'], 36 | inherited: ['editor'] 37 | }, 38 | 'admin': { 39 | //name: 'Administrator', 40 | permissions: ['manage'] 41 | }, 42 | 43 | 'cyclic1': { 44 | permissions: ['crc1'], 45 | inherited: ['cyclic2'] 46 | }, 47 | 'cyclic2': { 48 | permissions: ['crc2'], 49 | inherited: ['cyclic1'] 50 | }, 51 | 52 | 'special': { 53 | // note: no permissions 54 | } 55 | }, 56 | users: { 57 | 'bart': ['guest', 'reader'], 58 | 'marge': ['editor'], 59 | 'homer': ['admin', 'director'], 60 | 'burns': ['admin'], 61 | 'phsycho bob': ['cyclic1'], 62 | 'ralph': ['special', 'learned'] // unknown role 'learned'! 63 | } 64 | }; 65 | 66 | const MIDDLEWARE_OPTIONS = { 67 | rbac: new RBAC({ provider: new JsonProvider(RULES) }) 68 | }; 69 | 70 | 71 | function validate(useRbacMiddleware, identity, validateionMiddleware, status, accept) { 72 | const app = new koa(); 73 | 74 | if (identity) { 75 | app.use((ctx, next) => { 76 | ctx.user = identity; 77 | return next(); 78 | }); 79 | } 80 | 81 | if (useRbacMiddleware) { 82 | app.use(middleware(useRbacMiddleware)); 83 | } 84 | if (Array.isArray(validateionMiddleware)) { 85 | validateionMiddleware.forEach(middleware => app.use(middleware)); 86 | } else { 87 | app.use(validateionMiddleware); 88 | } 89 | 90 | app.use(function (ctx) { 91 | ctx.status = 200; 92 | }); 93 | 94 | const error = new Error(); 95 | 96 | return request(app.listen()) 97 | .get('/') 98 | .set('Accept', accept) 99 | .expect(status) 100 | .catch(err => { 101 | error.message = err.message; 102 | throw error; 103 | }) 104 | ; 105 | } 106 | 107 | 108 | it('should return middleware with default options', () => { 109 | assert.ok(middleware() instanceof Function, 'Middleware is not a function'); 110 | }); 111 | 112 | it('should be a valid RBAC-A instance', () => { 113 | [ 114 | undefined, null, false, true, 0, NaN, Infinity, '', 'hello', [], {}, 115 | function () {}, async function () {}, function RBAC() {}, 116 | /./, new Date() 117 | ].forEach(rbac => assert.throws(() => middleware({ rbac }), 'Did not throw with value : ' + JSON.stringify(rbac))); 118 | }); 119 | 120 | it('should be a valid identity function', () => { 121 | [ 122 | undefined, null, false, true, 0, NaN, Infinity, '', 'hello', [], {}, 123 | /./, new Date() 124 | ].forEach(identity => assert.throws(() => middleware({ identity }), 'Did not throw with value : ' + JSON.stringify(identity))); 125 | }); 126 | 127 | it('should be a valid restriction handler', () => { 128 | [ 129 | undefined, null, false, true, 0, NaN, Infinity, '', 'hello', [], {}, 130 | /./, new Date() 131 | ].forEach(restrictionHandler => assert.throws(() => middleware({ restrictionHandler }), 'Did not throw with value : ' + JSON.stringify(restrictionHandler))); 132 | }); 133 | 134 | it('should accept valid RBAC-A instance', () => { 135 | const rbac = new RBAC({ provider: new JsonProvider(RULES) }); 136 | const options = { 137 | rbac: rbac 138 | }; 139 | 140 | middleware(options); 141 | 142 | assert.strictEqual(options.rbac, rbac, 'Failed to set rbac instance'); 143 | }); 144 | 145 | it('should accept valid identity function', () => { 146 | const identity = function () {}; 147 | const options = { 148 | identity: identity 149 | }; 150 | 151 | middleware(options); 152 | 153 | assert.strictEqual(options.identity, identity, 'Failed to set identity function'); 154 | }); 155 | 156 | it('should allow / deny', () => { 157 | return Promise.all([ 158 | validate(MIDDLEWARE_OPTIONS, 'bart', middleware.allow(['read']), 200, 'text/html'), 159 | validate(MIDDLEWARE_OPTIONS, 'marge', middleware.allow(['update']), 200, 'text/html'), 160 | validate(MIDDLEWARE_OPTIONS, 'homer', middleware.allow(['create', 'update']), 200, 'text/html'), 161 | validate(MIDDLEWARE_OPTIONS, 'homer', middleware.allow('create, update'), 200, 'text/html'), 162 | validate(MIDDLEWARE_OPTIONS, 'burns', middleware.allow(['manage']), 200, 'text/html'), 163 | validate(MIDDLEWARE_OPTIONS, 'homer', middleware.allow(['foo']), 200, 'text/html'), 164 | validate(MIDDLEWARE_OPTIONS, 'burns', middleware.allow(['read']), 403, 'text/html'), 165 | validate(MIDDLEWARE_OPTIONS, 'marge', middleware.allow('read && update'), 200, 'text/html'), 166 | 167 | validate(MIDDLEWARE_OPTIONS, 'marge', middleware.allow('read && update'), 200, 'text/html'), 168 | 169 | validate(MIDDLEWARE_OPTIONS, 'bart', middleware.deny(['read']), 403, 'text/html'), 170 | validate(MIDDLEWARE_OPTIONS, 'bart', middleware.deny(['read']), 403, 'text/html'), 171 | validate(MIDDLEWARE_OPTIONS, 'burns', middleware.deny(['read', 'update']), 200, 'text/html'), 172 | validate(MIDDLEWARE_OPTIONS, 'burns', middleware.deny(['read', 'manage']), 403, 'text/html'), 173 | 174 | validate(MIDDLEWARE_OPTIONS, 'bart', middleware.check({ 'allow': 'read' }), 200, 'text/html'), 175 | validate(MIDDLEWARE_OPTIONS, 'burns', middleware.check({ 'deny': ['read', 'update'] }), 200, 'text/html'), 176 | validate(MIDDLEWARE_OPTIONS, 'burns', middleware.check({ 'deny': ['read', 'manage'] }), 403, 'text/html'), 177 | validate(MIDDLEWARE_OPTIONS, 'marge', middleware.check({ 'allow': ['update'], 'deny': ['read'] }), 200, 'text/html'), 178 | validate(MIDDLEWARE_OPTIONS, 'marge', middleware.check({ 'allow': ['manage'], 'deny': ['read'] }), 403, 'text/html'), 179 | 180 | // redirect 181 | validate(MIDDLEWARE_OPTIONS, 'bart', middleware.allow('read', '/foo'), 200, 'text/html'), 182 | validate(MIDDLEWARE_OPTIONS, 'marge', middleware.allow(['update'], {}, '/foo'), 200, 'text/html'), 183 | validate(MIDDLEWARE_OPTIONS, 'bart', middleware.allow('manage','/foo'), 302, 'text/html'), 184 | 185 | validate(MIDDLEWARE_OPTIONS, 'bart', middleware.deny(['read'], {}, '/foo'), 302, 'text/html'), 186 | validate(MIDDLEWARE_OPTIONS, 'bart', middleware.deny(['read'], '/foo'), 302, 'application/json'), 187 | validate(MIDDLEWARE_OPTIONS, 'burns', middleware.deny(['read', 'update'], null, '/foo'), 200, 'text/html'), 188 | validate(MIDDLEWARE_OPTIONS, 'bart', middleware.deny(['read'], '/foo'), 302, 'text/html'), 189 | validate(MIDDLEWARE_OPTIONS, 'bart', middleware.deny(['read'], null, '/foo'), 302, 'application/json'), 190 | validate(MIDDLEWARE_OPTIONS, 'burns', middleware.deny(['read', 'manage'], null, '/foo'), 302, 'text/html'), 191 | validate(MIDDLEWARE_OPTIONS, 'burns', middleware.deny(['read', 'manage'], null, '/foo'), 302, 'application/json'), 192 | 193 | validate(MIDDLEWARE_OPTIONS, 'marge', middleware.check({ 'allow': ['manage'], 'deny': ['read'] }, '/foo'), 302, 'text/html'), 194 | validate(MIDDLEWARE_OPTIONS, 'marge', middleware.check({ 'allow': ['manage'], 'deny': ['read'] }, {}, '/foo'), 302, 'application/json '), 195 | ]); 196 | }); 197 | 198 | 199 | it('should allow / deny if no middleware', () => { 200 | return Promise.all([ 201 | validate(false, null, middleware.allow('read'), 200, 'text/html'), 202 | validate(false, 'bart', middleware.allow(['manage']), 200, 'text/html'), 203 | validate(false, 'burns', middleware.allow(['read']), 200, 'text/html'), 204 | 205 | validate(false, null, middleware.deny(['foo']), 403, 'text/html'), 206 | validate(false, null, middleware.deny(['read']), 403, 'text/html'), 207 | validate(false, 'bart', middleware.deny(['manage']), 403, 'text/html'), 208 | validate(false, 'burns', middleware.deny(['manage']), 403, 'text/html'), 209 | 210 | validate(false, 'homer', middleware.check(), 200, 'text/html') 211 | ]); 212 | }); 213 | 214 | it('should execute restriction handler on deny', () => { 215 | const middlewareOptions = { 216 | rbac: new RBAC({ provider: new JsonProvider(RULES) }), 217 | restrictionHandler: (ctx, permissions) => { 218 | restricted.push(permissions); 219 | ctx.status = 418; 220 | } 221 | } 222 | var restricted = []; 223 | 224 | return Promise.all([ 225 | validate(middlewareOptions, 'bart', middleware.allow(['read']), 200, 'text/html'), 226 | validate(middlewareOptions, 'bart', middleware.deny(['read'], '/foo'), 418, 'application/json'), 227 | validate(middlewareOptions, 'burns', middleware.deny(['read', 'manage'], null, '/foo'), 418, 'application/json'), 228 | ]).then(() => { 229 | const expected = [ 230 | ["read"], 231 | ["read","manage"] 232 | ]; 233 | assert.deepStrictEqual(restricted, expected, 'Failed to received expected restriction : ' + JSON.stringify(restricted)); 234 | }); 235 | }); 236 | 237 | it('should ignore invalid permission values', () => { 238 | return Promise.all([ 239 | validate(MIDDLEWARE_OPTIONS, 'homer', middleware.allow('create, update'), 200, 'text/html'), 240 | validate(MIDDLEWARE_OPTIONS, 'homer', middleware.allow(['create', 'update']), 200, 'text/html'), 241 | validate(MIDDLEWARE_OPTIONS, 'homer', middleware.allow([ ['create', 'foo'], 'update']), 200, 'text/html'), 242 | 243 | validate(MIDDLEWARE_OPTIONS, 'homer', middleware.check(), 403, 'text/html') 244 | ]); 245 | }); 246 | 247 | 248 | it('should fail if no user', () => { 249 | return Promise.all([ 250 | validate(MIDDLEWARE_OPTIONS, null, middleware.allow('create, update'), 403, 'text/html') 251 | ]); 252 | }); 253 | 254 | 255 | it('should fail if no RBAC instance', () => { 256 | return Promise.all([ 257 | validate({}, 'homer', middleware.allow('create, update'), 403, 'text/html') 258 | ]); 259 | }); 260 | 261 | 262 | it('should allow validating inside a custom middlewares', () => { 263 | return Promise.all([ 264 | validate(MIDDLEWARE_OPTIONS, 'phsycho bob', [ 265 | async (ctx, next) => { 266 | const allowed = await ctx.rbac.check('crc1'); 267 | 268 | assert.strictEqual(allowed, 1, 'Failed to check crc1'); 269 | 270 | return next(); 271 | }, 272 | async (ctx, next) => { 273 | const allowed = await ctx.rbac.check('crc2'); 274 | 275 | assert.strictEqual(allowed, 2, 'Failed to check crc2'); 276 | 277 | return next(); 278 | } 279 | ], 200, 'text/html') 280 | ]); 281 | }); 282 | 283 | }); 284 | --------------------------------------------------------------------------------