├── .eslintignore ├── test ├── unit │ ├── mocha.opts │ └── adapter.test.js ├── .eslintrc.json ├── integration │ ├── mocha.opts │ └── adapter.test.js ├── fixtures │ └── basic_model.conf └── helpers │ └── createEnforcer.js ├── .editorconfig ├── .eslintrc.json ├── src ├── model.js └── adapter.js ├── .circleci └── config.yml ├── .gitignore ├── package.json ├── README.md ├── API.md └── LICENSE /.eslintignore: -------------------------------------------------------------------------------- 1 | coverage 2 | -------------------------------------------------------------------------------- /test/unit/mocha.opts: -------------------------------------------------------------------------------- 1 | ./test/unit/**/*.test.js 2 | --reporter spec 3 | --recursive 4 | --exit 5 | -------------------------------------------------------------------------------- /test/.eslintrc.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "../.eslintrc.json", 3 | "env": { 4 | "mocha": true 5 | } 6 | } 7 | -------------------------------------------------------------------------------- /test/integration/mocha.opts: -------------------------------------------------------------------------------- 1 | ./test/integration/**/*.test.js 2 | --recursive 3 | --reporter spec 4 | --timeout 2000 5 | --exit 6 | -------------------------------------------------------------------------------- /test/fixtures/basic_model.conf: -------------------------------------------------------------------------------- 1 | [request_definition] 2 | r = sub, obj, act 3 | 4 | [policy_definition] 5 | p = sub, obj, act 6 | 7 | [policy_effect] 8 | e = some(where (p.eft == allow)) 9 | 10 | [matchers] 11 | m = r.sub == p.sub && r.obj == p.obj && r.act == p.act 12 | -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | # editorconfig.org 2 | root = true 3 | 4 | [*] 5 | indent_style = space 6 | indent_size = 2 7 | end_of_line = lf 8 | charset = utf-8 9 | trim_trailing_whitespace = true 10 | insert_final_newline = true 11 | 12 | [*.md] 13 | trim_trailing_whitespace = false 14 | -------------------------------------------------------------------------------- /.eslintrc.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "standard", 3 | "rules": { 4 | "semi": [ 5 | "error", 6 | "always" 7 | ], 8 | "camelcase": [ 9 | "error", 10 | { 11 | "allow": [ 12 | "p_type" 13 | ] 14 | } 15 | ] 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /test/helpers/createEnforcer.js: -------------------------------------------------------------------------------- 1 | const path = require('path'); 2 | const { newEnforcer } = require('casbin'); 3 | const MongooseAdapter = require('../..'); 4 | 5 | const MONGOOSE_OPTIONS = { useNewUrlParser: true, useCreateIndex: true }; 6 | 7 | module.exports = async function createEnforcer () { 8 | const model = path.resolve(__dirname, '../fixtures/basic_model.conf'); 9 | const adapter = await MongooseAdapter.newAdapter('mongodb://localhost:27017/casbin', MONGOOSE_OPTIONS); 10 | 11 | return newEnforcer(model, adapter); 12 | }; 13 | -------------------------------------------------------------------------------- /src/model.js: -------------------------------------------------------------------------------- 1 | const { Schema } = require('mongoose'); 2 | const mongoose = require('mongoose'); 3 | 4 | const schema = new Schema({ 5 | p_type: { 6 | type: Schema.Types.String, 7 | required: true, 8 | index: true 9 | }, 10 | v0: { 11 | type: Schema.Types.String, 12 | index: true 13 | }, 14 | v1: { 15 | type: Schema.Types.String, 16 | index: true 17 | }, 18 | v2: { 19 | type: Schema.Types.String, 20 | index: true 21 | }, 22 | v3: { 23 | type: Schema.Types.String, 24 | index: true 25 | }, 26 | v4: { 27 | type: Schema.Types.String, 28 | index: true 29 | }, 30 | v5: { 31 | type: Schema.Types.String, 32 | index: true 33 | } 34 | }, { collection: 'casbin_rule', minimize: false, timestamps: false }); 35 | 36 | module.exports = mongoose.model('CasbinRule', schema, 'casbin_rule'); 37 | -------------------------------------------------------------------------------- /.circleci/config.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | jobs: 3 | build: 4 | docker: 5 | - image: node:10-alpine 6 | - image: mongo:4 7 | steps: 8 | - checkout 9 | - restore_cache: 10 | key: dependency-cache-{{ checksum "package.json" }} 11 | - run: 12 | name: Installing Dependencies 13 | command: npm install 14 | - save_cache: 15 | key: dependency-cache-{{ checksum "package.json" }} 16 | paths: 17 | - node_modules 18 | - run: 19 | name: Running Lint Checks 20 | command: npm run lint 21 | - run: 22 | name: Running Unit Tests 23 | command: npm run test:unit 24 | - run: 25 | name: Running Integration Tests 26 | command: npm run test:integration 27 | workflows: 28 | version: 2 29 | build: 30 | jobs: 31 | - build 32 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | npm-debug.log* 5 | yarn-debug.log* 6 | yarn-error.log* 7 | 8 | # Runtime data 9 | pids 10 | *.pid 11 | *.seed 12 | *.pid.lock 13 | 14 | # Directory for instrumented libs generated by jscoverage/JSCover 15 | lib-cov 16 | 17 | # Coverage directory used by tools like istanbul 18 | coverage 19 | 20 | # nyc test coverage 21 | .nyc_output 22 | 23 | # Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files) 24 | .grunt 25 | 26 | # Bower dependency directory (https://bower.io/) 27 | bower_components 28 | 29 | # node-waf configuration 30 | .lock-wscript 31 | 32 | # Compiled binary addons (https://nodejs.org/api/addons.html) 33 | build/Release 34 | 35 | # Dependency directories 36 | node_modules/ 37 | jspm_packages/ 38 | 39 | # TypeScript v1 declaration files 40 | typings/ 41 | 42 | # Optional npm cache directory 43 | .npm 44 | 45 | # Optional eslint cache 46 | .eslintcache 47 | 48 | # Optional REPL history 49 | .node_repl_history 50 | 51 | # Output of 'npm pack' 52 | *.tgz 53 | 54 | # Yarn Integrity file 55 | .yarn-integrity 56 | 57 | # dotenv environment variables file 58 | .env 59 | .env.test 60 | 61 | # parcel-bundler cache (https://parceljs.org/) 62 | .cache 63 | 64 | # next.js build output 65 | .next 66 | 67 | # nuxt.js build output 68 | .nuxt 69 | 70 | # vuepress build output 71 | .vuepress/dist 72 | 73 | # Serverless directories 74 | .serverless/ 75 | 76 | # FuseBox cache 77 | .fusebox/ 78 | 79 | # DynamoDB Local files 80 | .dynamodb/ 81 | -------------------------------------------------------------------------------- /test/unit/adapter.test.js: -------------------------------------------------------------------------------- 1 | const { assert } = require('chai'); 2 | const MongooseAdapter = require('../..'); 3 | 4 | const MONGOOSE_OPTIONS = { useNewUrlParser: true, useCreateIndex: true }; 5 | 6 | describe('MongooseAdapter', () => { 7 | it('Should properly throw error if Mongo URI is not provided', async () => { 8 | assert.throws(() => new MongooseAdapter(), 'You must provide Mongo URI to connect to!'); 9 | }); 10 | 11 | it('Should properly instantiate adapter', async () => { 12 | const adapter = new MongooseAdapter('mongodb://localhost:27017/casbin', MONGOOSE_OPTIONS); 13 | 14 | assert.instanceOf(adapter, MongooseAdapter); 15 | assert.isFalse(adapter.isFiltered); 16 | }); 17 | 18 | it('Should properly create new instance via static newAdapter', async () => { 19 | const adapter = await MongooseAdapter.newAdapter('mongodb://localhost:27017/casbin', MONGOOSE_OPTIONS); 20 | 21 | assert.instanceOf(adapter, MongooseAdapter); 22 | assert.isFalse(adapter.isFiltered); 23 | }); 24 | 25 | it('Should properly create filtered instance via static newFilteredAdapter', async () => { 26 | const adapter = await MongooseAdapter.newFilteredAdapter('mongodb://localhost:27017/casbin', MONGOOSE_OPTIONS); 27 | 28 | assert.instanceOf(adapter, MongooseAdapter); 29 | assert.isTrue(adapter.isFiltered); 30 | }); 31 | 32 | it('Should have implemented interface for casbin', async () => { 33 | const adapter = new MongooseAdapter('mongodb://localhost:27017/casbin', MONGOOSE_OPTIONS); 34 | 35 | assert.isFunction(MongooseAdapter.newAdapter); 36 | assert.isFunction(MongooseAdapter.newFilteredAdapter); 37 | assert.isFunction(adapter.loadPolicyLine); 38 | assert.isFunction(adapter.loadPolicy); 39 | assert.isFunction(adapter.loadFilteredPolicy); 40 | assert.isBoolean(adapter.isFiltered); 41 | assert.isFunction(adapter.savePolicyLine); 42 | assert.isFunction(adapter.savePolicy); 43 | assert.isFunction(adapter.addPolicy); 44 | assert.isFunction(adapter.removePolicy); 45 | assert.isFunction(adapter.removeFilteredPolicy); 46 | }); 47 | }); 48 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "@elastic.io/casbin-mongoose-adapter", 3 | "version": "1.0.0", 4 | "description": "Mongoose adapter for Casbin", 5 | "main": "src/adapter.js", 6 | "license": "Apache-2.0", 7 | "homepage": "https://github.com/elasticio/casbin-mongoose-adapter#readme", 8 | "author": { 9 | "name": "elastic.io GmbH", 10 | "url": "https://elastic.io" 11 | }, 12 | "contributors": [ 13 | { 14 | "name": "Eugene Obrezkov", 15 | "email": "ghaiklor@gmail.com", 16 | "url": "https://ghaiklor.com" 17 | } 18 | ], 19 | "repository": { 20 | "type": "git", 21 | "url": "git+https://github.com/elasticio/casbin-mongoose-adapter.git" 22 | }, 23 | "bugs": { 24 | "url": "https://github.com/elasticio/casbin-mongoose-adapter/issues", 25 | "email": "dev@elastic.io" 26 | }, 27 | "keywords": [ 28 | "casbin", 29 | "node-casbin", 30 | "adapter", 31 | "mongoose", 32 | "access-control", 33 | "authorization", 34 | "auth", 35 | "authz", 36 | "acl", 37 | "rbac", 38 | "abac", 39 | "orm" 40 | ], 41 | "engines": { 42 | "node": ">=8.0.0" 43 | }, 44 | "publishConfig": { 45 | "tag": "latest", 46 | "registry": "https://registry.npmjs.org" 47 | }, 48 | "scripts": { 49 | "docs": "jsdoc2md \"src/**/*.js\" > ./API.md", 50 | "lint": "eslint .", 51 | "prepublishOnly": "npm run lint && npm run test && npm run docs", 52 | "test:integration": "isparta cover _mocha -- --opts test/integration/mocha.opts", 53 | "test:unit": "isparta cover _mocha -- --opts test/unit/mocha.opts", 54 | "test": "npm run test:unit && npm run test:integration" 55 | }, 56 | "devDependencies": { 57 | "chai": "4.2.0", 58 | "eslint": "5.12.0", 59 | "eslint-config-standard": "12.0.0", 60 | "eslint-plugin-import": "2.14.0", 61 | "eslint-plugin-node": "8.0.1", 62 | "eslint-plugin-promise": "4.0.1", 63 | "eslint-plugin-standard": "4.0.0", 64 | "husky": "1.3.1", 65 | "isparta": "4.1.1", 66 | "jsdoc-to-markdown": "4.0.1", 67 | "mocha": "5.2.0" 68 | }, 69 | "dependencies": { 70 | "casbin": "2.0.0", 71 | "mongoose": "5.4.2" 72 | }, 73 | "husky": { 74 | "hooks": { 75 | "pre-commit": "npm run lint" 76 | } 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /test/integration/adapter.test.js: -------------------------------------------------------------------------------- 1 | const { assert } = require('chai'); 2 | const createEnforcer = require('../helpers/createEnforcer'); 3 | const CasbinRule = require('../../src/model'); 4 | 5 | // These tests are just smoke tests for get/set policy rules 6 | // We do not need to cover other aspects of casbin, since casbin itself is covered with tests 7 | describe('MongooseAdapter', () => { 8 | beforeEach(async () => { 9 | await createEnforcer(); 10 | await CasbinRule.deleteMany(); 11 | }); 12 | 13 | it('Should properly load policy', async () => { 14 | const enforcer = await createEnforcer(); 15 | assert.deepEqual(await enforcer.getPolicy(), []); 16 | 17 | const rules = await CasbinRule.find(); 18 | assert.deepEqual(rules, []); 19 | }); 20 | 21 | it('Should properly store new policy rules', async () => { 22 | const enforcer = await createEnforcer(); 23 | 24 | const rulesBefore = await CasbinRule.find(); 25 | assert.deepEqual(rulesBefore, []); 26 | assert.isTrue(await enforcer.addPolicy('sub', 'obj', 'act')); 27 | assert.deepEqual(await enforcer.getPolicy(), [['sub', 'obj', 'act']]); 28 | 29 | const rulesAfter = await CasbinRule.find({ p_type: 'p', v0: 'sub', v1: 'obj', v2: 'act' }); 30 | assert.equal(rulesAfter.length, 1); 31 | }); 32 | 33 | it('Should properly delete existing policy rules', async () => { 34 | const enforcer = await createEnforcer(); 35 | 36 | const rulesBefore = await CasbinRule.find(); 37 | assert.deepEqual(rulesBefore, []); 38 | assert.isTrue(await enforcer.addPolicy('sub', 'obj', 'act')); 39 | assert.deepEqual(await enforcer.getPolicy(), [['sub', 'obj', 'act']]); 40 | 41 | const rulesAfter = await CasbinRule.find({ p_type: 'p', v0: 'sub', v1: 'obj', v2: 'act' }); 42 | assert.equal(rulesAfter.length, 1); 43 | assert.isTrue(await enforcer.removePolicy('sub', 'obj', 'act')); 44 | assert.deepEqual(await enforcer.getPolicy(), []); 45 | 46 | const rulesAfterDelete = await CasbinRule.find({ p_type: 'p', v0: 'sub', v1: 'obj', v2: 'act' }); 47 | assert.equal(rulesAfterDelete.length, 0); 48 | }); 49 | 50 | it('Should allow you to close the connection', async () => { 51 | const enforcer = await createEnforcer(); 52 | const adapter = enforcer.getAdapter(); 53 | assert.equal(adapter.mongoseInstance.connection.readyState, 1); 54 | await adapter.close(); 55 | assert.equal(adapter.mongoseInstance.connection.readyState, 0); 56 | }); 57 | }); 58 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | casbin-mongoose-adapter 2 | === 3 | [![NPM version](https://img.shields.io/npm/v/@elastic.io/casbin-mongoose-adapter.svg?style=flat-square)](https://npmjs.com/package/@elastic.io/casbin-mongoose-adapter) 4 | [![NPM download](https://img.shields.io/npm/dm/@elastic.io/casbin-mongoose-adapter.svg?style=flat-square)](https://npmjs.com/package/@elastic.io/casbin-mongoose-adapter) 5 | [![CircleCI](https://circleci.com/gh/elasticio/casbin-mongoose-adapter/tree/master.svg?style=svg)](https://circleci.com/gh/elasticio/casbin-mongoose-adapter/tree/master) 6 | [![Release](https://img.shields.io/github/release/elasticio/casbin-mongoose-adapter.svg)](https://github.com/elasticio/casbin-mongoose-adapter/releases/latest) 7 | 8 | MongoDB policy storage, implemented as an adapter for [node-casbin](https://github.com/casbin/node-casbin). 9 | 10 | ## Getting Started 11 | 12 | Install the package as dependency in your project: 13 | 14 | ```bash 15 | npm install --save @elastic.io/casbin-mongoose-adapter 16 | ``` 17 | 18 | Require it in a place, where you are instantiating an enforcer ([read more about enforcer here](https://github.com/casbin/node-casbin#get-started)): 19 | 20 | ```javascript 21 | const path = require('path'); 22 | const { newEnforcer } = require('casbin'); 23 | const MongooseAdapter = require('@elastic.io/casbin-mongoose-adapter'); 24 | 25 | const model = path.resolve(__dirname, './your_model.conf'); 26 | const adapter = await MongooseAdapter.newAdapter('mongodb://your_mongodb_uri:27017'); 27 | const enforcer = await newEnforcer(model, adapter); 28 | ``` 29 | 30 | That is all what required for integrating the adapter into casbin. 31 | Casbin itself calls adapter methods to persist updates you made through it. 32 | 33 | ## Configuration 34 | 35 | You can pass mongooose-specific options when instantiating the adapter: 36 | 37 | ```javascript 38 | const MongooseAdapter = require('@elastic.io/casbin-mongoose-adapter'); 39 | const adapter = await MongooseAdapter.newAdapter('mongodb://your_mongodb_uri:27017', { mongoose_options: 'here' }); 40 | ``` 41 | 42 | Additional information regard to options you can pass in you can find in [mongoose documentation](https://mongoosejs.com/docs/connections.html#options) 43 | 44 | ## Filtered Adapter 45 | 46 | You can create an adapter instance that will load only those rules you need to. 47 | 48 | A simple case for it is when you have separate policy rules for separate domains (tenants). 49 | You do not need to load all the rules for all domains to make an authorization in specific domain. 50 | 51 | For such cases, filtered adapter exists in casbin. 52 | 53 | ```javascript 54 | const MongooseAdapter = require('@elastic.io/casbin-mongoose-adapter'); 55 | const adapter = await MongooseAdapter.newFilteredAdapter('mongodb://your_mongodb_uri:27017'); 56 | ``` 57 | 58 | ## License 59 | 60 | [Apache-2.0](./LICENSE) 61 | -------------------------------------------------------------------------------- /API.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | ## MongooseAdapter 4 | Implements a policy adapter for casbin with MongoDB support. 5 | 6 | **Kind**: global class 7 | 8 | * [MongooseAdapter](#MongooseAdapter) 9 | * [new MongooseAdapter(uri, [options])](#new_MongooseAdapter_new) 10 | * _instance_ 11 | * [.setFiltered([isFiltered])](#MongooseAdapter+setFiltered) 12 | * [.loadPolicyLine(line, model)](#MongooseAdapter+loadPolicyLine) 13 | * [.loadPolicy(model)](#MongooseAdapter+loadPolicy) ⇒ Promise.<void> 14 | * [.loadFilteredPolicy(model, [filter])](#MongooseAdapter+loadFilteredPolicy) 15 | * [.savePolicyLine(ptype, rule)](#MongooseAdapter+savePolicyLine) ⇒ Object 16 | * [.savePolicy(model)](#MongooseAdapter+savePolicy) ⇒ Promise.<Boolean> 17 | * [.addPolicy(sec, ptype, rule)](#MongooseAdapter+addPolicy) ⇒ Promise.<void> 18 | * [.removePolicy(sec, ptype, rule)](#MongooseAdapter+removePolicy) ⇒ Promise.<void> 19 | * [.removeFilteredPolicy(sec, ptype, fieldIndex, ...fieldValues)](#MongooseAdapter+removeFilteredPolicy) ⇒ Promise.<void> 20 | * _static_ 21 | * [.newAdapter(uri, [options])](#MongooseAdapter.newAdapter) 22 | * [.newFilteredAdapter(uri, [options])](#MongooseAdapter.newFilteredAdapter) 23 | 24 | 25 | 26 | ### new MongooseAdapter(uri, [options]) 27 | Creates a new instance of mongoose adapter for casbin. 28 | It does not wait for successfull connection to MongoDB. 29 | So, if you want to have a possibility to wait until connection successful, use newAdapter instead. 30 | 31 | 32 | | Param | Type | Default | Description | 33 | | --- | --- | --- | --- | 34 | | uri | String | | Mongo URI where casbin rules must be persisted | 35 | | [options] | Object | {} | Additional options to pass on to mongoose client | 36 | 37 | 38 | 39 | ### mongooseAdapter.setFiltered([isFiltered]) 40 | Switch adapter to (non)filtered state. 41 | Casbin uses this flag to determine if it should load the whole policy from DB or not. 42 | 43 | **Kind**: instance method of [MongooseAdapter](#MongooseAdapter) 44 | 45 | | Param | Type | Default | Description | 46 | | --- | --- | --- | --- | 47 | | [isFiltered] | Boolean | true | Flag that represents the current state of adapter (filtered or not) | 48 | 49 | 50 | 51 | ### mongooseAdapter.loadPolicyLine(line, model) 52 | Loads one policy rule into casbin model. 53 | This method is used by casbin and should not be called by user. 54 | 55 | **Kind**: instance method of [MongooseAdapter](#MongooseAdapter) 56 | 57 | | Param | Type | Description | 58 | | --- | --- | --- | 59 | | line | Object | Record with one policy rule from MongoDB | 60 | | model | Object | Casbin model to which policy rule must be loaded | 61 | 62 | 63 | 64 | ### mongooseAdapter.loadPolicy(model) ⇒ Promise.<void> 65 | Implements the process of loading policy from database into enforcer. 66 | This method is used by casbin and should not be called by user. 67 | 68 | **Kind**: instance method of [MongooseAdapter](#MongooseAdapter) 69 | 70 | | Param | Type | Description | 71 | | --- | --- | --- | 72 | | model | Model | Model instance from enforcer | 73 | 74 | 75 | 76 | ### mongooseAdapter.loadFilteredPolicy(model, [filter]) 77 | Loads partial policy based on filter criteria. 78 | This method is used by casbin and should not be called by user. 79 | 80 | **Kind**: instance method of [MongooseAdapter](#MongooseAdapter) 81 | 82 | | Param | Type | Description | 83 | | --- | --- | --- | 84 | | model | Model | Enforcer model | 85 | | [filter] | Object | MongoDB filter to query | 86 | 87 | 88 | 89 | ### mongooseAdapter.savePolicyLine(ptype, rule) ⇒ Object 90 | Persists one policy rule into MongoDB. 91 | This method is used by casbin and should not be called by user. 92 | 93 | **Kind**: instance method of [MongooseAdapter](#MongooseAdapter) 94 | **Returns**: Object - Returns a created CasbinRule record for MongoDB 95 | 96 | | Param | Type | Description | 97 | | --- | --- | --- | 98 | | ptype | String | Policy type to save into MongoDB | 99 | | rule | Array.<String> | An array which consists of policy rule elements to store | 100 | 101 | 102 | 103 | ### mongooseAdapter.savePolicy(model) ⇒ Promise.<Boolean> 104 | Implements the process of saving policy from enforcer into database. 105 | This method is used by casbin and should not be called by user. 106 | 107 | **Kind**: instance method of [MongooseAdapter](#MongooseAdapter) 108 | 109 | | Param | Type | Description | 110 | | --- | --- | --- | 111 | | model | Model | Model instance from enforcer | 112 | 113 | 114 | 115 | ### mongooseAdapter.addPolicy(sec, ptype, rule) ⇒ Promise.<void> 116 | Implements the process of adding policy rule. 117 | This method is used by casbin and should not be called by user. 118 | 119 | **Kind**: instance method of [MongooseAdapter](#MongooseAdapter) 120 | 121 | | Param | Type | Description | 122 | | --- | --- | --- | 123 | | sec | String | Section of the policy | 124 | | ptype | String | Type of the policy (e.g. "p" or "g") | 125 | | rule | Array.<String> | Policy rule to add into enforcer | 126 | 127 | 128 | 129 | ### mongooseAdapter.removePolicy(sec, ptype, rule) ⇒ Promise.<void> 130 | Implements the process of removing policy rule. 131 | This method is used by casbin and should not be called by user. 132 | 133 | **Kind**: instance method of [MongooseAdapter](#MongooseAdapter) 134 | 135 | | Param | Type | Description | 136 | | --- | --- | --- | 137 | | sec | String | Section of the policy | 138 | | ptype | String | Type of the policy (e.g. "p" or "g") | 139 | | rule | Array.<String> | Policy rule to remove from enforcer | 140 | 141 | 142 | 143 | ### mongooseAdapter.removeFilteredPolicy(sec, ptype, fieldIndex, ...fieldValues) ⇒ Promise.<void> 144 | Implements the process of removing policy rules. 145 | This method is used by casbin and should not be called by user. 146 | 147 | **Kind**: instance method of [MongooseAdapter](#MongooseAdapter) 148 | 149 | | Param | Type | Description | 150 | | --- | --- | --- | 151 | | sec | String | Section of the policy | 152 | | ptype | String | Type of the policy (e.g. "p" or "g") | 153 | | fieldIndex | Number | Index of the field to start filtering from | 154 | | ...fieldValues | String | Policy rule to match when removing (starting from fieldIndex) | 155 | 156 | 157 | 158 | ### MongooseAdapter.newAdapter(uri, [options]) 159 | Creates a new instance of mongoose adapter for casbin. 160 | Instead of constructor, it does wait for successfull connection to MongoDB. 161 | Preferable way to construct an adapter instance, is to use this static method. 162 | 163 | **Kind**: static method of [MongooseAdapter](#MongooseAdapter) 164 | 165 | | Param | Type | Default | Description | 166 | | --- | --- | --- | --- | 167 | | uri | String | | Mongo URI where casbin rules must be persisted | 168 | | [options] | Object | {} | Additional options to pass on to mongoose client | 169 | 170 | **Example** 171 | ```js 172 | const adapter = await MongooseAdapter.newAdapter('MONGO_URI'); 173 | const adapter = await MongooseAdapter.newAdapter('MONGO_URI', { mongoose_options: 'here' }); 174 | ``` 175 | 176 | 177 | ### MongooseAdapter.newFilteredAdapter(uri, [options]) 178 | Creates a new instance of mongoose adapter for casbin. 179 | It does the same as newAdapter, but it also sets a flag that this adapter is in filtered state. 180 | That way, casbin will not call loadPolicy() automatically. 181 | 182 | **Kind**: static method of [MongooseAdapter](#MongooseAdapter) 183 | 184 | | Param | Type | Default | Description | 185 | | --- | --- | --- | --- | 186 | | uri | String | | Mongo URI where casbin rules must be persisted | 187 | | [options] | Object | {} | Additional options to pass on to mongoose client | 188 | 189 | **Example** 190 | ```js 191 | const adapter = await MongooseAdapter.newFilteredAdapter('MONGO_URI'); 192 | const adapter = await MongooseAdapter.newFilteredAdapter('MONGO_URI', { mongoose_options: 'here' }); 193 | ``` 194 | -------------------------------------------------------------------------------- /src/adapter.js: -------------------------------------------------------------------------------- 1 | const { Helper } = require('casbin'); 2 | const mongoose = require('mongoose'); 3 | const CasbinRule = require('./model'); 4 | 5 | /** 6 | * Implements a policy adapter for casbin with MongoDB support. 7 | * 8 | * @class 9 | */ 10 | class MongooseAdapter { 11 | /** 12 | * Creates a new instance of mongoose adapter for casbin. 13 | * It does not wait for successfull connection to MongoDB. 14 | * So, if you want to have a possibility to wait until connection successful, use newAdapter instead. 15 | * 16 | * @constructor 17 | * @param {String} uri Mongo URI where casbin rules must be persisted 18 | * @param {Object} [options={}] Additional options to pass on to mongoose client 19 | * @example 20 | * const adapter = new MongooseAdapter('MONGO_URI'); 21 | * const adapter = new MongooseAdapter('MONGO_URI', { mongoose_options: 'here' }) 22 | */ 23 | constructor (uri, options = {}) { 24 | if (!uri || typeof uri !== 'string') { 25 | throw new Error('You must provide Mongo URI to connect to!'); 26 | } 27 | 28 | // by default, adapter is not filtered 29 | this.isFiltered = false; 30 | 31 | mongoose.connect(uri, options).then(instance => { 32 | this.mongoseInstance = instance; 33 | }); 34 | } 35 | 36 | /** 37 | * Creates a new instance of mongoose adapter for casbin. 38 | * Instead of constructor, it does wait for successfull connection to MongoDB. 39 | * Preferable way to construct an adapter instance, is to use this static method. 40 | * 41 | * @static 42 | * @param {String} uri Mongo URI where casbin rules must be persisted 43 | * @param {Object} [options={}] Additional options to pass on to mongoose client 44 | * @example 45 | * const adapter = await MongooseAdapter.newAdapter('MONGO_URI'); 46 | * const adapter = await MongooseAdapter.newAdapter('MONGO_URI', { mongoose_options: 'here' }); 47 | */ 48 | static async newAdapter (uri, options = {}) { 49 | const adapter = new MongooseAdapter(uri, options); 50 | await new Promise(resolve => mongoose.connection.once('connected', resolve)); 51 | 52 | return adapter; 53 | } 54 | 55 | /** 56 | * Creates a new instance of mongoose adapter for casbin. 57 | * It does the same as newAdapter, but it also sets a flag that this adapter is in filtered state. 58 | * That way, casbin will not call loadPolicy() automatically. 59 | * 60 | * @static 61 | * @param {String} uri Mongo URI where casbin rules must be persisted 62 | * @param {Object} [options={}] Additional options to pass on to mongoose client 63 | * @example 64 | * const adapter = await MongooseAdapter.newFilteredAdapter('MONGO_URI'); 65 | * const adapter = await MongooseAdapter.newFilteredAdapter('MONGO_URI', { mongoose_options: 'here' }); 66 | */ 67 | static async newFilteredAdapter (uri, options = {}) { 68 | const adapter = await MongooseAdapter.newAdapter(uri, options); 69 | adapter.setFiltered(true); 70 | 71 | return adapter; 72 | } 73 | 74 | /** 75 | * Switch adapter to (non)filtered state. 76 | * Casbin uses this flag to determine if it should load the whole policy from DB or not. 77 | * 78 | * @param {Boolean} [isFiltered=true] Flag that represents the current state of adapter (filtered or not) 79 | */ 80 | setFiltered (isFiltered = true) { 81 | this.isFiltered = isFiltered; 82 | } 83 | 84 | /** 85 | * Loads one policy rule into casbin model. 86 | * This method is used by casbin and should not be called by user. 87 | * 88 | * @param {Object} line Record with one policy rule from MongoDB 89 | * @param {Object} model Casbin model to which policy rule must be loaded 90 | */ 91 | loadPolicyLine (line, model) { 92 | let lineText = line.p_type; 93 | 94 | if (line.v0) { 95 | lineText += ', ' + line.v0; 96 | } 97 | 98 | if (line.v1) { 99 | lineText += ', ' + line.v1; 100 | } 101 | 102 | if (line.v2) { 103 | lineText += ', ' + line.v2; 104 | } 105 | 106 | if (line.v3) { 107 | lineText += ', ' + line.v3; 108 | } 109 | 110 | if (line.v4) { 111 | lineText += ', ' + line.v4; 112 | } 113 | 114 | if (line.v5) { 115 | lineText += ', ' + line.v5; 116 | } 117 | 118 | Helper.loadPolicyLine(lineText, model); 119 | } 120 | 121 | /** 122 | * Implements the process of loading policy from database into enforcer. 123 | * This method is used by casbin and should not be called by user. 124 | * 125 | * @param {Model} model Model instance from enforcer 126 | * @returns {Promise} 127 | */ 128 | async loadPolicy (model) { 129 | return this.loadFilteredPolicy(model); 130 | } 131 | 132 | /** 133 | * Loads partial policy based on filter criteria. 134 | * This method is used by casbin and should not be called by user. 135 | * 136 | * @param {Model} model Enforcer model 137 | * @param {Object} [filter] MongoDB filter to query 138 | */ 139 | async loadFilteredPolicy (model, filter) { 140 | if (filter) { 141 | this.setFiltered(true); 142 | } else { 143 | this.setFiltered(false); 144 | } 145 | 146 | const lines = await CasbinRule.find(filter || {}); 147 | for (const line of lines) { 148 | this.loadPolicyLine(line, model); 149 | } 150 | } 151 | 152 | /** 153 | * Persists one policy rule into MongoDB. 154 | * This method is used by casbin and should not be called by user. 155 | * 156 | * @param {String} ptype Policy type to save into MongoDB 157 | * @param {Array} rule An array which consists of policy rule elements to store 158 | * @returns {Object} Returns a created CasbinRule record for MongoDB 159 | */ 160 | savePolicyLine (ptype, rule) { 161 | const model = new CasbinRule({ p_type: ptype }); 162 | 163 | if (rule.length > 0) { 164 | model.v0 = rule[0]; 165 | } 166 | 167 | if (rule.length > 1) { 168 | model.v1 = rule[1]; 169 | } 170 | 171 | if (rule.length > 2) { 172 | model.v2 = rule[2]; 173 | } 174 | 175 | if (rule.length > 3) { 176 | model.v3 = rule[3]; 177 | } 178 | 179 | if (rule.length > 4) { 180 | model.v4 = rule[4]; 181 | } 182 | 183 | if (rule.length > 5) { 184 | model.v5 = rule[5]; 185 | } 186 | 187 | return model; 188 | } 189 | 190 | /** 191 | * Implements the process of saving policy from enforcer into database. 192 | * This method is used by casbin and should not be called by user. 193 | * 194 | * @param {Model} model Model instance from enforcer 195 | * @returns {Promise} 196 | */ 197 | async savePolicy (model) { 198 | const policyRuleAST = model.model.get('p'); 199 | const groupingPolicyAST = model.model.get('g'); 200 | 201 | for (const [ptype, ast] of policyRuleAST) { 202 | for (const rule of ast.policy) { 203 | const line = this.savePolicyLine(ptype, rule); 204 | await line.save(); 205 | } 206 | } 207 | 208 | for (const [ptype, ast] of groupingPolicyAST) { 209 | for (const rule of ast.policy) { 210 | const line = this.savePolicyLine(ptype, rule); 211 | await line.save(); 212 | } 213 | } 214 | 215 | return true; 216 | } 217 | 218 | /** 219 | * Implements the process of adding policy rule. 220 | * This method is used by casbin and should not be called by user. 221 | * 222 | * @param {String} sec Section of the policy 223 | * @param {String} ptype Type of the policy (e.g. "p" or "g") 224 | * @param {Array} rule Policy rule to add into enforcer 225 | * @returns {Promise} 226 | */ 227 | async addPolicy (sec, ptype, rule) { 228 | const line = this.savePolicyLine(ptype, rule); 229 | await line.save(); 230 | } 231 | 232 | /** 233 | * Implements the process of removing policy rule. 234 | * This method is used by casbin and should not be called by user. 235 | * 236 | * @param {String} sec Section of the policy 237 | * @param {String} ptype Type of the policy (e.g. "p" or "g") 238 | * @param {Array} rule Policy rule to remove from enforcer 239 | * @returns {Promise} 240 | */ 241 | async removePolicy (sec, ptype, rule) { 242 | const { p_type, v0, v1, v2, v3, v4, v5 } = this.savePolicyLine(ptype, rule); 243 | await CasbinRule.deleteMany({ p_type, v0, v1, v2, v3, v4, v5 }); 244 | } 245 | 246 | /** 247 | * Implements the process of removing policy rules. 248 | * This method is used by casbin and should not be called by user. 249 | * 250 | * @param {String} sec Section of the policy 251 | * @param {String} ptype Type of the policy (e.g. "p" or "g") 252 | * @param {Number} fieldIndex Index of the field to start filtering from 253 | * @param {...String} fieldValues Policy rule to match when removing (starting from fieldIndex) 254 | * @returns {Promise} 255 | */ 256 | async removeFilteredPolicy (sec, ptype, fieldIndex, ...fieldValues) { 257 | const where = { p_type: ptype }; 258 | 259 | if (fieldIndex <= 0 && fieldIndex + fieldValues.length > 0 && fieldValues[0 - fieldIndex]) { 260 | where.v0 = fieldValues[0 - fieldIndex]; 261 | } 262 | 263 | if (fieldIndex <= 1 && fieldIndex + fieldValues.length > 1 && fieldValues[1 - fieldIndex]) { 264 | where.v1 = fieldValues[1 - fieldIndex]; 265 | } 266 | 267 | if (fieldIndex <= 2 && fieldIndex + fieldValues.length > 2 && fieldValues[2 - fieldIndex]) { 268 | where.v2 = fieldValues[2 - fieldIndex]; 269 | } 270 | 271 | if (fieldIndex <= 3 && fieldIndex + fieldValues.length > 3 && fieldValues[3 - fieldIndex]) { 272 | where.v3 = fieldValues[3 - fieldIndex]; 273 | } 274 | 275 | if (fieldIndex <= 4 && fieldIndex + fieldValues.length > 4 && fieldValues[4 - fieldIndex]) { 276 | where.v4 = fieldValues[4 - fieldIndex]; 277 | } 278 | 279 | if (fieldIndex <= 5 && fieldIndex + fieldValues.length > 5 && fieldValues[5 - fieldIndex]) { 280 | where.v5 = fieldValues[5 - fieldIndex]; 281 | } 282 | 283 | await CasbinRule.deleteMany(where); 284 | } 285 | 286 | async close () { 287 | if (this.mongoseInstance && this.mongoseInstance.connection) { 288 | this.mongoseInstance.connection.close(); 289 | } 290 | } 291 | } 292 | 293 | module.exports = MongooseAdapter; 294 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | Copyright 2019 elastic.io GmbH 179 | 180 | Licensed under the Apache License, Version 2.0 (the "License"); 181 | you may not use this file except in compliance with the License. 182 | You may obtain a copy of the License at 183 | 184 | http://www.apache.org/licenses/LICENSE-2.0 185 | 186 | Unless required by applicable law or agreed to in writing, software 187 | distributed under the License is distributed on an "AS IS" BASIS, 188 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 189 | See the License for the specific language governing permissions and 190 | limitations under the License. 191 | --------------------------------------------------------------------------------