├── .eslintignore ├── test ├── fixtures │ ├── basic_policy.csv │ ├── rbac_policy.csv │ ├── basic_model.conf │ ├── rbac_with_domains_with_deny_policy.csv │ ├── rbac_model.conf │ └── rbac_with_domains_with_deny_model.conf ├── .eslintrc.json ├── unit │ ├── .mocharc.js │ └── adapter.test.js ├── .mocharc.js ├── integration │ ├── .mocharc.js │ └── adapter.test.js └── helpers │ └── helpers.js ├── .github ├── semantic.yml ├── mongo_setup.sh ├── Dockerfile ├── docker-entrypoint.sh └── workflows │ └── main.yml ├── tsconfig.cjs.json ├── tsconfig.esm.json ├── src ├── index.ts ├── errors.ts ├── model.ts └── adapter.ts ├── .prettierrc ├── .editorconfig ├── .eslintrc.json ├── tsconfig.json ├── .releaserc.json ├── .gitignore ├── package.json ├── README.md ├── CHANGELOG.md └── LICENSE /.eslintignore: -------------------------------------------------------------------------------- 1 | coverage 2 | lib/ 3 | -------------------------------------------------------------------------------- /test/fixtures/basic_policy.csv: -------------------------------------------------------------------------------- 1 | p, alice, data1, read 2 | p, bob, data2, write -------------------------------------------------------------------------------- /.github/semantic.yml: -------------------------------------------------------------------------------- 1 | # Always validate the PR title AND all the commits 2 | titleAndCommits: true 3 | -------------------------------------------------------------------------------- /test/.eslintrc.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "../.eslintrc.json", 3 | "env": { 4 | "mocha": true 5 | } 6 | } 7 | -------------------------------------------------------------------------------- /test/fixtures/rbac_policy.csv: -------------------------------------------------------------------------------- 1 | p, alice, data1, read 2 | p, bob, data2, write 3 | p, data2_admin, data2, read 4 | p, data2_admin, data2, write 5 | g, alice, data2_admin -------------------------------------------------------------------------------- /tsconfig.cjs.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "./tsconfig", 3 | "compilerOptions": { 4 | "target": "ES6", 5 | "module": "CommonJS", 6 | "outDir": "lib/cjs" 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /tsconfig.esm.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "./tsconfig", 3 | "compilerOptions": { 4 | "target": "ES2017", 5 | "module": "ESNext", 6 | "outDir": "lib/esm" 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /.github/mongo_setup.sh: -------------------------------------------------------------------------------- 1 | docker build -t mongodb-rs:latest ./.github/ 2 | 3 | docker run -d -p 27001:27001 -p 27002:27002 -p 27003:27003 --name mongo -e "REPLICA_SET_NAME=rs0" mongodb-rs 4 | -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- 1 | import {MongooseAdapter} from "./adapter"; 2 | 3 | export * from './model' 4 | export * from './errors' 5 | export * from './adapter' 6 | 7 | export default MongooseAdapter 8 | -------------------------------------------------------------------------------- /.prettierrc: -------------------------------------------------------------------------------- 1 | { 2 | "endOfLine": "lf", 3 | "semi": true, 4 | "camelcase": false, 5 | "new-cap": false, 6 | "singleQuote": true, 7 | "tabWidth": 2, 8 | "trailingComma": "none", 9 | "printWidth": 100 10 | } 11 | -------------------------------------------------------------------------------- /.github/Dockerfile: -------------------------------------------------------------------------------- 1 | FROM mongo:6.0.13 2 | 3 | VOLUME /data 4 | EXPOSE 27001 27002 27003 5 | 6 | COPY docker-entrypoint.sh /usr/local/bin/ 7 | RUN chmod +x /usr/local/bin/docker-entrypoint.sh 8 | 9 | ENTRYPOINT ["docker-entrypoint.sh"] 10 | -------------------------------------------------------------------------------- /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 -------------------------------------------------------------------------------- /test/unit/.mocharc.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | recursive: true, 3 | extension: ['js'], 4 | diff: true, 5 | opts: false, 6 | exit: true, 7 | reporter: 'spec', 8 | slow: 75, 9 | ui: 'bdd', 10 | spec: 'test/unit/**/*.test.js' 11 | }; 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 | -------------------------------------------------------------------------------- /test/.mocharc.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | recursive: true, 3 | extension: ['js'], 4 | diff: true, 5 | opts: false, 6 | exit: true, 7 | reporter: 'spec', 8 | slow: 75, 9 | timeout: 4000, 10 | ui: 'bdd', 11 | spec: 'test/**/**/*.test.js' 12 | }; -------------------------------------------------------------------------------- /test/fixtures/rbac_with_domains_with_deny_policy.csv: -------------------------------------------------------------------------------- 1 | p, admin, domain1, data1, read, allow 2 | p, admin, domain1, data1, write, allow 3 | p, admin, domain2, data2, read, allow 4 | p, admin, domain2, data2, write, allow 5 | p, alice, domain2, data2, write, deny 6 | 7 | g, alice, admin, domain2 -------------------------------------------------------------------------------- /.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/fixtures/rbac_model.conf: -------------------------------------------------------------------------------- 1 | [request_definition] 2 | r = sub, obj, act 3 | 4 | [policy_definition] 5 | p = sub, obj, act 6 | 7 | [role_definition] 8 | g = _, _ 9 | 10 | [policy_effect] 11 | e = some(where (p.eft == allow)) 12 | 13 | [matchers] 14 | m = g(r.sub, p.sub) && r.obj == p.obj && r.act == p.act -------------------------------------------------------------------------------- /test/integration/.mocharc.js: -------------------------------------------------------------------------------- 1 | 2 | module.exports = { 3 | recursive: true, 4 | extension: ['js'], 5 | diff: true, 6 | opts: false, 7 | exit: true, 8 | reporter: 'spec', 9 | slow: 75, 10 | timeout: 4000, 11 | ui: 'bdd', 12 | spec: 'test/integration/**/*.test.js' 13 | }; 14 | -------------------------------------------------------------------------------- /src/errors.ts: -------------------------------------------------------------------------------- 1 | class AdapterError extends Error { 2 | constructor(message: string) { 3 | super(message); 4 | this.name = 'AdapterError'; 5 | } 6 | } 7 | 8 | class InvalidAdapterTypeError extends Error { 9 | constructor(message: string) { 10 | super(message); 11 | this.name = 'InvalidAdapterTypeError'; 12 | } 13 | } 14 | 15 | export {AdapterError, InvalidAdapterTypeError} 16 | -------------------------------------------------------------------------------- /test/fixtures/rbac_with_domains_with_deny_model.conf: -------------------------------------------------------------------------------- 1 | [request_definition] 2 | r = sub, dom, obj, act 3 | 4 | [policy_definition] 5 | p = sub, dom, obj, act, eft 6 | 7 | [role_definition] 8 | g = _, _, _ 9 | 10 | [policy_effect] 11 | e = some(where (p.eft == allow)) && !some(where (p.eft == deny)) 12 | 13 | [matchers] 14 | m = g(r.sub, p.sub, r.dom) && r.dom == p.dom && r.obj == p.obj && r.act == p.act -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "target": "ES6", 4 | "module": "CommonJS", 5 | "moduleResolution": "Node", 6 | "strict": true, 7 | "strictPropertyInitialization": false, 8 | "declaration": true, 9 | "downlevelIteration": true, 10 | "allowJs": true, 11 | "allowSyntheticDefaultImports": true, 12 | "esModuleInterop": true 13 | }, 14 | "include": ["src/**/*"] 15 | } 16 | -------------------------------------------------------------------------------- /.releaserc.json: -------------------------------------------------------------------------------- 1 | { 2 | "debug": true, 3 | "plugins": [ 4 | "@semantic-release/commit-analyzer", 5 | "@semantic-release/release-notes-generator", 6 | "@semantic-release/npm", 7 | [ 8 | "@semantic-release/changelog", 9 | { 10 | "changelogFile": "CHANGELOG.md" 11 | } 12 | ], 13 | [ 14 | "@semantic-release/git", 15 | { 16 | "assets": ["package.json", "CHANGELOG.md"], 17 | "message": "chore(release): ${nextRelease.version} [skip ci]\n\n${nextRelease.notes}" 18 | } 19 | ], 20 | "@semantic-release/github" 21 | ] 22 | } 23 | -------------------------------------------------------------------------------- /.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 | 82 | .idea/ 83 | *.iml 84 | 85 | lib/ 86 | 87 | # Lock files 88 | package-lock.json 89 | -------------------------------------------------------------------------------- /src/model.ts: -------------------------------------------------------------------------------- 1 | // Copyright 2019 The elastic.io team (http://elastic.io). All Rights Reserved. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | import {Schema, Document} from 'mongoose'; 16 | 17 | export interface IModel extends Document { 18 | ptype: string; 19 | v0: string; 20 | v1: string; 21 | v2: string; 22 | v3: string; 23 | v4: string; 24 | v5: string; 25 | } 26 | 27 | export const collectionName = 'casbin_rule'; 28 | export const modelName = 'CasbinRule'; 29 | 30 | export const schema = (timestamps = false, customCollectionName?: string) => { 31 | return new Schema({ 32 | ptype: { 33 | type: Schema.Types.String, 34 | required: true, 35 | index: true 36 | }, 37 | v0: { 38 | type: Schema.Types.String, 39 | index: true 40 | }, 41 | v1: { 42 | type: Schema.Types.String, 43 | index: true 44 | }, 45 | v2: { 46 | type: Schema.Types.String, 47 | index: true 48 | }, 49 | v3: { 50 | type: Schema.Types.String, 51 | index: true 52 | }, 53 | v4: { 54 | type: Schema.Types.String, 55 | index: true 56 | }, 57 | v5: { 58 | type: Schema.Types.String, 59 | index: true 60 | } 61 | }, { 62 | collection: customCollectionName || collectionName, 63 | minimize: false, 64 | timestamps: timestamps 65 | }); 66 | } 67 | -------------------------------------------------------------------------------- /.github/docker-entrypoint.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | set -e 3 | 4 | REPLICA_SET_NAME=${REPLICA_SET_NAME:=rs0} 5 | USERNAME=${USERNAME:=dev} 6 | PASSWORD=${PASSWORD:=dev} 7 | 8 | 9 | function waitForMongo { 10 | port=$1 11 | n=0 12 | until [ $n -ge 20 ] 13 | do 14 | mongosh admin --quiet --port $port --eval "db" && break 15 | n=$[$n+1] 16 | sleep 2 17 | done 18 | } 19 | 20 | if [ ! "$(ls -A /data/db1)" ]; then 21 | mkdir /data/db1 22 | mkdir /data/db2 23 | mkdir /data/db3 24 | fi 25 | 26 | echo "STARTING CLUSTER" 27 | 28 | mongod --port 27003 --dbpath /data/db3 --replSet $REPLICA_SET_NAME --bind_ip=::,0.0.0.0 & 29 | DB3_PID=$! 30 | mongod --port 27002 --dbpath /data/db2 --replSet $REPLICA_SET_NAME --bind_ip=::,0.0.0.0 & 31 | DB2_PID=$! 32 | mongod --port 27001 --dbpath /data/db1 --replSet $REPLICA_SET_NAME --bind_ip=::,0.0.0.0 & 33 | DB1_PID=$! 34 | 35 | waitForMongo 27001 36 | waitForMongo 27002 37 | waitForMongo 27003 38 | 39 | echo "CONFIGURING REPLICA SET" 40 | CONFIG="{ _id: '$REPLICA_SET_NAME', members: [{_id: 0, host: 'localhost:27001', priority: 2 }, { _id: 1, host: 'localhost:27002' }, { _id: 2, host: 'localhost:27003' } ]}" 41 | mongosh admin --port 27001 --eval "db.runCommand({ replSetInitiate: $CONFIG })" 42 | 43 | waitForMongo 27002 44 | waitForMongo 27003 45 | 46 | mongosh admin --port 27001 --eval "db.runCommand({ setParameter: 1, quiet: 1 })" 47 | mongosh admin --port 27002 --eval "db.runCommand({ setParameter: 1, quiet: 1 })" 48 | mongosh admin --port 27003 --eval "db.runCommand({ setParameter: 1, quiet: 1 })" 49 | 50 | mongosh admin --port 27001 --eval "db.adminCommand({ setParameter: 1, maxTransactionLockRequestTimeoutMillis: 5000 })" 51 | mongosh admin --port 27002 --eval "db.adminCommand({ setParameter: 1, maxTransactionLockRequestTimeoutMillis: 5000 })" 52 | mongosh admin --port 27003 --eval "db.adminCommand({ setParameter: 1, maxTransactionLockRequestTimeoutMillis: 5000 })" 53 | 54 | echo "REPLICA SET ONLINE" 55 | 56 | trap 'echo "KILLING"; kill $DB1_PID $DB2_PID $DB3_PID; wait $DB1_PID; wait $DB2_PID; wait $DB3_PID' SIGINT SIGTERM EXIT 57 | 58 | wait $DB1_PID 59 | wait $DB2_PID 60 | wait $DB3_PID 61 | -------------------------------------------------------------------------------- /.github/workflows/main.yml: -------------------------------------------------------------------------------- 1 | name: main 2 | on: 3 | pull_request: 4 | push: 5 | branches: 6 | - master 7 | jobs: 8 | test: 9 | runs-on: ubuntu-latest 10 | strategy: 11 | fail-fast: false 12 | matrix: 13 | node-version: ['20', '22'] 14 | steps: 15 | - name: Checkout 16 | uses: actions/checkout@v2 17 | 18 | - name: Setup MongoDB 19 | run: bash ./.github/mongo_setup.sh 20 | 21 | - uses: actions/setup-node@v1 22 | with: 23 | node-version: ${{ matrix.node-version }} 24 | 25 | - name: Install Dependency 26 | run: yarn install --ignore-engines 27 | 28 | - name: Build library 29 | run: yarn run build 30 | 31 | - name: Run unit tests 32 | run: yarn run tests 33 | 34 | coverall: 35 | needs: [test] 36 | runs-on: ubuntu-latest 37 | strategy: 38 | fail-fast: false 39 | matrix: 40 | node-version: ['20', '22'] 41 | steps: 42 | - name: Checkout 43 | uses: actions/checkout@v2 44 | 45 | - name: Setup MongoDB 46 | run: bash ./.github/mongo_setup.sh 47 | 48 | - uses: actions/setup-node@v1 49 | with: 50 | node-version: ${{ matrix.node-version }} 51 | 52 | - name: Install Dependency 53 | run: yarn install --ignore-engines 54 | 55 | - name: Build library 56 | run: yarn run build 57 | 58 | - name: Run code coverage 59 | run: yarn run coverage 60 | 61 | - name: Coveralls Parallel 62 | uses: coverallsapp/github-action@master 63 | with: 64 | github-token: ${{ secrets.GITHUB_TOKEN }} 65 | 66 | release: 67 | needs: [test,coverall] 68 | runs-on: ubuntu-latest 69 | steps: 70 | - name: Coveralls Finished 71 | uses: coverallsapp/github-action@master 72 | with: 73 | github-token: ${{ secrets.GITHUB_TOKEN }} 74 | parallel-finished: true 75 | 76 | - name: Checkout 77 | uses: actions/checkout@v2 78 | 79 | - name: Install Dependency 80 | run: yarn install --ignore-engines 81 | 82 | - name: Build library 83 | run: yarn run build 84 | 85 | - name: Release 86 | if: github.event_name == 'push' && github.repository == 'node-casbin/mongoose-adapter' 87 | run: npx -p semantic-release -p @semantic-release/git -p @semantic-release/changelog -p @semantic-release/commit-analyzer -p @semantic-release/release-notes-generator -p @semantic-release/release-notes-generator -p @semantic-release/changelog -p @semantic-release/git -p @semantic-release/github semantic-release 88 | env: 89 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 90 | NPM_TOKEN: ${{ secrets.NPM_TOKEN }} 91 | -------------------------------------------------------------------------------- /test/helpers/helpers.js: -------------------------------------------------------------------------------- 1 | // Copyright 2019 The elastic.io team (http://elastic.io). All Rights Reserved. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | const path = require('path'); 16 | const { newEnforcer } = require('casbin'); 17 | const { MongooseAdapter } = require('../../lib/cjs'); 18 | const basicModel = path.resolve(__dirname, '../fixtures/basic_model.conf'); 19 | const basicPolicy = path.resolve(__dirname, '../fixtures/basic_policy.csv'); 20 | const rbacModel = path.resolve(__dirname, '../fixtures/rbac_model.conf'); 21 | const rbacPolicy = path.resolve(__dirname, '../fixtures/rbac_policy.csv'); 22 | const rbacDenyDomainModel = path.resolve(__dirname, '../fixtures/rbac_with_domains_with_deny_model.conf'); 23 | const rbacDenyDomainPolicy = path.resolve(__dirname, '../fixtures/rbac_with_domains_with_deny_policy.csv'); 24 | 25 | async function createEnforcer () { 26 | const adapter = await MongooseAdapter.newAdapter('mongodb://localhost:27001,localhost:27002/casbin?replicaSet=rs0'); 27 | 28 | return newEnforcer(basicModel, adapter); 29 | } 30 | 31 | async function createAdapter (useTransaction = false) { 32 | return MongooseAdapter.newAdapter('mongodb://localhost:27001,localhost:27002/casbin?replicaSet=rs0', {}, { 33 | filtered: false, 34 | synced: useTransaction 35 | }); 36 | } 37 | 38 | async function createAdapterWithDBName (dbName, useTransaction = false) { 39 | return MongooseAdapter.newAdapter('mongodb://localhost:27001,localhost:27002?replicaSet=rs0', { 40 | dbName: dbName 41 | }, { 42 | filtered: false, 43 | synced: useTransaction 44 | }); 45 | } 46 | 47 | async function createSyncedAdapter () { 48 | const adapter = MongooseAdapter.newSyncedAdapter('mongodb://localhost:27001,localhost:27002/casbin?replicaSet=rs0'); 49 | await new Promise(resolve => setTimeout(resolve, 1000)); 50 | return adapter; 51 | } 52 | 53 | async function createDisconnectedAdapter () { 54 | return new MongooseAdapter('mongodb://localhost:27001,localhost:27002/casbin?replicaSet=rs0'); 55 | } 56 | 57 | module.exports = { 58 | createEnforcer, 59 | createAdapter, 60 | createAdapterWithDBName, 61 | createSyncedAdapter, 62 | createDisconnectedAdapter, 63 | basicModel, 64 | basicPolicy, 65 | rbacModel, 66 | rbacPolicy, 67 | rbacDenyDomainModel, 68 | rbacDenyDomainPolicy 69 | }; 70 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "casbin-mongoose-adapter", 3 | "version": "5.6.0", 4 | "description": "Mongoose adapter for Casbin", 5 | "main": "lib/cjs/index.js", 6 | "typings": "lib/cjs/index.d.ts", 7 | "module": "lib/esm/index.js", 8 | "license": "Apache-2.0", 9 | "homepage": "https://github.com/node-casbin/mongoose-adapter", 10 | "author": { 11 | "name": "Node-Casbin" 12 | }, 13 | "contributors": [ 14 | { 15 | "name": "Eugene Obrezkov", 16 | "email": "ghaiklor@gmail.com", 17 | "url": "https://ghaiklor.com" 18 | } 19 | ], 20 | "repository": { 21 | "type": "git", 22 | "url": "git+https://github.com/node-casbin/mongoose-adapter.git" 23 | }, 24 | "bugs": { 25 | "url": "https://github.com/node-casbin/mongoose-adapter/issues" 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 | "lint": "eslint .", 50 | "prepublishOnly": "npm run lint", 51 | "test:integration": "nyc mocha -- --config test/integration/.mocharc.js", 52 | "test:unit": "nyc mocha -- --config test/unit/.mocharc.js", 53 | "tests": "run-s build && run-s test:*", 54 | "coverage": "nyc mocha -- --config test/.mocharc.js", 55 | "postpack": "run-s clean", 56 | "build": "run-s clean && run-p build:*", 57 | "build:cjs": "tsc -p tsconfig.cjs.json", 58 | "build:esm": "tsc -p tsconfig.esm.json", 59 | "clean": "rimraf lib", 60 | "prepare": "npm run build" 61 | }, 62 | "devDependencies": { 63 | "@types/node": "^20.11.6", 64 | "@typescript-eslint/eslint-plugin": "^6.19.1", 65 | "casbin": "^5.28.0", 66 | "chai": "^4.3.0", 67 | "coveralls": "^3.1.1", 68 | "cz-conventional-changelog": "^3.3.0", 69 | "eslint": "^7.20.0", 70 | "eslint-config-standard": "^16.0.2", 71 | "eslint-plugin-import": "^2.29.1", 72 | "eslint-plugin-node": "^11.1.0", 73 | "eslint-plugin-promise": "^4.3.1", 74 | "eslint-plugin-standard": "^5.0.0", 75 | "husky": "^5.0.9", 76 | "jsdoc-to-markdown": "^6.0.1", 77 | "mocha": "^8.3.0", 78 | "npm-run-all": "^4.1.5", 79 | "nyc": "^15.1.0", 80 | "sinon": "^9.0.0", 81 | "typescript": "^5.3.3" 82 | }, 83 | "dependencies": { 84 | "mongoose": "^8.1.1" 85 | }, 86 | "peerDependencies": { 87 | "casbin": "^5.28.0" 88 | }, 89 | "husky": { 90 | "hooks": { 91 | "prepare-commit-msg": "exec < /dev/tty && git cz --hook || true", 92 | "pre-commit": "npm run lint" 93 | } 94 | }, 95 | "config": { 96 | "commitizen": { 97 | "path": "./node_modules/cz-conventional-changelog" 98 | } 99 | }, 100 | "nyc": { 101 | "reporter": [ 102 | "lcov" 103 | ] 104 | } 105 | } 106 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Mongoose Adapter 2 | ==== 3 | [![tests](https://github.com/node-casbin/mongoose-adapter/actions/workflows/main.yml/badge.svg)](https://github.com/node-casbin/mongoose-adapter/actions/workflows/main.yml) 4 | [![NPM version][npm-image]][npm-url] 5 | [![NPM download][download-image]][download-url] 6 | [![codebeat badge](https://codebeat.co/badges/c17c9ee1-da42-4db3-8047-9574ad2b23b1)](https://codebeat.co/projects/github-com-node-casbin-mongoose-adapter-master) 7 | [![Coverage Status](https://coveralls.io/repos/github/node-casbin/mongoose-adapter/badge.svg?branch=master)](https://coveralls.io/github/node-casbin/mongoose-adapter?branch=master) 8 | [![Discord](https://img.shields.io/discord/1022748306096537660?logo=discord&label=discord&color=5865F2)](https://discord.gg/S5UjpzGZjN) 9 | 10 | [npm-image]: https://img.shields.io/npm/v/casbin-mongoose-adapter.svg?style=flat-square 11 | [npm-url]: https://npmjs.org/package/casbin-mongoose-adapter 12 | [download-image]: https://img.shields.io/npm/dm/casbin-mongoose-adapter.svg?style=flat-square 13 | [download-url]: https://npmjs.org/package/casbin-mongoose-adapter 14 | 15 | Mongoose Adapter is the [Mongoose](https://github.com/Automattic/mongoose/) adapter for [Node-Casbin](https://github.com/casbin/node-casbin). With this library, Node-Casbin can load policy from Mongoose supported database or save policy to it. It is originally developed by @ghaiklor from @elasticio. 16 | 17 | Based on [Officially Supported Databases](https://mongoosejs.com/docs/), The current supported database is MongoDB. 18 | 19 | Mongoose Adapter has been rewritten to TypeScript since v3.x. 20 | 21 | ## Getting Started 22 | 23 | Install the package as dependency in your project: 24 | 25 | ```bash 26 | npm install --save casbin-mongoose-adapter casbin 27 | ``` 28 | **Note**: `casbin` as peerDependencies! 29 | 30 | Require it in a place, where you are instantiating an enforcer ([read more about enforcer here](https://github.com/casbin/node-casbin#get-started)): 31 | 32 | ```javascript 33 | const path = require('path'); 34 | const { newEnforcer } = require('casbin'); 35 | const { MongooseAdapter } = require('casbin-mongoose-adapter'); 36 | 37 | // const MongooseAdapter = require('casbin-mongoose-adapter'); 38 | // You should use this in v2.x 39 | 40 | const model = path.resolve(__dirname, './your_model.conf'); 41 | const adapter = await MongooseAdapter.newAdapter('mongodb://your_mongodb_uri:27017'); 42 | const enforcer = await newEnforcer(model, adapter); 43 | ``` 44 | 45 | That is all what required for integrating the adapter into casbin. 46 | Casbin itself calls adapter methods to persist updates you made through it. 47 | 48 | ## Configuration 49 | 50 | You can pass mongooose-specific options when instantiating the adapter: 51 | 52 | ```javascript 53 | const { MongooseAdapter } = require('casbin-mongoose-adapter'); 54 | const adapter = await MongooseAdapter.newAdapter('mongodb://your_mongodb_uri:27017', { mongoose_options: 'here' }); 55 | ``` 56 | 57 | Additional information regard to options you can pass in you can find in [mongoose documentation](https://mongoosejs.com/docs/connections.html#options) 58 | 59 | ### Custom Collection Name 60 | 61 | By default, the adapter uses `casbin_rule` as the collection name. You can customize this by passing a `collectionName` option in `adapterOptions`: 62 | 63 | ```javascript 64 | const { MongooseAdapter } = require('casbin-mongoose-adapter'); 65 | 66 | // Use custom collection name 67 | const adapter = await MongooseAdapter.newAdapter( 68 | 'mongodb://your_mongodb_uri:27017', 69 | {}, 70 | { collectionName: 'casbinRule' } 71 | ); 72 | ``` 73 | 74 | This allows you to follow your own database naming conventions (e.g., camelCase). 75 | 76 | ## Filtered Adapter 77 | 78 | You can create an adapter instance that will load only those rules you need to. 79 | 80 | A simple case for it is when you have separate policy rules for separate domains (tenants). 81 | You do not need to load all the rules for all domains to make an authorization in specific domain. 82 | 83 | For such cases, filtered adapter exists in casbin. 84 | 85 | ```javascript 86 | const { MongooseAdapter } = require('casbin-mongoose-adapter'); 87 | const adapter = await MongooseAdapter.newFilteredAdapter('mongodb://your_mongodb_uri:27017'); 88 | ``` 89 | 90 | ## License 91 | 92 | [Apache-2.0](./LICENSE) 93 | -------------------------------------------------------------------------------- /test/unit/adapter.test.js: -------------------------------------------------------------------------------- 1 | // Copyright 2019 The elastic.io team (http://elastic.io). All Rights Reserved. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | const { assert } = require('chai'); 16 | const { MongooseAdapter } = require('../../lib/cjs'); 17 | 18 | describe('MongooseAdapter', () => { 19 | it('Should properly throw error if Mongo URI is not provided', async () => { 20 | assert.throws(() => new MongooseAdapter(), 'You must provide Mongo URI to connect to!'); 21 | }); 22 | 23 | it('Should properly instantiate adapter', async () => { 24 | const adapter = new MongooseAdapter('mongodb://localhost:27001/casbin'); 25 | 26 | assert.instanceOf(adapter, MongooseAdapter); 27 | assert.isFalse(adapter.isFiltered()); 28 | 29 | await adapter.close(); 30 | }); 31 | 32 | it('Should properly create new instance via static newAdapter', async () => { 33 | const adapter = await MongooseAdapter.newAdapter('mongodb://localhost:27001,localhost:27002/casbin?replicaSet=rs0'); 34 | 35 | assert.instanceOf(adapter, MongooseAdapter); 36 | assert.isFalse(adapter.isFiltered()); 37 | 38 | await adapter.close(); 39 | }); 40 | 41 | it('Should properly create filtered instance via static newFilteredAdapter', async () => { 42 | const adapter = await MongooseAdapter.newFilteredAdapter('mongodb://localhost:27001,localhost:27002/casbin?replicaSet=rs0'); 43 | 44 | assert.instanceOf(adapter, MongooseAdapter); 45 | assert.isTrue(adapter.isFiltered()); 46 | 47 | await adapter.close(); 48 | }); 49 | 50 | it('Should have implemented interface for casbin', async () => { 51 | const adapter = new MongooseAdapter('mongodb://localhost:27001,localhost:27002/casbin?replicaSet=rs0'); 52 | 53 | assert.isFunction(MongooseAdapter.newAdapter); 54 | assert.isFunction(MongooseAdapter.newFilteredAdapter); 55 | assert.isFunction(MongooseAdapter.newSyncedAdapter); 56 | assert.isFunction(adapter.close); 57 | assert.isFunction(adapter.getSession); 58 | assert.isFunction(adapter.getTransaction); 59 | assert.isFunction(adapter.commitTransaction); 60 | assert.isFunction(adapter.abortTransaction); 61 | assert.isFunction(adapter.abortTransaction); 62 | assert.isFunction(adapter.loadPolicyLine); 63 | assert.isFunction(adapter.loadPolicy); 64 | assert.isFunction(adapter.loadFilteredPolicy); 65 | assert.isFunction(adapter.setFiltered); 66 | assert.isFunction(adapter.setSynced); 67 | assert.isFunction(adapter.isFiltered); 68 | assert.isBoolean(adapter.filtered); 69 | assert.isBoolean(adapter.isSynced); 70 | assert.isFunction(adapter.savePolicyLine); 71 | assert.isFunction(adapter.savePolicy); 72 | assert.isFunction(adapter.addPolicy); 73 | assert.isFunction(adapter.removePolicy); 74 | assert.isFunction(adapter.removeFilteredPolicy); 75 | assert.isFunction(adapter.getCasbinRule); 76 | }); 77 | 78 | it('Should use default collection name when not provided', async () => { 79 | const adapter = new MongooseAdapter('mongodb://localhost:27001/casbin'); 80 | const casbinRule = adapter.getCasbinRule(); 81 | 82 | assert.equal(casbinRule.schema.options.collection, 'casbin_rule'); 83 | 84 | await adapter.close(); 85 | }); 86 | 87 | it('Should use custom collection name when provided', async () => { 88 | const adapter = new MongooseAdapter('mongodb://localhost:27001/casbin', {}, { collectionName: 'casbinRule' }); 89 | const casbinRule = adapter.getCasbinRule(); 90 | 91 | assert.equal(casbinRule.schema.options.collection, 'casbinRule'); 92 | 93 | await adapter.close(); 94 | }); 95 | 96 | it('Should use custom collection name via newAdapter', async () => { 97 | const adapter = await MongooseAdapter.newAdapter('mongodb://localhost:27001/casbin', {}, { collectionName: 'customCasbinRules' }); 98 | const casbinRule = adapter.getCasbinRule(); 99 | 100 | assert.equal(casbinRule.schema.options.collection, 'customCasbinRules'); 101 | 102 | await adapter.close(); 103 | }); 104 | }); 105 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # [5.6.0](https://github.com/node-casbin/mongoose-adapter/compare/v5.5.0...v5.6.0) (2025-12-09) 2 | 3 | 4 | ### Features 5 | 6 | * add configurable collection name via adapterOptions ([7db67fa](https://github.com/node-casbin/mongoose-adapter/commit/7db67fa18c1951153cba61f35ec9daff6e827a5b)) 7 | 8 | # [5.5.0](https://github.com/node-casbin/mongoose-adapter/compare/v5.4.0...v5.5.0) (2025-12-09) 9 | 10 | 11 | ### Features 12 | 13 | * fix duplicate CI runs on pull requests ([#83](https://github.com/node-casbin/mongoose-adapter/issues/83)) ([cd799f7](https://github.com/node-casbin/mongoose-adapter/commit/cd799f7d477c1af37e4f4955c80bb7850e7cdab9)) 14 | * upgrade CI scripts' Node.js version to 20 and 22 ([#85](https://github.com/node-casbin/mongoose-adapter/issues/85)) ([ed25ea8](https://github.com/node-casbin/mongoose-adapter/commit/ed25ea87e1ed06b8a9beec858c3d55d5d0374ee9)) 15 | 16 | # [5.4.0](https://github.com/node-casbin/mongoose-adapter/compare/v5.3.1...v5.4.0) (2025-08-15) 17 | 18 | 19 | ### Features 20 | 21 | * improve README badges ([f703392](https://github.com/node-casbin/mongoose-adapter/commit/f7033927535eeb637cb01dc63dc37b50f6d39676)) 22 | * upgrade mongoose to 8.1.0 and casbin to 5.28.0 ([#76](https://github.com/node-casbin/mongoose-adapter/issues/76)) ([78f5a6a](https://github.com/node-casbin/mongoose-adapter/commit/78f5a6aba836977cef87fa3e0be2d1be123c56a5)) 23 | 24 | ## [5.3.1](https://github.com/node-casbin/mongoose-adapter/compare/v5.3.0...v5.3.1) (2023-08-06) 25 | 26 | 27 | ### Bug Fixes 28 | 29 | * fix broken links ([#74](https://github.com/node-casbin/mongoose-adapter/issues/74)) ([160f44c](https://github.com/node-casbin/mongoose-adapter/commit/160f44c79452ae939865ddc5de116983c9fcc340)) 30 | 31 | # [5.3.0](https://github.com/node-casbin/mongoose-adapter/compare/v5.2.0...v5.3.0) (2023-07-14) 32 | 33 | 34 | ### Features 35 | 36 | * update mongoose dependency to 7.3.4 ([#73](https://github.com/node-casbin/mongoose-adapter/issues/73)) ([bbc7953](https://github.com/node-casbin/mongoose-adapter/commit/bbc79536d6abf5aca92bd83e601a457104f0b02a)) 37 | 38 | # [5.2.0](https://github.com/node-casbin/mongoose-adapter/compare/v5.1.1...v5.2.0) (2023-04-21) 39 | 40 | 41 | ### Features 42 | 43 | * enable mongoose timestamps for casbin rule model via adapter options ([#71](https://github.com/node-casbin/mongoose-adapter/issues/71)) ([3dd8862](https://github.com/node-casbin/mongoose-adapter/commit/3dd8862f8eb452adc1365c96df55125561358bb1)) 44 | 45 | ## [5.1.1](https://github.com/node-casbin/mongoose-adapter/compare/v5.1.0...v5.1.1) (2023-04-19) 46 | 47 | 48 | ### Bug Fixes 49 | 50 | * fix multiple adapter ([#68](https://github.com/node-casbin/mongoose-adapter/issues/68)) ([49e69bc](https://github.com/node-casbin/mongoose-adapter/commit/49e69bc2f526fdb42b7410a04173c6b4c58bb635)) 51 | 52 | # [5.1.0](https://github.com/node-casbin/mongoose-adapter/compare/v5.0.0...v5.1.0) (2022-03-21) 53 | 54 | 55 | ### Bug Fixes 56 | 57 | * format issues ([d653519](https://github.com/node-casbin/mongoose-adapter/commit/d653519ec3cfc8b1f81d2a061dbb86df1a4df9c3)) 58 | * token parsing issues if token contains delimeter ([cd695a6](https://github.com/node-casbin/mongoose-adapter/commit/cd695a68f7f45faaae065d4e37c7d4593f7d09b9)) 59 | * update lock file ([203cc98](https://github.com/node-casbin/mongoose-adapter/commit/203cc98d9db46e10319f89ea6ab3affe98c2098b)) 60 | 61 | 62 | ### Features 63 | 64 | * add postinstall script ([af93ec8](https://github.com/node-casbin/mongoose-adapter/commit/af93ec8025f10bd761b47c276a841e368f61bc1a)) 65 | * check if the word is already wrapped in quotes ([d31166e](https://github.com/node-casbin/mongoose-adapter/commit/d31166e3fd8f67eb6ffcff475a68916f61ce7f60)) 66 | 67 | # [5.0.0](https://github.com/node-casbin/mongoose-adapter/compare/v4.0.1...v5.0.0) (2022-03-13) 68 | 69 | 70 | ### Bug Fixes 71 | 72 | * change p_type to ptype ([#61](https://github.com/node-casbin/mongoose-adapter/issues/61)) ([1167bed](https://github.com/node-casbin/mongoose-adapter/commit/1167bed29efc618f09fef7b7c98d8ff81520369f)) 73 | 74 | 75 | ### BREAKING CHANGES 76 | 77 | * we will finally move to `ptype`, as discussed one year ago: https://github.com/pycasbin/sqlalchemy-adapter/issues/26#issuecomment-769799410 . It is also officially documented in the official site: https://casbin.org/docs/adapters/ 78 | 79 | Co-authored-by: Shivansh Yadav 80 | 81 | ## [4.0.1](https://github.com/node-casbin/mongoose-adapter/compare/v4.0.0...v4.0.1) (2022-01-31) 82 | 83 | 84 | ### Bug Fixes 85 | 86 | * **adapter:** expose mongoose instance as public property ([#54](https://github.com/node-casbin/mongoose-adapter/issues/54)) ([31e6ef9](https://github.com/node-casbin/mongoose-adapter/commit/31e6ef9f81aebba385d0b7a0e66960c23e316c4f)) 87 | 88 | # [4.0.0](https://github.com/node-casbin/mongoose-adapter/compare/v3.1.1...v4.0.0) (2022-01-29) 89 | 90 | 91 | ### Features 92 | 93 | * upgrade Mongoose ([#52](https://github.com/node-casbin/mongoose-adapter/issues/52)) ([fb53794](https://github.com/node-casbin/mongoose-adapter/commit/fb5379432397710a27570b116ea3f7459f4bd3b6)) 94 | 95 | 96 | ### BREAKING CHANGES 97 | 98 | * upgrade to Mongoose 6.x and drop Node 10 support 99 | 100 | ## [3.1.1](https://github.com/node-casbin/mongoose-adapter/compare/v3.1.0...v3.1.1) (2021-08-28) 101 | 102 | 103 | ### Bug Fixes 104 | 105 | * fix wrong action with empty string ([#47](https://github.com/node-casbin/mongoose-adapter/issues/47)) ([f51fdde](https://github.com/node-casbin/mongoose-adapter/commit/f51fdde975df95a33c0b9bbcc8fdcf64b7af73a2)) 106 | 107 | # [3.1.0](https://github.com/node-casbin/mongoose-adapter/compare/v3.0.1...v3.1.0) (2021-08-03) 108 | 109 | 110 | ### Features 111 | 112 | * implement UpdatableAdapter interface ([#49](https://github.com/node-casbin/mongoose-adapter/issues/49)) ([131a446](https://github.com/node-casbin/mongoose-adapter/commit/131a446b813b202d322ac0d0fc45d436e34832ca)) 113 | 114 | ## [3.0.1](https://github.com/node-casbin/mongoose-adapter/compare/v3.0.0...v3.0.1) (2021-04-27) 115 | 116 | 117 | ### Bug Fixes 118 | 119 | * no longer support legacy require ([5b09912](https://github.com/node-casbin/mongoose-adapter/commit/5b09912a693a3cf6442d640fe4031938a373c820)) 120 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /src/adapter.ts: -------------------------------------------------------------------------------- 1 | // Copyright 2019 The elastic.io team (http://elastic.io). All Rights Reserved. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | import { BatchAdapter, FilteredAdapter, Helper, logPrint, Model, UpdatableAdapter } from 'casbin'; 16 | import { 17 | ClientSession, 18 | Connection, 19 | ConnectOptions, 20 | createConnection, 21 | FilterQuery, 22 | Model as MongooseModel 23 | } from 'mongoose'; 24 | import { AdapterError, InvalidAdapterTypeError } from './errors'; 25 | import { collectionName, IModel, modelName, schema } from './model'; 26 | 27 | export interface MongooseAdapterOptions { 28 | filtered?: boolean; 29 | synced?: boolean; 30 | autoAbort?: boolean; 31 | autoCommit?: boolean; 32 | timestamps?: boolean; 33 | collectionName?: string; 34 | } 35 | 36 | export interface policyLine { 37 | ptype?: string; 38 | v0?: string; 39 | v1?: string; 40 | v2?: string; 41 | v3?: string; 42 | v4?: string; 43 | v5?: string; 44 | } 45 | 46 | export interface sessionOption { 47 | session?: ClientSession; 48 | } 49 | 50 | /** 51 | * Implements a policy adapter for casbin with MongoDB support. 52 | * 53 | * @class 54 | */ 55 | export class MongooseAdapter implements BatchAdapter, FilteredAdapter, UpdatableAdapter { 56 | public connection?: Connection; 57 | 58 | private filtered: boolean; 59 | private isSynced: boolean; 60 | private uri: string; 61 | private options?: ConnectOptions; 62 | private autoAbort: boolean; 63 | private autoCommit: boolean; 64 | private session: ClientSession; 65 | private casbinRule: MongooseModel; 66 | 67 | /** 68 | * Creates a new instance of mongoose adapter for casbin. 69 | * It does not wait for successfull connection to MongoDB. 70 | * So, if you want to have a possibility to wait until connection successful, use newAdapter instead. 71 | * 72 | * @constructor 73 | * @param {String} uri Mongo URI where casbin rules must be persisted 74 | * @param {Object} [options={}] Additional options to pass on to mongoose client 75 | * @param {Object} [adapterOptions={}] adapterOptions additional adapter options 76 | * @example 77 | * const adapter = new MongooseAdapter('MONGO_URI'); 78 | * const adapter = new MongooseAdapter('MONGO_URI', { mongoose_options: 'here' }) 79 | */ 80 | constructor(uri: string, options?: ConnectOptions, adapterOptions?: MongooseAdapterOptions) { 81 | if (!uri) { 82 | throw new AdapterError('You must provide Mongo URI to connect to!'); 83 | } 84 | 85 | // by default, adapter is not filtered 86 | this.filtered = false; 87 | this.isSynced = false; 88 | this.autoAbort = false; 89 | this.uri = uri; 90 | this.options = options; 91 | this.connection = createConnection(this.uri, this.options); 92 | const customCollectionName = adapterOptions?.collectionName || collectionName; 93 | this.casbinRule = this.connection.model( 94 | modelName, 95 | schema(adapterOptions?.timestamps, customCollectionName), 96 | customCollectionName 97 | ); 98 | } 99 | 100 | /** 101 | * Creates a new instance of mongoose adapter for casbin. 102 | * Instead of constructor, it does wait for successfull connection to MongoDB. 103 | * Preferable way to construct an adapter instance, is to use this static method. 104 | * 105 | * @static 106 | * @param {String} uri Mongo URI where casbin rules must be persisted 107 | * @param {Object} [options={}] Additional options to pass on to mongoose client 108 | * @param {Object} [adapterOptions={}] Additional options to pass on to adapter 109 | * @example 110 | * const adapter = await MongooseAdapter.newAdapter('MONGO_URI'); 111 | * const adapter = await MongooseAdapter.newAdapter('MONGO_URI', { mongoose_options: 'here' }); 112 | */ 113 | static async newAdapter( 114 | uri: string, 115 | options?: ConnectOptions, 116 | adapterOptions: MongooseAdapterOptions = {} 117 | ) { 118 | const adapter = new MongooseAdapter(uri, options, adapterOptions); 119 | const { 120 | filtered = false, 121 | synced = false, 122 | autoAbort = false, 123 | autoCommit = false 124 | } = adapterOptions; 125 | adapter.setFiltered(filtered); 126 | adapter.setSynced(synced); 127 | adapter.setAutoAbort(autoAbort); 128 | adapter.setAutoCommit(autoCommit); 129 | return adapter; 130 | } 131 | 132 | /** 133 | * Creates a new instance of mongoose adapter for casbin. 134 | * It does the same as newAdapter, but it also sets a flag that this adapter is in filtered state. 135 | * That way, casbin will not call loadPolicy() automatically. 136 | * 137 | * @static 138 | * @param {String} uri Mongo URI where casbin rules must be persisted 139 | * @param {Object} [options] Additional options to pass on to mongoose client 140 | * @example 141 | * const adapter = await MongooseAdapter.newFilteredAdapter('MONGO_URI'); 142 | * const adapter = await MongooseAdapter.newFilteredAdapter('MONGO_URI', { mongoose_options: 'here' }); 143 | */ 144 | static async newFilteredAdapter(uri: string, options?: ConnectOptions) { 145 | const adapter = await MongooseAdapter.newAdapter(uri, options, { 146 | filtered: true 147 | }); 148 | return adapter; 149 | } 150 | 151 | /** 152 | * Creates a new instance of mongoose adapter for casbin. 153 | * It does the same as newAdapter, but it checks wether database is a replica set. If it is, it enables 154 | * transactions for the adapter. 155 | * Transactions are never commited automatically. You have to use commitTransaction to add pending changes. 156 | * 157 | * @static 158 | * @param {String} uri Mongo URI where casbin rules must be persisted 159 | * @param {Object} [options={}] Additional options to pass on to mongoose client 160 | * @param {Boolean} autoAbort Whether to abort transactions on Error automatically 161 | * @param autoCommit 162 | * @example 163 | * const adapter = await MongooseAdapter.newFilteredAdapter('MONGO_URI'); 164 | * const adapter = await MongooseAdapter.newFilteredAdapter('MONGO_URI', { mongoose_options: 'here' }); 165 | */ 166 | static async newSyncedAdapter( 167 | uri: string, 168 | options?: ConnectOptions, 169 | autoAbort: boolean = true, 170 | autoCommit = true 171 | ) { 172 | return await MongooseAdapter.newAdapter(uri, options, { 173 | synced: true, 174 | autoAbort, 175 | autoCommit 176 | }); 177 | } 178 | 179 | /** 180 | * Switch adapter to (non)filtered state. 181 | * Casbin uses this flag to determine if it should load the whole policy from DB or not. 182 | * 183 | * @param {Boolean} [enable=true] Flag that represents the current state of adapter (filtered or not) 184 | */ 185 | setFiltered(enable: boolean = true) { 186 | this.filtered = enable; 187 | } 188 | 189 | /** 190 | * isFiltered determines whether the filtered model is enabled for the adapter. 191 | * @returns {boolean} 192 | */ 193 | isFiltered(): boolean { 194 | return this.filtered; 195 | } 196 | 197 | /** 198 | * SyncedAdapter: Switch adapter to (non)synced state. 199 | * This enables mongoDB transactions when loading and saving policies to DB. 200 | * 201 | * @param {Boolean} [synced=true] Flag that represents the current state of adapter (filtered or not) 202 | */ 203 | setSynced(synced: boolean = true) { 204 | this.isSynced = synced; 205 | } 206 | 207 | /** 208 | * SyncedAdapter: Automatically abort on Error. 209 | * When enabled, functions will automatically abort on error 210 | * 211 | * @param {Boolean} [abort=true] Flag that represents if automatic abort should be enabled or not 212 | */ 213 | setAutoAbort(abort: boolean = true) { 214 | if (this.isSynced) this.autoAbort = abort; 215 | } 216 | 217 | /** 218 | * SyncedAdapter: Automatically commit after each addition. 219 | * When enabled, functions will automatically commit after function has finished 220 | * 221 | * @param {Boolean} [commit=true] Flag that represents if automatic commit should be enabled or not 222 | */ 223 | setAutoCommit(commit: boolean = true) { 224 | if (this.isSynced) this.autoCommit = commit; 225 | } 226 | 227 | /** 228 | * SyncedAdapter: Gets active session or starts a new one. Sessions are used to handle transactions. 229 | */ 230 | async getSession(): Promise { 231 | if (this.isSynced) { 232 | return this.session && this.session.inTransaction() 233 | ? this.session 234 | : this.connection!.startSession(); 235 | } else 236 | throw new InvalidAdapterTypeError( 237 | 'Transactions are only supported by SyncedAdapter. See newSyncedAdapter' 238 | ); 239 | } 240 | 241 | /** 242 | * SyncedAdapter: Sets current session to specific one. Do not use this unless you know what you are doing. 243 | */ 244 | async setSession(session: ClientSession) { 245 | if (this.isSynced) { 246 | this.session = session; 247 | } else { 248 | throw new InvalidAdapterTypeError( 249 | 'Sessions are only supported by SyncedAdapter. See newSyncedAdapter' 250 | ); 251 | } 252 | } 253 | 254 | /** 255 | * SyncedAdapter: Gets active transaction or starts a new one. Transaction must be closed before changes are done 256 | * to the database. See: commitTransaction, abortTransaction 257 | * @returns {Promise} Returns a session with active transaction 258 | */ 259 | async getTransaction(): Promise { 260 | if (this.isSynced) { 261 | const session = await this.getSession(); 262 | if (!session.inTransaction()) { 263 | await this.casbinRule.createCollection(); 264 | await session.startTransaction(); 265 | logPrint( 266 | 'Transaction started. To commit changes use adapter.commitTransaction() or to abort use adapter.abortTransaction()' 267 | ); 268 | } 269 | return session; 270 | } else 271 | throw new InvalidAdapterTypeError( 272 | 'Transactions are only supported by SyncedAdapter. See newSyncedAdapter' 273 | ); 274 | } 275 | 276 | /** 277 | * SyncedAdapter: Commits active transaction. Documents are not saved before this function is used. 278 | * Transaction closes after the use of this function. 279 | * @returns {Promise} 280 | */ 281 | async commitTransaction(): Promise { 282 | if (this.isSynced) { 283 | const session = await this.getSession(); 284 | await session.commitTransaction(); 285 | } else 286 | throw new InvalidAdapterTypeError( 287 | 'Transactions are only supported by SyncedAdapter. See newSyncedAdapter' 288 | ); 289 | } 290 | 291 | /** 292 | * SyncedAdapter: Aborts active transaction. All Document changes within this transaction are reverted. 293 | * Transaction closes after the use of this function. 294 | * @returns {Promise} 295 | */ 296 | async abortTransaction(): Promise { 297 | if (this.isSynced) { 298 | const session = await this.getSession(); 299 | await session.abortTransaction(); 300 | logPrint('Transaction aborted'); 301 | } else 302 | throw new InvalidAdapterTypeError( 303 | 'Transactions are only supported by SyncedAdapter. See newSyncedAdapter' 304 | ); 305 | } 306 | 307 | /** 308 | * Loads one policy rule into casbin model. 309 | * This method is used by casbin and should not be called by user. 310 | * 311 | * @param {Object} line Record with one policy rule from MongoDB 312 | * @param {Object} model Casbin model to which policy rule must be loaded 313 | */ 314 | loadPolicyLine(line: policyLine, model: Model) { 315 | let lineText = `${line.ptype!}`; 316 | 317 | for (const word of [line.v0, line.v1, line.v2, line.v3, line.v4, line.v5]) { 318 | if (word !== undefined) { 319 | let wrappedWord = /^".*"$/.test(word) ? word : `"${word}"`; 320 | lineText = `${lineText},${wrappedWord}`; 321 | } else { 322 | break; 323 | } 324 | } 325 | 326 | if (lineText) { 327 | Helper.loadPolicyLine(lineText, model); 328 | } 329 | } 330 | 331 | /** 332 | * Implements the process of loading policy from database into enforcer. 333 | * This method is used by casbin and should not be called by user. 334 | * 335 | * @param {Model} model Model instance from enforcer 336 | * @returns {Promise} 337 | */ 338 | async loadPolicy(model: Model): Promise { 339 | return this.loadFilteredPolicy(model, null); 340 | } 341 | 342 | /** 343 | * Loads partial policy based on filter criteria. 344 | * This method is used by casbin and should not be called by user. 345 | * 346 | * @param {Model} model Enforcer model 347 | * @param {Object} [filter] MongoDB filter to query 348 | */ 349 | async loadFilteredPolicy(model: Model, filter: FilterQuery | null) { 350 | if (filter) { 351 | this.setFiltered(true); 352 | } else { 353 | this.setFiltered(false); 354 | } 355 | const options: sessionOption = {}; 356 | if (this.isSynced) options.session = await this.getTransaction(); 357 | 358 | const lines = await this.casbinRule.find(filter || {}, null, options).lean(); 359 | 360 | this.autoCommit && options.session && (await options.session.commitTransaction()); 361 | for (const line of lines) { 362 | this.loadPolicyLine(line, model); 363 | } 364 | } 365 | 366 | /** 367 | * Generates one policy rule ready to be saved into MongoDB. 368 | * This method is used by casbin to generate Mongoose Model Object for single policy 369 | * and should not be called by user. 370 | * 371 | * @param {String} pType Policy type to save into MongoDB 372 | * @param {Array} rule An array which consists of policy rule elements to store 373 | * @returns {IModel} Returns a created CasbinRule record for MongoDB 374 | */ 375 | savePolicyLine(pType: string, rule: string[]): IModel { 376 | const model = new this.casbinRule({ ptype: pType }); 377 | 378 | if (rule.length > 0) { 379 | model.v0 = rule[0]; 380 | } 381 | 382 | if (rule.length > 1) { 383 | model.v1 = rule[1]; 384 | } 385 | 386 | if (rule.length > 2) { 387 | model.v2 = rule[2]; 388 | } 389 | 390 | if (rule.length > 3) { 391 | model.v3 = rule[3]; 392 | } 393 | 394 | if (rule.length > 4) { 395 | model.v4 = rule[4]; 396 | } 397 | 398 | if (rule.length > 5) { 399 | model.v5 = rule[5]; 400 | } 401 | 402 | return model; 403 | } 404 | 405 | /** 406 | * Implements the process of saving policy from enforcer into database. 407 | * If you are using replica sets with mongo, this function will use mongo 408 | * transaction, so every line in the policy needs tosucceed for this to 409 | * take effect. 410 | * This method is used by casbin and should not be called by user. 411 | * 412 | * @param {Model} model Model instance from enforcer 413 | * @returns {Promise} 414 | */ 415 | async savePolicy(model: Model) { 416 | const options: sessionOption = {}; 417 | if (this.isSynced) options.session = await this.getTransaction(); 418 | 419 | try { 420 | const lines: IModel[] = []; 421 | const policyRuleAST = model.model.get('p') instanceof Map ? model.model.get('p')! : new Map(); 422 | const groupingPolicyAST = 423 | model.model.get('g') instanceof Map ? model.model.get('g')! : new Map(); 424 | 425 | for (const [ptype, ast] of policyRuleAST) { 426 | for (const rule of ast.policy) { 427 | lines.push(this.savePolicyLine(ptype, rule)); 428 | } 429 | } 430 | 431 | for (const [ptype, ast] of groupingPolicyAST) { 432 | for (const rule of ast.policy) { 433 | lines.push(this.savePolicyLine(ptype, rule)); 434 | } 435 | } 436 | 437 | await this.casbinRule.collection.insertMany(lines, options); 438 | 439 | this.autoCommit && options.session && (await options.session.commitTransaction()); 440 | } catch (err) { 441 | this.autoAbort && options.session && (await options.session.abortTransaction()); 442 | console.error(err); 443 | return false; 444 | } 445 | 446 | return true; 447 | } 448 | 449 | /** 450 | * Implements the process of adding policy rule. 451 | * This method is used by casbin and should not be called by user. 452 | * 453 | * @param {String} sec Section of the policy 454 | * @param {String} pType Type of the policy (e.g. "p" or "g") 455 | * @param {Array} rule Policy rule to add into enforcer 456 | * @returns {Promise} 457 | */ 458 | async addPolicy(sec: string, pType: string, rule: string[]): Promise { 459 | const options: sessionOption = {}; 460 | try { 461 | if (this.isSynced) options.session = await this.getTransaction(); 462 | 463 | const line = this.savePolicyLine(pType, rule); 464 | await line.save(options); 465 | 466 | this.autoCommit && options.session && (await options.session.commitTransaction()); 467 | } catch (err) { 468 | this.autoAbort && options.session && (await options.session.abortTransaction()); 469 | throw err; 470 | } 471 | } 472 | 473 | /** 474 | * Implements the process of adding a list of policy rules. 475 | * This method is used by casbin and should not be called by user. 476 | * 477 | * @param {String} sec Section of the policy 478 | * @param {String} pType Type of the policy (e.g. "p" or "g") 479 | * @param {Array} rules Policy rule to add into enforcer 480 | * @returns {Promise} 481 | */ 482 | async addPolicies(sec: string, pType: string, rules: Array): Promise { 483 | const options: sessionOption = {}; 484 | if (this.isSynced) options.session = await this.getTransaction(); 485 | else 486 | throw new InvalidAdapterTypeError( 487 | 'addPolicies is only supported by SyncedAdapter. See newSyncedAdapter' 488 | ); 489 | try { 490 | const promises = rules.map(async (rule) => this.addPolicy(sec, pType, rule)); 491 | await Promise.all(promises); 492 | 493 | this.autoCommit && options.session && (await options.session.commitTransaction()); 494 | } catch (err) { 495 | this.autoAbort && options.session && (await options.session.abortTransaction()); 496 | throw err; 497 | } 498 | } 499 | 500 | /** 501 | * Implements the process of updating policy rule. 502 | * This method is used by casbin and should not be called by user. 503 | * 504 | * @param {String} sec Section of the policy 505 | * @param {String} pType Type of the policy (e.g. "p" or "g") 506 | * @param {Array} oldRule Policy rule to remove from enforcer 507 | * @param {Array} newRule Policy rule to add into enforcer 508 | * @returns {Promise} 509 | */ 510 | async updatePolicy( 511 | sec: string, 512 | pType: string, 513 | oldRule: string[], 514 | newRule: string[] 515 | ): Promise { 516 | const options: sessionOption = {}; 517 | try { 518 | if (this.isSynced) options.session = await this.getTransaction(); 519 | const { ptype, v0, v1, v2, v3, v4, v5 } = this.savePolicyLine(pType, oldRule); 520 | const newRuleLine = this.savePolicyLine(pType, newRule); 521 | const newModel = { 522 | ptype: newRuleLine.ptype, 523 | v0: newRuleLine.v0, 524 | v1: newRuleLine.v1, 525 | v2: newRuleLine.v2, 526 | v3: newRuleLine.v3, 527 | v4: newRuleLine.v4, 528 | v5: newRuleLine.v5 529 | }; 530 | 531 | await this.casbinRule.updateOne({ ptype, v0, v1, v2, v3, v4, v5 }, newModel, options); 532 | 533 | this.autoCommit && options.session && (await options.session.commitTransaction()); 534 | } catch (err) { 535 | this.autoAbort && options.session && (await options.session.abortTransaction()); 536 | throw err; 537 | } 538 | } 539 | 540 | /** 541 | * Implements the process of removing a list of policy rules. 542 | * This method is used by casbin and should not be called by user. 543 | * 544 | * @param {String} sec Section of the policy 545 | * @param {String} pType Type of the policy (e.g. "p" or "g") 546 | * @param {Array} rule Policy rule to remove from enforcer 547 | * @returns {Promise} 548 | */ 549 | async removePolicy(sec: string, pType: string, rule: string[]): Promise { 550 | const options: sessionOption = {}; 551 | try { 552 | if (this.isSynced) options.session = await this.getTransaction(); 553 | 554 | const { ptype, v0, v1, v2, v3, v4, v5 } = this.savePolicyLine(pType, rule); 555 | 556 | await this.casbinRule.deleteMany({ ptype, v0, v1, v2, v3, v4, v5 }, options); 557 | 558 | this.autoCommit && options.session && (await options.session.commitTransaction()); 559 | } catch (err) { 560 | this.autoAbort && options.session && (await options.session.abortTransaction()); 561 | throw err; 562 | } 563 | } 564 | 565 | /** 566 | * Implements the process of removing a policyList rules. 567 | * This method is used by casbin and should not be called by user. 568 | * 569 | * @param {String} sec Section of the policy 570 | * @param {String} pType Type of the policy (e.g. "p" or "g") 571 | * @param {Array} rules Policy rule to remove from enforcer 572 | * @returns {Promise} 573 | */ 574 | async removePolicies(sec: string, pType: string, rules: Array): Promise { 575 | const options: sessionOption = {}; 576 | try { 577 | if (this.isSynced) options.session = await this.getTransaction(); 578 | else 579 | throw new InvalidAdapterTypeError( 580 | 'removePolicies is only supported by SyncedAdapter. See newSyncedAdapter' 581 | ); 582 | 583 | const promises = rules.map(async (rule) => this.removePolicy(sec, pType, rule)); 584 | await Promise.all(promises); 585 | 586 | this.autoCommit && options.session && (await options.session.commitTransaction()); 587 | } catch (err) { 588 | this.autoAbort && options.session && (await options.session.abortTransaction()); 589 | throw err; 590 | } 591 | } 592 | 593 | /** 594 | * Implements the process of removing policy rules. 595 | * This method is used by casbin and should not be called by user. 596 | * 597 | * @param {String} sec Section of the policy 598 | * @param {String} pType Type of the policy (e.g. "p" or "g") 599 | * @param {Number} fieldIndex Index of the field to start filtering from 600 | * @param {...String} fieldValues Policy rule to match when removing (starting from fieldIndex) 601 | * @returns {Promise} 602 | */ 603 | async removeFilteredPolicy( 604 | sec: string, 605 | pType: string, 606 | fieldIndex: number, 607 | ...fieldValues: string[] 608 | ): Promise { 609 | const options: sessionOption = {}; 610 | try { 611 | if (this.isSynced) options.session = await this.getTransaction(); 612 | const where: any = pType ? { ptype: pType } : {}; 613 | 614 | if (fieldIndex <= 0 && fieldIndex + fieldValues.length > 0 && fieldValues[0 - fieldIndex]) { 615 | if (pType === 'g') { 616 | where.$or = [{ v0: fieldValues[0 - fieldIndex] }, { v1: fieldValues[0 - fieldIndex] }]; 617 | } else { 618 | where.v0 = fieldValues[0 - fieldIndex]; 619 | } 620 | } 621 | 622 | if (fieldIndex <= 1 && fieldIndex + fieldValues.length > 1 && fieldValues[1 - fieldIndex]) { 623 | where.v1 = fieldValues[1 - fieldIndex]; 624 | } 625 | 626 | if (fieldIndex <= 2 && fieldIndex + fieldValues.length > 2 && fieldValues[2 - fieldIndex]) { 627 | where.v2 = fieldValues[2 - fieldIndex]; 628 | } 629 | 630 | if (fieldIndex <= 3 && fieldIndex + fieldValues.length > 3 && fieldValues[3 - fieldIndex]) { 631 | where.v3 = fieldValues[3 - fieldIndex]; 632 | } 633 | 634 | if (fieldIndex <= 4 && fieldIndex + fieldValues.length > 4 && fieldValues[4 - fieldIndex]) { 635 | where.v4 = fieldValues[4 - fieldIndex]; 636 | } 637 | 638 | if (fieldIndex <= 5 && fieldIndex + fieldValues.length > 5 && fieldValues[5 - fieldIndex]) { 639 | where.v5 = fieldValues[5 - fieldIndex]; 640 | } 641 | 642 | await this.casbinRule.deleteMany(where, options); 643 | 644 | this.autoCommit && options.session && (await options.session.commitTransaction()); 645 | } catch (err) { 646 | this.autoAbort && options.session && (await options.session.abortTransaction()); 647 | throw err; 648 | } 649 | } 650 | 651 | async close() { 652 | if (this.connection) { 653 | if (this.session) await this.session.endSession(); 654 | await this.connection.close(); 655 | } 656 | } 657 | 658 | /** 659 | * Just for testing. 660 | */ 661 | getCasbinRule() { 662 | return this.casbinRule; 663 | } 664 | } 665 | -------------------------------------------------------------------------------- /test/integration/adapter.test.js: -------------------------------------------------------------------------------- 1 | // Copyright 2019 The elastic.io team (http://elastic.io). All Rights Reserved. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | const { assert } = require('chai'); 16 | const sinon = require('sinon'); 17 | const { 18 | createEnforcer, 19 | createAdapter, 20 | createDisconnectedAdapter, 21 | createSyncedAdapter, 22 | basicModel, 23 | basicPolicy, 24 | rbacModel, 25 | rbacPolicy, 26 | rbacDenyDomainModel, 27 | rbacDenyDomainPolicy, 28 | createAdapterWithDBName 29 | } = require('../helpers/helpers'); 30 | const { newEnforcer, Model } = require('casbin'); 31 | const { InvalidAdapterTypeError } = require('../../lib/cjs/errors'); 32 | 33 | // These tests are just smoke tests for get/set policy rules 34 | // We do not need to cover other aspects of casbin, since casbin itself is covered with tests 35 | describe('MongooseAdapter', () => { 36 | beforeEach(async () => { 37 | const enforcer = await createEnforcer(); 38 | const CasbinRule = enforcer.getAdapter().getCasbinRule(); 39 | await CasbinRule.deleteMany(); 40 | }); 41 | 42 | it('Should properly load policy', async () => { 43 | const enforcer = await createEnforcer(); 44 | const CasbinRule = enforcer.getAdapter().getCasbinRule(); 45 | 46 | assert.deepEqual(await enforcer.getPolicy(), []); 47 | 48 | const rules = await CasbinRule.find(); 49 | assert.deepEqual(rules, []); 50 | }); 51 | 52 | it('Should properly store new policy rules', async () => { 53 | const enforcer = await createEnforcer(); 54 | const CasbinRule = enforcer.getAdapter().getCasbinRule(); 55 | 56 | const rulesBefore = await CasbinRule.find(); 57 | assert.deepEqual(rulesBefore, []); 58 | assert.isTrue(await enforcer.addPolicy('sub', 'obj', 'act')); 59 | assert.deepEqual(await enforcer.getPolicy(), [['sub', 'obj', 'act']]); 60 | 61 | const rulesAfter = await CasbinRule.find({ 62 | ptype: 'p', 63 | v0: 'sub', 64 | v1: 'obj', 65 | v2: 'act' 66 | }); 67 | assert.equal(rulesAfter.length, 1); 68 | }); 69 | 70 | it('Should properly add and remove policies', async () => { 71 | const a = await createSyncedAdapter(); 72 | const CasbinRule = a.getCasbinRule(); 73 | 74 | // Because the DB is empty at first, 75 | // so we need to load the policy from the file adapter (.CSV) first. 76 | let e = await newEnforcer(rbacModel, rbacPolicy); 77 | 78 | const rulesBefore = await CasbinRule.find({}); 79 | assert.equal(rulesBefore.length, 0); 80 | 81 | // This is a trick to save the current policy to the DB. 82 | // We can't call e.savePolicy() because the adapter in the enforcer is still the file adapter. 83 | // The current policy means the policy in the Node-Casbin enforcer (aka in memory). 84 | await a.savePolicy(await e.getModel()); 85 | const rulesAfter = await CasbinRule.find({}); 86 | assert.deepEqual( 87 | rulesAfter.map((rule) => [rule.ptype, rule.v0, rule.v1, rule.v2]), 88 | [ 89 | ['p', 'alice', 'data1', 'read'], 90 | ['p', 'bob', 'data2', 'write'], 91 | ['p', 'data2_admin', 'data2', 'read'], 92 | ['p', 'data2_admin', 'data2', 'write'], 93 | ['g', 'alice', 'data2_admin', undefined] 94 | ] 95 | ); 96 | 97 | // Add a single policy to Database 98 | await a.addPolicy('', 'p', ['role', 'res', 'action']); 99 | e = await newEnforcer(rbacModel, a); 100 | assert.deepEqual(await e.getPolicy(), [ 101 | ['alice', 'data1', 'read'], 102 | ['bob', 'data2', 'write'], 103 | ['data2_admin', 'data2', 'read'], 104 | ['data2_admin', 'data2', 'write'], 105 | ['role', 'res', 'action'] 106 | ]); 107 | 108 | // Add a policyList to Database 109 | await a.addPolicies('', 'p', [ 110 | ['role', 'res', 'GET'], 111 | ['role', 'res', 'POST'] 112 | ]); 113 | e = await newEnforcer(rbacModel, a); 114 | 115 | // Clear the current policy. 116 | await e.clearPolicy(); 117 | assert.deepEqual(await e.getPolicy(), []); 118 | 119 | // Load the policy from Database. 120 | await a.loadPolicy(e.getModel()); 121 | assert.includeDeepMembers(await e.getPolicy(), [ 122 | ['alice', 'data1', 'read'], 123 | ['bob', 'data2', 'write'], 124 | ['data2_admin', 'data2', 'read'], 125 | ['data2_admin', 'data2', 'write'], 126 | ['role', 'res', 'action'], 127 | ['role', 'res', 'GET'], 128 | ['role', 'res', 'POST'] 129 | ]); 130 | 131 | // Remove a single policy from Database 132 | await a.removePolicy('', 'p', ['role', 'res', 'action']); 133 | e = await newEnforcer(rbacModel, a); 134 | assert.includeDeepMembers(await e.getPolicy(), [ 135 | ['alice', 'data1', 'read'], 136 | ['bob', 'data2', 'write'], 137 | ['data2_admin', 'data2', 'read'], 138 | ['data2_admin', 'data2', 'write'], 139 | ['role', 'res', 'GET'], 140 | ['role', 'res', 'POST'] 141 | ]); 142 | 143 | // Remove a policylist from Database 144 | await a.removePolicies('', 'p', [ 145 | ['role', 'res', 'GET'], 146 | ['role', 'res', 'POST'] 147 | ]); 148 | e = await newEnforcer(rbacModel, a); 149 | 150 | assert.includeDeepMembers(await e.getPolicy(), [ 151 | ['alice', 'data1', 'read'], 152 | ['bob', 'data2', 'write'], 153 | ['data2_admin', 'data2', 'read'], 154 | ['data2_admin', 'data2', 'write'] 155 | ]); 156 | }); 157 | 158 | it('Add Policies and Remove Policies should not work on normal adapter', async () => { 159 | const a = await createAdapter(); 160 | const CasbinRule = a.getCasbinRule(); 161 | 162 | // Because the DB is empty at first, 163 | // so we need to load the policy from the file adapter (.CSV) first. 164 | let e = await newEnforcer(rbacModel, rbacPolicy); 165 | 166 | const rulesBefore = await CasbinRule.find({}); 167 | assert.equal(rulesBefore.length, 0); 168 | // This is a trick to save the current policy to the DB. 169 | // We can't call e.savePolicy() because the adapter in the enforcer is still the file adapter. 170 | // The current policy means the policy in the Node-Casbin enforcer (aka in memory). 171 | await a.savePolicy(await e.getModel()); 172 | const rulesAfter = await CasbinRule.find({}); 173 | assert.deepEqual( 174 | rulesAfter.map((rule) => [rule.ptype, rule.v0, rule.v1, rule.v2]), 175 | [ 176 | ['p', 'alice', 'data1', 'read'], 177 | ['p', 'bob', 'data2', 'write'], 178 | ['p', 'data2_admin', 'data2', 'read'], 179 | ['p', 'data2_admin', 'data2', 'write'], 180 | ['g', 'alice', 'data2_admin', undefined] 181 | ] 182 | ); 183 | 184 | // Add a single policy to Database 185 | await a.addPolicy('', 'p', ['role', 'res', 'action']); 186 | e = await newEnforcer(rbacModel, a); 187 | assert.deepEqual(await e.getPolicy(), [ 188 | ['alice', 'data1', 'read'], 189 | ['bob', 'data2', 'write'], 190 | ['data2_admin', 'data2', 'read'], 191 | ['data2_admin', 'data2', 'write'], 192 | ['role', 'res', 'action'] 193 | ]); 194 | 195 | // Add policyList to Database 196 | try { 197 | await a.addPolicies('', 'p', [ 198 | ['role', 'res', 'GET'], 199 | ['role', 'res', 'POST'] 200 | ]); 201 | } catch (error) { 202 | assert(error instanceof InvalidAdapterTypeError); 203 | assert.equal( 204 | error.message, 205 | 'addPolicies is only supported by SyncedAdapter. See newSyncedAdapter' 206 | ); 207 | } 208 | 209 | e = await newEnforcer(rbacModel, a); 210 | 211 | // Clear the current policy. 212 | await e.clearPolicy(); 213 | assert.deepEqual(await e.getPolicy(), []); 214 | 215 | // Load the policy from Database. 216 | await a.loadPolicy(e.getModel()); 217 | assert.deepEqual(await e.getPolicy(), [ 218 | ['alice', 'data1', 'read'], 219 | ['bob', 'data2', 'write'], 220 | ['data2_admin', 'data2', 'read'], 221 | ['data2_admin', 'data2', 'write'], 222 | ['role', 'res', 'action'] 223 | ]); 224 | 225 | // Remove a single policy from Database 226 | await a.removePolicy('', 'p', ['role', 'res', 'action']); 227 | e = await newEnforcer(rbacModel, a); 228 | assert.deepEqual(await e.getPolicy(), [ 229 | ['alice', 'data1', 'read'], 230 | ['bob', 'data2', 'write'], 231 | ['data2_admin', 'data2', 'read'], 232 | ['data2_admin', 'data2', 'write'] 233 | ]); 234 | 235 | // Remove a policylist from Database 236 | 237 | try { 238 | await a.removePolicies('', 'p', [ 239 | ['data2_admin', 'datag1712', 'read'], 240 | ['data2_admin', 'data2', 'write'] 241 | ]); 242 | } catch (error) { 243 | assert(error instanceof InvalidAdapterTypeError); 244 | assert.equal( 245 | error.message, 246 | 'removePolicies is only supported by SyncedAdapter. See newSyncedAdapter' 247 | ); 248 | } 249 | e = await newEnforcer(rbacModel, a); 250 | 251 | assert.deepEqual(await e.getPolicy(), [ 252 | ['alice', 'data1', 'read'], 253 | ['bob', 'data2', 'write'], 254 | ['data2_admin', 'data2', 'read'], 255 | ['data2_admin', 'data2', 'write'] 256 | ]); 257 | }); 258 | 259 | it('Should properly store new policy rules from a file', async () => { 260 | const a = await createAdapter(); 261 | const CasbinRule = a.getCasbinRule(); 262 | 263 | // Because the DB is empty at first, 264 | // so we need to load the policy from the file adapter (.CSV) first. 265 | let e = await newEnforcer(rbacModel, rbacPolicy); 266 | 267 | const rulesBefore = await CasbinRule.find({}); 268 | assert.equal(rulesBefore.length, 0); 269 | 270 | // This is a trick to save the current policy to the DB. 271 | // We can't call e.savePolicy() because the adapter in the enforcer is still the file adapter. 272 | // The current policy means the policy in the Node-Casbin enforcer (aka in memory). 273 | await a.savePolicy(await e.getModel()); 274 | const rulesAfter = await CasbinRule.find({}); 275 | assert.deepEqual( 276 | rulesAfter.map((rule) => [rule.ptype, rule.v0, rule.v1, rule.v2]), 277 | [ 278 | ['p', 'alice', 'data1', 'read'], 279 | ['p', 'bob', 'data2', 'write'], 280 | ['p', 'data2_admin', 'data2', 'read'], 281 | ['p', 'data2_admin', 'data2', 'write'], 282 | ['g', 'alice', 'data2_admin', undefined] 283 | ] 284 | ); 285 | 286 | // Clear the current policy. 287 | await e.clearPolicy(); 288 | assert.deepEqual(await e.getPolicy(), []); 289 | 290 | // Load the policy from DB. 291 | await a.loadPolicy(e.getModel()); 292 | assert.deepEqual(await e.getPolicy(), [ 293 | ['alice', 'data1', 'read'], 294 | ['bob', 'data2', 'write'], 295 | ['data2_admin', 'data2', 'read'], 296 | ['data2_admin', 'data2', 'write'] 297 | ]); 298 | 299 | // Note: you don't need to look at the above code 300 | // if you already have a working DB with policy inside. 301 | 302 | // Now the DB has policy, so we can provide a normal use case. 303 | // Create an adapter and an enforcer. 304 | // newEnforcer() will load the policy automatically. 305 | e = await newEnforcer(rbacModel, a); 306 | assert.deepEqual(await e.getPolicy(), [ 307 | ['alice', 'data1', 'read'], 308 | ['bob', 'data2', 'write'], 309 | ['data2_admin', 'data2', 'read'], 310 | ['data2_admin', 'data2', 'write'] 311 | ]); 312 | 313 | // Add policy to DB 314 | await a.addPolicy('', 'p', ['role', 'res', 'action']); 315 | e = await newEnforcer(rbacModel, a); 316 | assert.deepEqual(await e.getPolicy(), [ 317 | ['alice', 'data1', 'read'], 318 | ['bob', 'data2', 'write'], 319 | ['data2_admin', 'data2', 'read'], 320 | ['data2_admin', 'data2', 'write'], 321 | ['role', 'res', 'action'] 322 | ]); 323 | // Remove policy from DB 324 | await a.removePolicy('', 'p', ['role', 'res', 'action']); 325 | e = await newEnforcer(rbacModel, a); 326 | assert.deepEqual(await e.getPolicy(), [ 327 | ['alice', 'data1', 'read'], 328 | ['bob', 'data2', 'write'], 329 | ['data2_admin', 'data2', 'read'], 330 | ['data2_admin', 'data2', 'write'] 331 | ]); 332 | }); 333 | 334 | it('Empty Role Definition should not raise an error', async () => { 335 | const a = await createAdapter(); 336 | const CasbinRule = a.getCasbinRule(); 337 | 338 | // Because the DB is empty at first, 339 | // so we need to load the policy from the file adapter (.CSV) first. 340 | let e = await newEnforcer(basicModel, basicPolicy); 341 | 342 | const rulesBefore = await CasbinRule.find({}); 343 | assert.equal(rulesBefore.length, 0); 344 | 345 | // This is a trick to save the current policy to the DB. 346 | // We can't call e.savePolicy() because the adapter in the enforcer is still the file adapter. 347 | // The current policy means the policy in the Node-Casbin enforcer (aka in memory). 348 | await a.savePolicy(e.getModel()); 349 | const rulesAfter = await CasbinRule.find({}); 350 | assert.deepEqual( 351 | rulesAfter.map((rule) => [rule.ptype, rule.v0, rule.v1, rule.v2]), 352 | [ 353 | ['p', 'alice', 'data1', 'read'], 354 | ['p', 'bob', 'data2', 'write'] 355 | ] 356 | ); 357 | 358 | // Clear the current policy. 359 | e.clearPolicy(); 360 | assert.deepEqual(await e.getPolicy(), []); 361 | 362 | // Load the policy from DB. 363 | await a.loadPolicy(e.getModel()); 364 | assert.deepEqual(await e.getPolicy(), [ 365 | ['alice', 'data1', 'read'], 366 | ['bob', 'data2', 'write'] 367 | ]); 368 | 369 | // Note: you don't need to look at the above code 370 | // if you already have a working DB with policy inside. 371 | 372 | // Now the DB has policy, so we can provide a normal use case. 373 | // Create an adapter and an enforcer. 374 | // newEnforcer() will load the policy automatically. 375 | e = await newEnforcer(basicModel, a); 376 | assert.deepEqual(await e.getPolicy(), [ 377 | ['alice', 'data1', 'read'], 378 | ['bob', 'data2', 'write'] 379 | ]); 380 | 381 | // Add policy to DB 382 | await a.addPolicy('', 'p', ['role', 'res', 'action']); 383 | e = await newEnforcer(basicModel, a); 384 | assert.deepEqual(await e.getPolicy(), [ 385 | ['alice', 'data1', 'read'], 386 | ['bob', 'data2', 'write'], 387 | ['role', 'res', 'action'] 388 | ]); 389 | // Remove policy from DB 390 | await a.removePolicy('', 'p', ['role', 'res', 'action']); 391 | e = await newEnforcer(basicModel, a); 392 | assert.deepEqual(await e.getPolicy(), [ 393 | ['alice', 'data1', 'read'], 394 | ['bob', 'data2', 'write'] 395 | ]); 396 | }); 397 | 398 | it('Empty Policy return false and log an error', async () => { 399 | const a = await createAdapter(); 400 | console.error = sinon.stub(); 401 | assert.isNotOk(await a.savePolicy(new Model())); 402 | assert(console.error.lastCall.firstArg.name, 'MongoError'); 403 | assert(console.error.callCount, 1); 404 | if (console.error.restore) console.error.restore(); 405 | }); 406 | 407 | it('Should not store new policy rules if one of them fails', async () => { 408 | const a = await createAdapter(); 409 | const CasbinRule = a.getCasbinRule(); 410 | 411 | // Because the DB is empty at first, 412 | // so we need to load the policy from the file adapter (.CSV) first. 413 | const e = await newEnforcer(rbacModel, rbacPolicy); 414 | const rulesBefore = await CasbinRule.find({}); 415 | assert.equal(rulesBefore.length, 0); 416 | 417 | // This is a trick to save the current policy to the DB. 418 | // We can't call e.savePolicy() because the adapter in the enforcer is still the file adapter. 419 | // The current policy means the policy in the Node-Casbin enforcer (aka in memory). 420 | e.getModel().model.set('g', {}); 421 | 422 | try { 423 | await a.savePolicy(e.getModel()); 424 | } catch (err) { 425 | if (err instanceof TypeError) { 426 | const rulesAfter = await CasbinRule.find({}); 427 | assert.equal(rulesAfter.length, 0); 428 | } else { 429 | throw err; 430 | } 431 | } 432 | }); 433 | 434 | it('Should properly fail when transaction is set to true', async () => { 435 | try { 436 | await createAdapter(true); 437 | } catch (error) { 438 | assert.equal(error, 'Error: Tried to enable transactions for non-replicaset connection'); 439 | } 440 | }); 441 | 442 | it('Should properly update existing policy rules', async () => { 443 | const enforcer = await createEnforcer(); 444 | const CasbinRule = enforcer.getAdapter().getCasbinRule(); 445 | 446 | const rulesBefore = await CasbinRule.find(); 447 | assert.deepEqual(rulesBefore, []); 448 | assert.isTrue(await enforcer.addPolicy('sub', 'obj', 'act')); 449 | assert.deepEqual(await enforcer.getPolicy(), [['sub', 'obj', 'act']]); 450 | 451 | const rulesAfter = await CasbinRule.find({ 452 | ptype: 'p', 453 | v0: 'sub', 454 | v1: 'obj', 455 | v2: 'act' 456 | }); 457 | assert.equal(rulesAfter.length, 1); 458 | assert.isTrue(await enforcer.updatePolicy(['sub', 'obj', 'act'], ['sub1', 'obj1', 'act1'])); 459 | assert.deepEqual(await enforcer.getPolicy(), [['sub1', 'obj1', 'act1']]); 460 | 461 | const rulesAfterUpdate = await CasbinRule.find({ 462 | ptype: 'p', 463 | v0: 'sub1', 464 | v1: 'obj1', 465 | v2: 'act1' 466 | }); 467 | assert.equal(rulesAfterUpdate.length, 1); 468 | }); 469 | 470 | it('Should properly delete existing policy rules', async () => { 471 | const enforcer = await createEnforcer(); 472 | const CasbinRule = enforcer.getAdapter().getCasbinRule(); 473 | 474 | const rulesBefore = await CasbinRule.find(); 475 | assert.deepEqual(rulesBefore, []); 476 | assert.isTrue(await enforcer.addPolicy('sub', 'obj', 'act')); 477 | assert.deepEqual(await enforcer.getPolicy(), [['sub', 'obj', 'act']]); 478 | 479 | const rulesAfter = await CasbinRule.find({ 480 | ptype: 'p', 481 | v0: 'sub', 482 | v1: 'obj', 483 | v2: 'act' 484 | }); 485 | assert.equal(rulesAfter.length, 1); 486 | assert.isTrue(await enforcer.removePolicy('sub', 'obj', 'act')); 487 | assert.deepEqual(await enforcer.getPolicy(), []); 488 | 489 | const rulesAfterDelete = await CasbinRule.find({ 490 | ptype: 'p', 491 | v0: 'sub', 492 | v1: 'obj', 493 | v2: 'act' 494 | }); 495 | assert.equal(rulesAfterDelete.length, 0); 496 | }); 497 | 498 | it('Should remove related policy rules via a filter', async () => { 499 | const a = await createAdapter(); 500 | const CasbinRule = a.getCasbinRule(); 501 | // Because the DB is empty at first, 502 | // so we need to load the policy from the file adapter (.CSV) first. 503 | let e = await newEnforcer(rbacModel, rbacPolicy); 504 | 505 | const rulesBefore = await CasbinRule.find({}); 506 | assert.equal(rulesBefore.length, 0); 507 | 508 | // This is a trick to save the current policy to the DB. 509 | // We can't call e.savePolicy() because the adapter in the enforcer is still the file adapter. 510 | // The current policy means the policy in the Node-Casbin enforcer (aka in memory). 511 | await a.savePolicy(e.getModel()); 512 | let rulesAfter = await CasbinRule.find({}); 513 | assert.deepEqual( 514 | rulesAfter.map((rule) => [rule.ptype, rule.v0, rule.v1, rule.v2]), 515 | [ 516 | ['p', 'alice', 'data1', 'read'], 517 | ['p', 'bob', 'data2', 'write'], 518 | ['p', 'data2_admin', 'data2', 'read'], 519 | ['p', 'data2_admin', 'data2', 'write'], 520 | ['g', 'alice', 'data2_admin', undefined] 521 | ] 522 | ); 523 | 524 | // Remove 'data2_admin' related policy rules via a filter. 525 | // Two rules: {'data2_admin', 'data2', 'read'}, {'data2_admin', 'data2', 'write'} are deleted. 526 | await a.removeFilteredPolicy(undefined, undefined, 0, 'data2_admin'); 527 | rulesAfter = await CasbinRule.find({}); 528 | assert.deepEqual( 529 | rulesAfter.map((rule) => [rule.ptype, rule.v0, rule.v1, rule.v2]), 530 | [ 531 | ['p', 'alice', 'data1', 'read'], 532 | ['p', 'bob', 'data2', 'write'], 533 | ['g', 'alice', 'data2_admin', undefined] 534 | ] 535 | ); 536 | e = await newEnforcer(rbacModel, a); 537 | assert.deepEqual(await e.getPolicy(), [ 538 | ['alice', 'data1', 'read'], 539 | ['bob', 'data2', 'write'] 540 | ]); 541 | 542 | // Remove 'data1' related policy rules via a filter. 543 | // One rule: {'alice', 'data1', 'read'} is deleted. 544 | await a.removeFilteredPolicy(undefined, undefined, 1, 'data1'); 545 | rulesAfter = await CasbinRule.find({}); 546 | assert.deepEqual( 547 | rulesAfter.map((rule) => [rule.ptype, rule.v0, rule.v1, rule.v2]), 548 | [ 549 | ['p', 'bob', 'data2', 'write'], 550 | ['g', 'alice', 'data2_admin', undefined] 551 | ] 552 | ); 553 | e = await newEnforcer(rbacModel, a); 554 | assert.deepEqual(await e.getPolicy(), [['bob', 'data2', 'write']]); 555 | 556 | // Remove 'write' related policy rules via a filter. 557 | // One rule: {'bob', 'data2', 'write'} is deleted. 558 | await a.removeFilteredPolicy(undefined, undefined, 2, 'write'); 559 | rulesAfter = await CasbinRule.find({}); 560 | assert.deepEqual( 561 | rulesAfter.map((rule) => [rule.ptype, rule.v0, rule.v1, rule.v2]), 562 | [['g', 'alice', 'data2_admin', undefined]] 563 | ); 564 | e = await newEnforcer(rbacModel, a); 565 | assert.deepEqual(await e.getPolicy(), []); 566 | }); 567 | 568 | it("Should remove user's policies and groups when using deleteUser", async () => { 569 | const a = await createAdapter(); 570 | const CasbinRule = a.getCasbinRule(); 571 | // Because the DB is empty at first, 572 | // so we need to load the policy from the file adapter (.CSV) first. 573 | let e = await newEnforcer(rbacModel, rbacPolicy); 574 | 575 | const rulesBefore = await CasbinRule.find({}); 576 | assert.equal(rulesBefore.length, 0); 577 | 578 | // This is a trick to save the current policy to the DB. 579 | // We can't call e.savePolicy() because the adapter in the enforcer is still the file adapter. 580 | // The current policy means the policy in the Node-Casbin enforcer (aka in memory). 581 | await a.savePolicy(e.getModel()); 582 | let rulesAfter = await CasbinRule.find({}); 583 | assert.deepEqual( 584 | rulesAfter.map((rule) => [rule.ptype, rule.v0, rule.v1, rule.v2]), 585 | [ 586 | ['p', 'alice', 'data1', 'read'], 587 | ['p', 'bob', 'data2', 'write'], 588 | ['p', 'data2_admin', 'data2', 'read'], 589 | ['p', 'data2_admin', 'data2', 'write'], 590 | ['g', 'alice', 'data2_admin', undefined] 591 | ] 592 | ); 593 | 594 | e = await newEnforcer(rbacModel, a); 595 | // Remove 'alice' related policy rules via a RBAC deleteUser-function. 596 | // One policy: {'alice', 'data2', 'read'} and One Grouping Policy {'alice', 'data2_admin'} are deleted. 597 | await e.deleteUser('alice'); 598 | rulesAfter = await CasbinRule.find({}); 599 | assert.deepEqual( 600 | rulesAfter.map((rule) => [rule.ptype, rule.v0, rule.v1, rule.v2]), 601 | [ 602 | ['p', 'bob', 'data2', 'write'], 603 | ['p', 'data2_admin', 'data2', 'read'], 604 | ['p', 'data2_admin', 'data2', 'write'] 605 | ] 606 | ); 607 | e = await newEnforcer(rbacModel, a); 608 | assert.deepEqual(await e.getPolicy(), [ 609 | ['bob', 'data2', 'write'], 610 | ['data2_admin', 'data2', 'read'], 611 | ['data2_admin', 'data2', 'write'] 612 | ]); 613 | 614 | // Remove 'data1' related policy rules via a filter. 615 | // One rule: {'bob', 'data2', 'write'} is deleted. 616 | await e.deleteUser('bob'); 617 | rulesAfter = await CasbinRule.find({}); 618 | assert.deepEqual( 619 | rulesAfter.map((rule) => [rule.ptype, rule.v0, rule.v1, rule.v2]), 620 | [ 621 | ['p', 'data2_admin', 'data2', 'read'], 622 | ['p', 'data2_admin', 'data2', 'write'] 623 | ] 624 | ); 625 | e = await newEnforcer(rbacModel, a); 626 | assert.deepEqual(await e.getPolicy(), [ 627 | ['data2_admin', 'data2', 'read'], 628 | ['data2_admin', 'data2', 'write'] 629 | ]); 630 | }); 631 | 632 | it("Should remove user's policies and groups when using deleteRole", async () => { 633 | const a = await createAdapter(); 634 | const CasbinRule = a.getCasbinRule(); 635 | // Because the DB is empty at first, 636 | // so we need to load the policy from the file adapter (.CSV) first. 637 | let e = await newEnforcer(rbacModel, rbacPolicy); 638 | 639 | const rulesBefore = await CasbinRule.find({}); 640 | assert.equal(rulesBefore.length, 0); 641 | 642 | // This is a trick to save the current policy to the DB. 643 | // We can't call e.savePolicy() because the adapter in the enforcer is still the file adapter. 644 | // The current policy means the policy in the Node-Casbin enforcer (aka in memory). 645 | await a.savePolicy(e.getModel()); 646 | let rulesAfter = await CasbinRule.find({}); 647 | assert.deepEqual( 648 | rulesAfter.map((rule) => [rule.ptype, rule.v0, rule.v1, rule.v2]), 649 | [ 650 | ['p', 'alice', 'data1', 'read'], 651 | ['p', 'bob', 'data2', 'write'], 652 | ['p', 'data2_admin', 'data2', 'read'], 653 | ['p', 'data2_admin', 'data2', 'write'], 654 | ['g', 'alice', 'data2_admin', undefined] 655 | ] 656 | ); 657 | 658 | e = await newEnforcer(rbacModel, a); 659 | // Remove 'data2_admin' related policy rules via a RBAC deleteRole-function. 660 | // One policy: {'data2_admin', 'data2', 'read'} and One Grouping Policy {'alice', 'data2_admin'} are deleted. 661 | await e.deleteRole('data2_admin'); 662 | rulesAfter = await CasbinRule.find({}); 663 | assert.deepEqual( 664 | rulesAfter.map((rule) => [rule.ptype, rule.v0, rule.v1, rule.v2]), 665 | [ 666 | ['p', 'alice', 'data1', 'read'], 667 | ['p', 'bob', 'data2', 'write'] 668 | ] 669 | ); 670 | assert.deepEqual(await e.getPolicy(), [ 671 | ['alice', 'data1', 'read'], 672 | ['bob', 'data2', 'write'] 673 | ]); 674 | }); 675 | 676 | it('Should properly store new complex policy rules from a file', async () => { 677 | const a = await createAdapter(); 678 | const CasbinRule = a.getCasbinRule(); 679 | // Because the DB is empty at first, 680 | // so we need to load the policy from the file adapter (.CSV) first. 681 | let e = await newEnforcer(rbacDenyDomainModel, rbacDenyDomainPolicy); 682 | 683 | const rulesBefore = await CasbinRule.find({}); 684 | assert.equal(rulesBefore.length, 0); 685 | 686 | // This is a trick to save the current policy to the DB. 687 | // We can't call e.savePolicy() because the adapter in the enforcer is still the file adapter. 688 | // The current policy means the policy in the Node-Casbin enforcer (aka in memory). 689 | await a.savePolicy(await e.getModel()); 690 | const rulesAfter = await CasbinRule.find({}); 691 | assert.deepEqual( 692 | rulesAfter.map((rule) => [rule.ptype, rule.v0, rule.v1, rule.v2, rule.v3, rule.v4]), 693 | [ 694 | ['p', 'admin', 'domain1', 'data1', 'read', 'allow'], 695 | ['p', 'admin', 'domain1', 'data1', 'write', 'allow'], 696 | ['p', 'admin', 'domain2', 'data2', 'read', 'allow'], 697 | ['p', 'admin', 'domain2', 'data2', 'write', 'allow'], 698 | ['p', 'alice', 'domain2', 'data2', 'write', 'deny'], 699 | ['g', 'alice', 'admin', 'domain2', undefined, undefined] 700 | ] 701 | ); 702 | 703 | // Clear the current policy. 704 | await e.clearPolicy(); 705 | assert.deepEqual(await e.getPolicy(), []); 706 | 707 | // Load the policy from DB. 708 | await a.loadPolicy(e.getModel()); 709 | assert.deepEqual(await e.getPolicy(), [ 710 | ['admin', 'domain1', 'data1', 'read', 'allow'], 711 | ['admin', 'domain1', 'data1', 'write', 'allow'], 712 | ['admin', 'domain2', 'data2', 'read', 'allow'], 713 | ['admin', 'domain2', 'data2', 'write', 'allow'], 714 | ['alice', 'domain2', 'data2', 'write', 'deny'] 715 | ]); 716 | 717 | // Note: you don't need to look at the above code 718 | // if you already have a working DB with policy inside. 719 | 720 | // Now the DB has policy, so we can provide a normal use case. 721 | // Create an adapter and an enforcer. 722 | // newEnforcer() will load the policy automatically. 723 | e = await newEnforcer(rbacDenyDomainModel, a); 724 | assert.deepEqual(await e.getPolicy(), [ 725 | ['admin', 'domain1', 'data1', 'read', 'allow'], 726 | ['admin', 'domain1', 'data1', 'write', 'allow'], 727 | ['admin', 'domain2', 'data2', 'read', 'allow'], 728 | ['admin', 'domain2', 'data2', 'write', 'allow'], 729 | ['alice', 'domain2', 'data2', 'write', 'deny'] 730 | ]); 731 | 732 | // Add policy to DB 733 | await a.addPolicy('', 'p', ['role', 'domain', 'res', 'action', 'allow']); 734 | e = await newEnforcer(rbacDenyDomainModel, a); 735 | assert.deepEqual(await e.getPolicy(), [ 736 | ['admin', 'domain1', 'data1', 'read', 'allow'], 737 | ['admin', 'domain1', 'data1', 'write', 'allow'], 738 | ['admin', 'domain2', 'data2', 'read', 'allow'], 739 | ['admin', 'domain2', 'data2', 'write', 'allow'], 740 | ['alice', 'domain2', 'data2', 'write', 'deny'], 741 | ['role', 'domain', 'res', 'action', 'allow'] 742 | ]); 743 | // Remove policy from DB 744 | await a.removePolicy('', 'p', ['role', 'domain', 'res', 'action', 'allow']); 745 | e = await newEnforcer(rbacDenyDomainModel, a); 746 | assert.deepEqual(await e.getPolicy(), [ 747 | ['admin', 'domain1', 'data1', 'read', 'allow'], 748 | ['admin', 'domain1', 'data1', 'write', 'allow'], 749 | ['admin', 'domain2', 'data2', 'read', 'allow'], 750 | ['admin', 'domain2', 'data2', 'write', 'allow'], 751 | ['alice', 'domain2', 'data2', 'write', 'deny'] 752 | ]); 753 | // Enforce a rule 754 | assert.notOk(await e.enforce('alice', 'domain2', 'data2', 'write')); 755 | assert.ok(await e.enforce('admin', 'domain2', 'data2', 'write')); 756 | assert.ok(await e.enforce('admin', 'domain2', 'data2', 'write')); 757 | assert.ok(await e.enforce('admin', 'domain2', 'data2', 'read')); 758 | assert.ok(await e.enforce('alice', 'domain2', 'data2', 'read')); 759 | assert.notOk(await e.enforce('alice', 'domain1', 'data1', 'read')); 760 | assert.notOk(await e.enforce('alice', 'domain1', 'data1', 'write')); 761 | }); 762 | 763 | it('Should remove related complex policy rules via a filter', async () => { 764 | const a = await createAdapter(); 765 | const CasbinRule = a.getCasbinRule(); 766 | // Because the DB is empty at first, 767 | // so we need to load the policy from the file adapter (.CSV) first. 768 | let e = await newEnforcer(rbacDenyDomainModel, rbacDenyDomainPolicy); 769 | 770 | const rulesBefore = await CasbinRule.find({}); 771 | assert.equal(rulesBefore.length, 0); 772 | 773 | // This is a trick to save the current policy to the DB. 774 | // We can't call e.savePolicy() because the adapter in the enforcer is still the file adapter. 775 | // The current policy means the policy in the Node-Casbin enforcer (aka in memory). 776 | await a.savePolicy(e.getModel()); 777 | let rulesAfter = await CasbinRule.find({}); 778 | assert.deepEqual( 779 | rulesAfter.map((rule) => [rule.ptype, rule.v0, rule.v1, rule.v2, rule.v3, rule.v4]), 780 | [ 781 | ['p', 'admin', 'domain1', 'data1', 'read', 'allow'], 782 | ['p', 'admin', 'domain1', 'data1', 'write', 'allow'], 783 | ['p', 'admin', 'domain2', 'data2', 'read', 'allow'], 784 | ['p', 'admin', 'domain2', 'data2', 'write', 'allow'], 785 | ['p', 'alice', 'domain2', 'data2', 'write', 'deny'], 786 | ['g', 'alice', 'admin', 'domain2', undefined, undefined] 787 | ] 788 | ); 789 | e = await newEnforcer(rbacDenyDomainModel, a); 790 | assert.deepEqual(await e.getPolicy(), [ 791 | ['admin', 'domain1', 'data1', 'read', 'allow'], 792 | ['admin', 'domain1', 'data1', 'write', 'allow'], 793 | ['admin', 'domain2', 'data2', 'read', 'allow'], 794 | ['admin', 'domain2', 'data2', 'write', 'allow'], 795 | ['alice', 'domain2', 'data2', 'write', 'deny'] 796 | ]); 797 | 798 | // Remove 'data2_admin' related policy rules via a filter. 799 | // Four rules: 800 | // {'admin', 'domain1', 'data1', 'read', 'allow'}, 801 | // {'admin', 'domain1', 'data1', 'write', 'allow'}, 802 | // {'admin', 'domain2', 'data2', 'read', 'allow'}, 803 | // {'admin', 'domain2', 'data2', 'write', 'allow'} 804 | // are deleted. 805 | await a.removeFilteredPolicy(undefined, undefined, 0, 'admin'); 806 | rulesAfter = await CasbinRule.find({}); 807 | assert.deepEqual( 808 | rulesAfter.map((rule) => [rule.ptype, rule.v0, rule.v1, rule.v2, rule.v3, rule.v4]), 809 | [ 810 | ['p', 'alice', 'domain2', 'data2', 'write', 'deny'], 811 | ['g', 'alice', 'admin', 'domain2', undefined, undefined] 812 | ] 813 | ); 814 | e = await newEnforcer(rbacDenyDomainModel, a); 815 | assert.deepEqual(await e.getPolicy(), [['alice', 'domain2', 'data2', 'write', 'deny']]); 816 | await a.removeFilteredPolicy(undefined, 'g'); 817 | rulesAfter = await CasbinRule.find({}); 818 | assert.deepEqual( 819 | rulesAfter.map((rule) => [rule.ptype, rule.v0, rule.v1, rule.v2, rule.v3, rule.v4]), 820 | [['p', 'alice', 'domain2', 'data2', 'write', 'deny']] 821 | ); 822 | await a.removeFilteredPolicy(undefined, 'p'); 823 | rulesAfter = await CasbinRule.find({}); 824 | assert.deepEqual( 825 | rulesAfter.map((rule) => [rule.ptype, rule.v0, rule.v1, rule.v2, rule.v3, rule.v4]), 826 | [] 827 | ); 828 | 829 | // Reload the mode + policy 830 | e = await newEnforcer(rbacDenyDomainModel, rbacDenyDomainPolicy); 831 | await a.savePolicy(e.getModel()); 832 | // Remove 'domain2' related policy rules via a filter. 833 | // Three rules: 834 | // {'p', 'admin', 'domain2', 'data2', 'read', 'allow'}, 835 | // {'p', 'admin', 'domain2', 'data2', 'write', 'allow'}, 836 | // {'p', 'alice', 'domain2', 'data2', 'write', 'deny'} 837 | // are deleted. 838 | await a.removeFilteredPolicy(undefined, undefined, 1, 'domain2'); 839 | rulesAfter = await CasbinRule.find({}); 840 | assert.deepEqual( 841 | rulesAfter.map((rule) => [rule.ptype, rule.v0, rule.v1, rule.v2, rule.v3, rule.v4]), 842 | [ 843 | ['p', 'admin', 'domain1', 'data1', 'read', 'allow'], 844 | ['p', 'admin', 'domain1', 'data1', 'write', 'allow'], 845 | ['g', 'alice', 'admin', 'domain2', undefined, undefined] 846 | ] 847 | ); 848 | e = await newEnforcer(rbacModel, a); 849 | assert.deepEqual(await e.getPolicy(), [ 850 | ['admin', 'domain1', 'data1', 'read', 'allow'], 851 | ['admin', 'domain1', 'data1', 'write', 'allow'] 852 | ]); 853 | 854 | // Remove 'data1' related policy rules via a filter. 855 | // Two rules: 856 | // {'admin', 'domain1', 'data1', 'read', 'allow'}, 857 | // {'admin', 'domain1', 'data1', 'write', 'allow'} 858 | // are deleted. 859 | await a.removeFilteredPolicy(undefined, undefined, 2, 'data1'); 860 | rulesAfter = await CasbinRule.find({}); 861 | assert.deepEqual( 862 | rulesAfter.map((rule) => [rule.ptype, rule.v0, rule.v1, rule.v2, rule.v3, rule.v4]), 863 | [['g', 'alice', 'admin', 'domain2', undefined, undefined]] 864 | ); 865 | e = await newEnforcer(rbacDenyDomainModel, a); 866 | assert.deepEqual(await e.getPolicy(), []); 867 | 868 | await a.removeFilteredPolicy(undefined, 'g'); 869 | await a.removeFilteredPolicy(undefined, 'p'); 870 | rulesAfter = await CasbinRule.find({}); 871 | assert.deepEqual( 872 | rulesAfter.map((rule) => [rule.ptype, rule.v0, rule.v1, rule.v2, rule.v3, rule.v4]), 873 | [] 874 | ); 875 | 876 | e = await newEnforcer(rbacDenyDomainModel, rbacDenyDomainPolicy); 877 | await a.savePolicy(e.getModel()); 878 | 879 | // Remove 'read' related policy rules via a filter. 880 | // Two rules: 881 | // {'admin', 'domain1', 'data1', 'read', 'allow'}, 882 | // {'admin', 'domain2', 'data2', 'read', 'allow'} 883 | // are deleted. 884 | await a.removeFilteredPolicy(undefined, undefined, 3, 'read'); 885 | rulesAfter = await CasbinRule.find({}); 886 | assert.deepEqual( 887 | rulesAfter.map((rule) => [rule.ptype, rule.v0, rule.v1, rule.v2, rule.v3, rule.v4]), 888 | [ 889 | ['p', 'admin', 'domain1', 'data1', 'write', 'allow'], 890 | ['p', 'admin', 'domain2', 'data2', 'write', 'allow'], 891 | ['p', 'alice', 'domain2', 'data2', 'write', 'deny'], 892 | ['g', 'alice', 'admin', 'domain2', undefined, undefined] 893 | ] 894 | ); 895 | e = await newEnforcer(rbacDenyDomainModel, a); 896 | assert.deepEqual(await e.getPolicy(), [ 897 | ['admin', 'domain1', 'data1', 'write', 'allow'], 898 | ['admin', 'domain2', 'data2', 'write', 'allow'], 899 | ['alice', 'domain2', 'data2', 'write', 'deny'] 900 | ]); 901 | 902 | // Remove 'read' related policy rules via a filter. 903 | // One rule: 904 | // {'alice', 'domain2', 'data2', 'write', 'deny'}, 905 | // is deleted. 906 | await a.removeFilteredPolicy(undefined, undefined, 4, 'deny'); 907 | rulesAfter = await CasbinRule.find({}); 908 | assert.deepEqual( 909 | rulesAfter.map((rule) => [rule.ptype, rule.v0, rule.v1, rule.v2, rule.v3, rule.v4]), 910 | [ 911 | ['p', 'admin', 'domain1', 'data1', 'write', 'allow'], 912 | ['p', 'admin', 'domain2', 'data2', 'write', 'allow'], 913 | ['g', 'alice', 'admin', 'domain2', undefined, undefined] 914 | ] 915 | ); 916 | e = await newEnforcer(rbacDenyDomainModel, a); 917 | assert.deepEqual(await e.getPolicy(), [ 918 | ['admin', 'domain1', 'data1', 'write', 'allow'], 919 | ['admin', 'domain2', 'data2', 'write', 'allow'] 920 | ]); 921 | }); 922 | 923 | it('SetSynced should fail in non-replicaset connection', async () => { 924 | // Create SyncedMongoAdapter 925 | try { 926 | const adapter = await createAdapter(); 927 | adapter.setSynced(true); 928 | } catch (error) { 929 | assert(error instanceof InvalidAdapterTypeError); 930 | assert.equal(error.message, 'Tried to enable transactions for non-replicaset connection'); 931 | } 932 | }); 933 | 934 | it('getSession should fail in non-replicaset connection', async () => { 935 | // Create SyncedMongoAdapter 936 | try { 937 | const adapter = await createAdapter(); 938 | adapter.getSession(); 939 | } catch (error) { 940 | assert(error instanceof InvalidAdapterTypeError); 941 | assert.equal(error.message, 'Tried to start a session for non-replicaset connection'); 942 | } 943 | }); 944 | 945 | it('getTransaction should fail in non-replicaset connection', async () => { 946 | // Create SyncedMongoAdapter 947 | try { 948 | const adapter = await createAdapter(); 949 | adapter.getTransaction(); 950 | } catch (error) { 951 | assert(error instanceof InvalidAdapterTypeError); 952 | assert.equal(error.message, 'Tried to start a session for non-replicaset connection'); 953 | } 954 | }); 955 | 956 | it('commitTransaction should fail in non-replicaset connection', async () => { 957 | // Create SyncedMongoAdapter 958 | try { 959 | const adapter = await createAdapter(); 960 | adapter.commitTransaction(); 961 | } catch (error) { 962 | assert(error instanceof InvalidAdapterTypeError); 963 | assert.equal(error.message, 'Tried to start a session for non-replicaset connection'); 964 | } 965 | }); 966 | 967 | it('abortTransaction should fail in non-replicaset connection', async () => { 968 | // Create SyncedMongoAdapter 969 | try { 970 | const adapter = await createAdapter(); 971 | adapter.abortTransaction(); 972 | } catch (error) { 973 | assert(error instanceof InvalidAdapterTypeError); 974 | assert(error.message, 'Tried to start a session for non-replicaset connection'); 975 | } 976 | }); 977 | 978 | it('Should allow you to close the connection', async () => { 979 | // Create mongoAdapter 980 | const enforcer = await createEnforcer(); 981 | const adapter = enforcer.getAdapter(); 982 | assert.equal(adapter.connection.readyState, 1, 'Connection should be open'); 983 | 984 | // Connection should close 985 | await adapter.close(); 986 | assert.equal(adapter.connection.readyState, 0, 'Connection should be closed'); 987 | }); 988 | 989 | it('Closing a closed/undefined connection should not raise an error', async () => { 990 | // Create mongoAdapter 991 | const adapter = await createDisconnectedAdapter(); 992 | // Closing a closed connection should not raise an error 993 | await adapter.close(); 994 | }); 995 | 996 | it('Multiple adapter with different database names should not share the datasource', async () => { 997 | const a1 = await createAdapterWithDBName('node1'); 998 | const e1 = await newEnforcer(rbacModel, a1); 999 | const p1 = ['alice', 'data1', 'read']; 1000 | await e1.addPolicy(...p1); 1001 | 1002 | const a2 = await createAdapterWithDBName('node2'); 1003 | const e2 = await newEnforcer(rbacModel, a2); 1004 | assert.isFalse(await e2.enforce(...p1), 'Adapter should not share the datasource'); 1005 | }); 1006 | }); 1007 | --------------------------------------------------------------------------------