├── .editorconfig ├── .eslintignore ├── .eslintrc.json ├── .github ├── Dockerfile ├── docker-entrypoint.sh ├── mongo_setup.sh ├── semantic.yml └── workflows │ └── main.yml ├── .gitignore ├── .prettierrc ├── .releaserc.json ├── CHANGELOG.md ├── LICENSE ├── README.md ├── package.json ├── src ├── adapter.ts ├── errors.ts ├── index.ts └── model.ts ├── test ├── .eslintrc.json ├── .mocharc.js ├── fixtures │ ├── basic_model.conf │ ├── basic_policy.csv │ ├── rbac_model.conf │ ├── rbac_policy.csv │ ├── rbac_with_domains_with_deny_model.conf │ └── rbac_with_domains_with_deny_policy.csv ├── helpers │ └── helpers.js ├── integration │ ├── .mocharc.js │ └── adapter.test.js └── unit │ ├── .mocharc.js │ └── adapter.test.js ├── tsconfig.cjs.json ├── tsconfig.esm.json ├── tsconfig.json └── yarn.lock /.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 | -------------------------------------------------------------------------------- /.eslintignore: -------------------------------------------------------------------------------- 1 | coverage 2 | lib/ 3 | -------------------------------------------------------------------------------- /.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 | -------------------------------------------------------------------------------- /.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 | -------------------------------------------------------------------------------- /.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/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 | -------------------------------------------------------------------------------- /.github/semantic.yml: -------------------------------------------------------------------------------- 1 | # Always validate the PR title AND all the commits 2 | titleAndCommits: true 3 | -------------------------------------------------------------------------------- /.github/workflows/main.yml: -------------------------------------------------------------------------------- 1 | name: main 2 | on: [push, pull_request] 3 | jobs: 4 | test: 5 | runs-on: ubuntu-latest 6 | strategy: 7 | fail-fast: false 8 | matrix: 9 | node-version: [^16, ^18] 10 | steps: 11 | - name: Checkout 12 | uses: actions/checkout@v2 13 | 14 | - name: Setup MongoDB 15 | run: bash ./.github/mongo_setup.sh 16 | 17 | - uses: actions/setup-node@v1 18 | with: 19 | node-version: ${{ matrix.node-version }} 20 | 21 | - name: Install Dependency 22 | run: yarn install --ignore-engines 23 | 24 | - name: Build library 25 | run: yarn run build 26 | 27 | - name: Run unit tests 28 | run: yarn run tests 29 | 30 | coverall: 31 | needs: [test] 32 | runs-on: ubuntu-latest 33 | strategy: 34 | fail-fast: false 35 | matrix: 36 | node-version: [^16, ^18] 37 | steps: 38 | - name: Checkout 39 | uses: actions/checkout@v2 40 | 41 | - name: Setup MongoDB 42 | run: bash ./.github/mongo_setup.sh 43 | 44 | - uses: actions/setup-node@v1 45 | with: 46 | node-version: ${{ matrix.node-version }} 47 | 48 | - name: Install Dependency 49 | run: yarn install --ignore-engines 50 | 51 | - name: Build library 52 | run: yarn run build 53 | 54 | - name: Run code coverage 55 | run: yarn run coverage 56 | 57 | - name: Coveralls Parallel 58 | uses: coverallsapp/github-action@master 59 | with: 60 | github-token: ${{ secrets.GITHUB_TOKEN }} 61 | 62 | release: 63 | needs: [test,coverall] 64 | runs-on: ubuntu-latest 65 | steps: 66 | - name: Coveralls Finished 67 | uses: coverallsapp/github-action@master 68 | with: 69 | github-token: ${{ secrets.GITHUB_TOKEN }} 70 | parallel-finished: true 71 | 72 | - name: Checkout 73 | uses: actions/checkout@v2 74 | 75 | - name: Install Dependency 76 | run: yarn install --ignore-engines 77 | 78 | - name: Build library 79 | run: yarn run build 80 | 81 | - name: Release 82 | if: github.event_name == 'push' && github.repository == 'node-casbin/mongoose-adapter' 83 | 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 84 | env: 85 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 86 | NPM_TOKEN: ${{ secrets.NPM_TOKEN }} 87 | -------------------------------------------------------------------------------- /.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 | -------------------------------------------------------------------------------- /.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 | -------------------------------------------------------------------------------- /.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 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | ## [5.3.1](https://github.com/node-casbin/mongoose-adapter/compare/v5.3.0...v5.3.1) (2023-08-06) 2 | 3 | 4 | ### Bug Fixes 5 | 6 | * fix broken links ([#74](https://github.com/node-casbin/mongoose-adapter/issues/74)) ([160f44c](https://github.com/node-casbin/mongoose-adapter/commit/160f44c79452ae939865ddc5de116983c9fcc340)) 7 | 8 | # [5.3.0](https://github.com/node-casbin/mongoose-adapter/compare/v5.2.0...v5.3.0) (2023-07-14) 9 | 10 | 11 | ### Features 12 | 13 | * 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)) 14 | 15 | # [5.2.0](https://github.com/node-casbin/mongoose-adapter/compare/v5.1.1...v5.2.0) (2023-04-21) 16 | 17 | 18 | ### Features 19 | 20 | * 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)) 21 | 22 | ## [5.1.1](https://github.com/node-casbin/mongoose-adapter/compare/v5.1.0...v5.1.1) (2023-04-19) 23 | 24 | 25 | ### Bug Fixes 26 | 27 | * fix multiple adapter ([#68](https://github.com/node-casbin/mongoose-adapter/issues/68)) ([49e69bc](https://github.com/node-casbin/mongoose-adapter/commit/49e69bc2f526fdb42b7410a04173c6b4c58bb635)) 28 | 29 | # [5.1.0](https://github.com/node-casbin/mongoose-adapter/compare/v5.0.0...v5.1.0) (2022-03-21) 30 | 31 | 32 | ### Bug Fixes 33 | 34 | * format issues ([d653519](https://github.com/node-casbin/mongoose-adapter/commit/d653519ec3cfc8b1f81d2a061dbb86df1a4df9c3)) 35 | * token parsing issues if token contains delimeter ([cd695a6](https://github.com/node-casbin/mongoose-adapter/commit/cd695a68f7f45faaae065d4e37c7d4593f7d09b9)) 36 | * update lock file ([203cc98](https://github.com/node-casbin/mongoose-adapter/commit/203cc98d9db46e10319f89ea6ab3affe98c2098b)) 37 | 38 | 39 | ### Features 40 | 41 | * add postinstall script ([af93ec8](https://github.com/node-casbin/mongoose-adapter/commit/af93ec8025f10bd761b47c276a841e368f61bc1a)) 42 | * check if the word is already wrapped in quotes ([d31166e](https://github.com/node-casbin/mongoose-adapter/commit/d31166e3fd8f67eb6ffcff475a68916f61ce7f60)) 43 | 44 | # [5.0.0](https://github.com/node-casbin/mongoose-adapter/compare/v4.0.1...v5.0.0) (2022-03-13) 45 | 46 | 47 | ### Bug Fixes 48 | 49 | * 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)) 50 | 51 | 52 | ### BREAKING CHANGES 53 | 54 | * 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/ 55 | 56 | Co-authored-by: Shivansh Yadav 57 | 58 | ## [4.0.1](https://github.com/node-casbin/mongoose-adapter/compare/v4.0.0...v4.0.1) (2022-01-31) 59 | 60 | 61 | ### Bug Fixes 62 | 63 | * **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)) 64 | 65 | # [4.0.0](https://github.com/node-casbin/mongoose-adapter/compare/v3.1.1...v4.0.0) (2022-01-29) 66 | 67 | 68 | ### Features 69 | 70 | * upgrade Mongoose ([#52](https://github.com/node-casbin/mongoose-adapter/issues/52)) ([fb53794](https://github.com/node-casbin/mongoose-adapter/commit/fb5379432397710a27570b116ea3f7459f4bd3b6)) 71 | 72 | 73 | ### BREAKING CHANGES 74 | 75 | * upgrade to Mongoose 6.x and drop Node 10 support 76 | 77 | ## [3.1.1](https://github.com/node-casbin/mongoose-adapter/compare/v3.1.0...v3.1.1) (2021-08-28) 78 | 79 | 80 | ### Bug Fixes 81 | 82 | * 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)) 83 | 84 | # [3.1.0](https://github.com/node-casbin/mongoose-adapter/compare/v3.0.1...v3.1.0) (2021-08-03) 85 | 86 | 87 | ### Features 88 | 89 | * implement UpdatableAdapter interface ([#49](https://github.com/node-casbin/mongoose-adapter/issues/49)) ([131a446](https://github.com/node-casbin/mongoose-adapter/commit/131a446b813b202d322ac0d0fc45d436e34832ca)) 90 | 91 | ## [3.0.1](https://github.com/node-casbin/mongoose-adapter/compare/v3.0.0...v3.0.1) (2021-04-27) 92 | 93 | 94 | ### Bug Fixes 95 | 96 | * no longer support legacy require ([5b09912](https://github.com/node-casbin/mongoose-adapter/commit/5b09912a693a3cf6442d640fe4031938a373c820)) 97 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Mongoose Adapter 2 | ==== 3 | [![NPM version][npm-image]][npm-url] 4 | [![NPM download][download-image]][download-url] 5 | [![codebeat badge](https://codebeat.co/badges/c17c9ee1-da42-4db3-8047-9574ad2b23b1)](https://codebeat.co/projects/github-com-node-casbin-mongoose-adapter-master) 6 | [![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) 7 | [![Discord](https://img.shields.io/discord/1022748306096537660?logo=discord&label=discord&color=5865F2)](https://discord.gg/S5UjpzGZjN) 8 | [![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) 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 | ## Filtered Adapter 60 | 61 | You can create an adapter instance that will load only those rules you need to. 62 | 63 | A simple case for it is when you have separate policy rules for separate domains (tenants). 64 | You do not need to load all the rules for all domains to make an authorization in specific domain. 65 | 66 | For such cases, filtered adapter exists in casbin. 67 | 68 | ```javascript 69 | const { MongooseAdapter } = require('casbin-mongoose-adapter'); 70 | const adapter = await MongooseAdapter.newFilteredAdapter('mongodb://your_mongodb_uri:27017'); 71 | ``` 72 | 73 | ## License 74 | 75 | [Apache-2.0](./LICENSE) 76 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "casbin-mongoose-adapter", 3 | "version": "5.3.1", 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 | -------------------------------------------------------------------------------- /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 | } 34 | 35 | export interface policyLine { 36 | ptype?: string; 37 | v0?: string; 38 | v1?: string; 39 | v2?: string; 40 | v3?: string; 41 | v4?: string; 42 | v5?: string; 43 | } 44 | 45 | export interface sessionOption { 46 | session?: ClientSession; 47 | } 48 | 49 | /** 50 | * Implements a policy adapter for casbin with MongoDB support. 51 | * 52 | * @class 53 | */ 54 | export class MongooseAdapter implements BatchAdapter, FilteredAdapter, UpdatableAdapter { 55 | public connection?: Connection; 56 | 57 | private filtered: boolean; 58 | private isSynced: boolean; 59 | private uri: string; 60 | private options?: ConnectOptions; 61 | private autoAbort: boolean; 62 | private autoCommit: boolean; 63 | private session: ClientSession; 64 | private casbinRule: MongooseModel; 65 | 66 | /** 67 | * Creates a new instance of mongoose adapter for casbin. 68 | * It does not wait for successfull connection to MongoDB. 69 | * So, if you want to have a possibility to wait until connection successful, use newAdapter instead. 70 | * 71 | * @constructor 72 | * @param {String} uri Mongo URI where casbin rules must be persisted 73 | * @param {Object} [options={}] Additional options to pass on to mongoose client 74 | * @param {Object} [adapterOptions={}] adapterOptions additional adapter options 75 | * @example 76 | * const adapter = new MongooseAdapter('MONGO_URI'); 77 | * const adapter = new MongooseAdapter('MONGO_URI', { mongoose_options: 'here' }) 78 | */ 79 | constructor(uri: string, options?: ConnectOptions, adapterOptions?: MongooseAdapterOptions) { 80 | if (!uri) { 81 | throw new AdapterError('You must provide Mongo URI to connect to!'); 82 | } 83 | 84 | // by default, adapter is not filtered 85 | this.filtered = false; 86 | this.isSynced = false; 87 | this.autoAbort = false; 88 | this.uri = uri; 89 | this.options = options; 90 | this.connection = createConnection(this.uri, this.options); 91 | this.casbinRule = this.connection.model( 92 | modelName, 93 | schema(adapterOptions?.timestamps), 94 | collectionName 95 | ); 96 | } 97 | 98 | /** 99 | * Creates a new instance of mongoose adapter for casbin. 100 | * Instead of constructor, it does wait for successfull connection to MongoDB. 101 | * Preferable way to construct an adapter instance, is to use this static method. 102 | * 103 | * @static 104 | * @param {String} uri Mongo URI where casbin rules must be persisted 105 | * @param {Object} [options={}] Additional options to pass on to mongoose client 106 | * @param {Object} [adapterOptions={}] Additional options to pass on to adapter 107 | * @example 108 | * const adapter = await MongooseAdapter.newAdapter('MONGO_URI'); 109 | * const adapter = await MongooseAdapter.newAdapter('MONGO_URI', { mongoose_options: 'here' }); 110 | */ 111 | static async newAdapter( 112 | uri: string, 113 | options?: ConnectOptions, 114 | adapterOptions: MongooseAdapterOptions = {} 115 | ) { 116 | const adapter = new MongooseAdapter(uri, options, adapterOptions); 117 | const { 118 | filtered = false, 119 | synced = false, 120 | autoAbort = false, 121 | autoCommit = false 122 | } = adapterOptions; 123 | adapter.setFiltered(filtered); 124 | adapter.setSynced(synced); 125 | adapter.setAutoAbort(autoAbort); 126 | adapter.setAutoCommit(autoCommit); 127 | return adapter; 128 | } 129 | 130 | /** 131 | * Creates a new instance of mongoose adapter for casbin. 132 | * It does the same as newAdapter, but it also sets a flag that this adapter is in filtered state. 133 | * That way, casbin will not call loadPolicy() automatically. 134 | * 135 | * @static 136 | * @param {String} uri Mongo URI where casbin rules must be persisted 137 | * @param {Object} [options] Additional options to pass on to mongoose client 138 | * @example 139 | * const adapter = await MongooseAdapter.newFilteredAdapter('MONGO_URI'); 140 | * const adapter = await MongooseAdapter.newFilteredAdapter('MONGO_URI', { mongoose_options: 'here' }); 141 | */ 142 | static async newFilteredAdapter(uri: string, options?: ConnectOptions) { 143 | const adapter = await MongooseAdapter.newAdapter(uri, options, { 144 | filtered: true 145 | }); 146 | return adapter; 147 | } 148 | 149 | /** 150 | * Creates a new instance of mongoose adapter for casbin. 151 | * It does the same as newAdapter, but it checks wether database is a replica set. If it is, it enables 152 | * transactions for the adapter. 153 | * Transactions are never commited automatically. You have to use commitTransaction to add pending changes. 154 | * 155 | * @static 156 | * @param {String} uri Mongo URI where casbin rules must be persisted 157 | * @param {Object} [options={}] Additional options to pass on to mongoose client 158 | * @param {Boolean} autoAbort Whether to abort transactions on Error automatically 159 | * @param autoCommit 160 | * @example 161 | * const adapter = await MongooseAdapter.newFilteredAdapter('MONGO_URI'); 162 | * const adapter = await MongooseAdapter.newFilteredAdapter('MONGO_URI', { mongoose_options: 'here' }); 163 | */ 164 | static async newSyncedAdapter( 165 | uri: string, 166 | options?: ConnectOptions, 167 | autoAbort: boolean = true, 168 | autoCommit = true 169 | ) { 170 | return await MongooseAdapter.newAdapter(uri, options, { 171 | synced: true, 172 | autoAbort, 173 | autoCommit 174 | }); 175 | } 176 | 177 | /** 178 | * Switch adapter to (non)filtered state. 179 | * Casbin uses this flag to determine if it should load the whole policy from DB or not. 180 | * 181 | * @param {Boolean} [enable=true] Flag that represents the current state of adapter (filtered or not) 182 | */ 183 | setFiltered(enable: boolean = true) { 184 | this.filtered = enable; 185 | } 186 | 187 | /** 188 | * isFiltered determines whether the filtered model is enabled for the adapter. 189 | * @returns {boolean} 190 | */ 191 | isFiltered(): boolean { 192 | return this.filtered; 193 | } 194 | 195 | /** 196 | * SyncedAdapter: Switch adapter to (non)synced state. 197 | * This enables mongoDB transactions when loading and saving policies to DB. 198 | * 199 | * @param {Boolean} [synced=true] Flag that represents the current state of adapter (filtered or not) 200 | */ 201 | setSynced(synced: boolean = true) { 202 | this.isSynced = synced; 203 | } 204 | 205 | /** 206 | * SyncedAdapter: Automatically abort on Error. 207 | * When enabled, functions will automatically abort on error 208 | * 209 | * @param {Boolean} [abort=true] Flag that represents if automatic abort should be enabled or not 210 | */ 211 | setAutoAbort(abort: boolean = true) { 212 | if (this.isSynced) this.autoAbort = abort; 213 | } 214 | 215 | /** 216 | * SyncedAdapter: Automatically commit after each addition. 217 | * When enabled, functions will automatically commit after function has finished 218 | * 219 | * @param {Boolean} [commit=true] Flag that represents if automatic commit should be enabled or not 220 | */ 221 | setAutoCommit(commit: boolean = true) { 222 | if (this.isSynced) this.autoCommit = commit; 223 | } 224 | 225 | /** 226 | * SyncedAdapter: Gets active session or starts a new one. Sessions are used to handle transactions. 227 | */ 228 | async getSession(): Promise { 229 | if (this.isSynced) { 230 | return this.session && this.session.inTransaction() 231 | ? this.session 232 | : this.connection!.startSession(); 233 | } else 234 | throw new InvalidAdapterTypeError( 235 | 'Transactions are only supported by SyncedAdapter. See newSyncedAdapter' 236 | ); 237 | } 238 | 239 | /** 240 | * SyncedAdapter: Sets current session to specific one. Do not use this unless you know what you are doing. 241 | */ 242 | async setSession(session: ClientSession) { 243 | if (this.isSynced) { 244 | this.session = session; 245 | } else { 246 | throw new InvalidAdapterTypeError( 247 | 'Sessions are only supported by SyncedAdapter. See newSyncedAdapter' 248 | ); 249 | } 250 | } 251 | 252 | /** 253 | * SyncedAdapter: Gets active transaction or starts a new one. Transaction must be closed before changes are done 254 | * to the database. See: commitTransaction, abortTransaction 255 | * @returns {Promise} Returns a session with active transaction 256 | */ 257 | async getTransaction(): Promise { 258 | if (this.isSynced) { 259 | const session = await this.getSession(); 260 | if (!session.inTransaction()) { 261 | await this.casbinRule.createCollection(); 262 | await session.startTransaction(); 263 | logPrint( 264 | 'Transaction started. To commit changes use adapter.commitTransaction() or to abort use adapter.abortTransaction()' 265 | ); 266 | } 267 | return session; 268 | } else 269 | throw new InvalidAdapterTypeError( 270 | 'Transactions are only supported by SyncedAdapter. See newSyncedAdapter' 271 | ); 272 | } 273 | 274 | /** 275 | * SyncedAdapter: Commits active transaction. Documents are not saved before this function is used. 276 | * Transaction closes after the use of this function. 277 | * @returns {Promise} 278 | */ 279 | async commitTransaction(): Promise { 280 | if (this.isSynced) { 281 | const session = await this.getSession(); 282 | await session.commitTransaction(); 283 | } else 284 | throw new InvalidAdapterTypeError( 285 | 'Transactions are only supported by SyncedAdapter. See newSyncedAdapter' 286 | ); 287 | } 288 | 289 | /** 290 | * SyncedAdapter: Aborts active transaction. All Document changes within this transaction are reverted. 291 | * Transaction closes after the use of this function. 292 | * @returns {Promise} 293 | */ 294 | async abortTransaction(): Promise { 295 | if (this.isSynced) { 296 | const session = await this.getSession(); 297 | await session.abortTransaction(); 298 | logPrint('Transaction aborted'); 299 | } else 300 | throw new InvalidAdapterTypeError( 301 | 'Transactions are only supported by SyncedAdapter. See newSyncedAdapter' 302 | ); 303 | } 304 | 305 | /** 306 | * Loads one policy rule into casbin model. 307 | * This method is used by casbin and should not be called by user. 308 | * 309 | * @param {Object} line Record with one policy rule from MongoDB 310 | * @param {Object} model Casbin model to which policy rule must be loaded 311 | */ 312 | loadPolicyLine(line: policyLine, model: Model) { 313 | let lineText = `${line.ptype!}`; 314 | 315 | for (const word of [line.v0, line.v1, line.v2, line.v3, line.v4, line.v5]) { 316 | if (word !== undefined) { 317 | let wrappedWord = /^".*"$/.test(word) ? word : `"${word}"`; 318 | lineText = `${lineText},${wrappedWord}`; 319 | } else { 320 | break; 321 | } 322 | } 323 | 324 | if (lineText) { 325 | Helper.loadPolicyLine(lineText, model); 326 | } 327 | } 328 | 329 | /** 330 | * Implements the process of loading policy from database into enforcer. 331 | * This method is used by casbin and should not be called by user. 332 | * 333 | * @param {Model} model Model instance from enforcer 334 | * @returns {Promise} 335 | */ 336 | async loadPolicy(model: Model): Promise { 337 | return this.loadFilteredPolicy(model, null); 338 | } 339 | 340 | /** 341 | * Loads partial policy based on filter criteria. 342 | * This method is used by casbin and should not be called by user. 343 | * 344 | * @param {Model} model Enforcer model 345 | * @param {Object} [filter] MongoDB filter to query 346 | */ 347 | async loadFilteredPolicy(model: Model, filter: FilterQuery | null) { 348 | if (filter) { 349 | this.setFiltered(true); 350 | } else { 351 | this.setFiltered(false); 352 | } 353 | const options: sessionOption = {}; 354 | if (this.isSynced) options.session = await this.getTransaction(); 355 | 356 | const lines = await this.casbinRule.find(filter || {}, null, options).lean(); 357 | 358 | this.autoCommit && options.session && (await options.session.commitTransaction()); 359 | for (const line of lines) { 360 | this.loadPolicyLine(line, model); 361 | } 362 | } 363 | 364 | /** 365 | * Generates one policy rule ready to be saved into MongoDB. 366 | * This method is used by casbin to generate Mongoose Model Object for single policy 367 | * and should not be called by user. 368 | * 369 | * @param {String} pType Policy type to save into MongoDB 370 | * @param {Array} rule An array which consists of policy rule elements to store 371 | * @returns {IModel} Returns a created CasbinRule record for MongoDB 372 | */ 373 | savePolicyLine(pType: string, rule: string[]): IModel { 374 | const model = new this.casbinRule({ ptype: pType }); 375 | 376 | if (rule.length > 0) { 377 | model.v0 = rule[0]; 378 | } 379 | 380 | if (rule.length > 1) { 381 | model.v1 = rule[1]; 382 | } 383 | 384 | if (rule.length > 2) { 385 | model.v2 = rule[2]; 386 | } 387 | 388 | if (rule.length > 3) { 389 | model.v3 = rule[3]; 390 | } 391 | 392 | if (rule.length > 4) { 393 | model.v4 = rule[4]; 394 | } 395 | 396 | if (rule.length > 5) { 397 | model.v5 = rule[5]; 398 | } 399 | 400 | return model; 401 | } 402 | 403 | /** 404 | * Implements the process of saving policy from enforcer into database. 405 | * If you are using replica sets with mongo, this function will use mongo 406 | * transaction, so every line in the policy needs tosucceed for this to 407 | * take effect. 408 | * This method is used by casbin and should not be called by user. 409 | * 410 | * @param {Model} model Model instance from enforcer 411 | * @returns {Promise} 412 | */ 413 | async savePolicy(model: Model) { 414 | const options: sessionOption = {}; 415 | if (this.isSynced) options.session = await this.getTransaction(); 416 | 417 | try { 418 | const lines: IModel[] = []; 419 | const policyRuleAST = model.model.get('p') instanceof Map ? model.model.get('p')! : new Map(); 420 | const groupingPolicyAST = 421 | model.model.get('g') instanceof Map ? model.model.get('g')! : new Map(); 422 | 423 | for (const [ptype, ast] of policyRuleAST) { 424 | for (const rule of ast.policy) { 425 | lines.push(this.savePolicyLine(ptype, rule)); 426 | } 427 | } 428 | 429 | for (const [ptype, ast] of groupingPolicyAST) { 430 | for (const rule of ast.policy) { 431 | lines.push(this.savePolicyLine(ptype, rule)); 432 | } 433 | } 434 | 435 | await this.casbinRule.collection.insertMany(lines, options); 436 | 437 | this.autoCommit && options.session && (await options.session.commitTransaction()); 438 | } catch (err) { 439 | this.autoAbort && options.session && (await options.session.abortTransaction()); 440 | console.error(err); 441 | return false; 442 | } 443 | 444 | return true; 445 | } 446 | 447 | /** 448 | * Implements the process of adding policy rule. 449 | * This method is used by casbin and should not be called by user. 450 | * 451 | * @param {String} sec Section of the policy 452 | * @param {String} pType Type of the policy (e.g. "p" or "g") 453 | * @param {Array} rule Policy rule to add into enforcer 454 | * @returns {Promise} 455 | */ 456 | async addPolicy(sec: string, pType: string, rule: string[]): Promise { 457 | const options: sessionOption = {}; 458 | try { 459 | if (this.isSynced) options.session = await this.getTransaction(); 460 | 461 | const line = this.savePolicyLine(pType, rule); 462 | await line.save(options); 463 | 464 | this.autoCommit && options.session && (await options.session.commitTransaction()); 465 | } catch (err) { 466 | this.autoAbort && options.session && (await options.session.abortTransaction()); 467 | throw err; 468 | } 469 | } 470 | 471 | /** 472 | * Implements the process of adding a list of policy rules. 473 | * This method is used by casbin and should not be called by user. 474 | * 475 | * @param {String} sec Section of the policy 476 | * @param {String} pType Type of the policy (e.g. "p" or "g") 477 | * @param {Array} rules Policy rule to add into enforcer 478 | * @returns {Promise} 479 | */ 480 | async addPolicies(sec: string, pType: string, rules: Array): Promise { 481 | const options: sessionOption = {}; 482 | if (this.isSynced) options.session = await this.getTransaction(); 483 | else 484 | throw new InvalidAdapterTypeError( 485 | 'addPolicies is only supported by SyncedAdapter. See newSyncedAdapter' 486 | ); 487 | try { 488 | const promises = rules.map(async (rule) => this.addPolicy(sec, pType, rule)); 489 | await Promise.all(promises); 490 | 491 | this.autoCommit && options.session && (await options.session.commitTransaction()); 492 | } catch (err) { 493 | this.autoAbort && options.session && (await options.session.abortTransaction()); 494 | throw err; 495 | } 496 | } 497 | 498 | /** 499 | * Implements the process of updating policy rule. 500 | * This method is used by casbin and should not be called by user. 501 | * 502 | * @param {String} sec Section of the policy 503 | * @param {String} pType Type of the policy (e.g. "p" or "g") 504 | * @param {Array} oldRule Policy rule to remove from enforcer 505 | * @param {Array} newRule Policy rule to add into enforcer 506 | * @returns {Promise} 507 | */ 508 | async updatePolicy( 509 | sec: string, 510 | pType: string, 511 | oldRule: string[], 512 | newRule: string[] 513 | ): Promise { 514 | const options: sessionOption = {}; 515 | try { 516 | if (this.isSynced) options.session = await this.getTransaction(); 517 | const { ptype, v0, v1, v2, v3, v4, v5 } = this.savePolicyLine(pType, oldRule); 518 | const newRuleLine = this.savePolicyLine(pType, newRule); 519 | const newModel = { 520 | ptype: newRuleLine.ptype, 521 | v0: newRuleLine.v0, 522 | v1: newRuleLine.v1, 523 | v2: newRuleLine.v2, 524 | v3: newRuleLine.v3, 525 | v4: newRuleLine.v4, 526 | v5: newRuleLine.v5 527 | }; 528 | 529 | await this.casbinRule.updateOne({ ptype, v0, v1, v2, v3, v4, v5 }, newModel, options); 530 | 531 | this.autoCommit && options.session && (await options.session.commitTransaction()); 532 | } catch (err) { 533 | this.autoAbort && options.session && (await options.session.abortTransaction()); 534 | throw err; 535 | } 536 | } 537 | 538 | /** 539 | * Implements the process of removing a list of policy rules. 540 | * This method is used by casbin and should not be called by user. 541 | * 542 | * @param {String} sec Section of the policy 543 | * @param {String} pType Type of the policy (e.g. "p" or "g") 544 | * @param {Array} rule Policy rule to remove from enforcer 545 | * @returns {Promise} 546 | */ 547 | async removePolicy(sec: string, pType: string, rule: string[]): Promise { 548 | const options: sessionOption = {}; 549 | try { 550 | if (this.isSynced) options.session = await this.getTransaction(); 551 | 552 | const { ptype, v0, v1, v2, v3, v4, v5 } = this.savePolicyLine(pType, rule); 553 | 554 | await this.casbinRule.deleteMany({ ptype, v0, v1, v2, v3, v4, v5 }, options); 555 | 556 | this.autoCommit && options.session && (await options.session.commitTransaction()); 557 | } catch (err) { 558 | this.autoAbort && options.session && (await options.session.abortTransaction()); 559 | throw err; 560 | } 561 | } 562 | 563 | /** 564 | * Implements the process of removing a policyList rules. 565 | * This method is used by casbin and should not be called by user. 566 | * 567 | * @param {String} sec Section of the policy 568 | * @param {String} pType Type of the policy (e.g. "p" or "g") 569 | * @param {Array} rules Policy rule to remove from enforcer 570 | * @returns {Promise} 571 | */ 572 | async removePolicies(sec: string, pType: string, rules: Array): Promise { 573 | const options: sessionOption = {}; 574 | try { 575 | if (this.isSynced) options.session = await this.getTransaction(); 576 | else 577 | throw new InvalidAdapterTypeError( 578 | 'removePolicies is only supported by SyncedAdapter. See newSyncedAdapter' 579 | ); 580 | 581 | const promises = rules.map(async (rule) => this.removePolicy(sec, pType, rule)); 582 | await Promise.all(promises); 583 | 584 | this.autoCommit && options.session && (await options.session.commitTransaction()); 585 | } catch (err) { 586 | this.autoAbort && options.session && (await options.session.abortTransaction()); 587 | throw err; 588 | } 589 | } 590 | 591 | /** 592 | * Implements the process of removing policy rules. 593 | * This method is used by casbin and should not be called by user. 594 | * 595 | * @param {String} sec Section of the policy 596 | * @param {String} pType Type of the policy (e.g. "p" or "g") 597 | * @param {Number} fieldIndex Index of the field to start filtering from 598 | * @param {...String} fieldValues Policy rule to match when removing (starting from fieldIndex) 599 | * @returns {Promise} 600 | */ 601 | async removeFilteredPolicy( 602 | sec: string, 603 | pType: string, 604 | fieldIndex: number, 605 | ...fieldValues: string[] 606 | ): Promise { 607 | const options: sessionOption = {}; 608 | try { 609 | if (this.isSynced) options.session = await this.getTransaction(); 610 | const where: any = pType ? { ptype: pType } : {}; 611 | 612 | if (fieldIndex <= 0 && fieldIndex + fieldValues.length > 0 && fieldValues[0 - fieldIndex]) { 613 | if (pType === 'g') { 614 | where.$or = [{ v0: fieldValues[0 - fieldIndex] }, { v1: fieldValues[0 - fieldIndex] }]; 615 | } else { 616 | where.v0 = fieldValues[0 - fieldIndex]; 617 | } 618 | } 619 | 620 | if (fieldIndex <= 1 && fieldIndex + fieldValues.length > 1 && fieldValues[1 - fieldIndex]) { 621 | where.v1 = fieldValues[1 - fieldIndex]; 622 | } 623 | 624 | if (fieldIndex <= 2 && fieldIndex + fieldValues.length > 2 && fieldValues[2 - fieldIndex]) { 625 | where.v2 = fieldValues[2 - fieldIndex]; 626 | } 627 | 628 | if (fieldIndex <= 3 && fieldIndex + fieldValues.length > 3 && fieldValues[3 - fieldIndex]) { 629 | where.v3 = fieldValues[3 - fieldIndex]; 630 | } 631 | 632 | if (fieldIndex <= 4 && fieldIndex + fieldValues.length > 4 && fieldValues[4 - fieldIndex]) { 633 | where.v4 = fieldValues[4 - fieldIndex]; 634 | } 635 | 636 | if (fieldIndex <= 5 && fieldIndex + fieldValues.length > 5 && fieldValues[5 - fieldIndex]) { 637 | where.v5 = fieldValues[5 - fieldIndex]; 638 | } 639 | 640 | await this.casbinRule.deleteMany(where, options); 641 | 642 | this.autoCommit && options.session && (await options.session.commitTransaction()); 643 | } catch (err) { 644 | this.autoAbort && options.session && (await options.session.abortTransaction()); 645 | throw err; 646 | } 647 | } 648 | 649 | async close() { 650 | if (this.connection) { 651 | if (this.session) await this.session.endSession(); 652 | await this.connection.close(); 653 | } 654 | } 655 | 656 | /** 657 | * Just for testing. 658 | */ 659 | getCasbinRule() { 660 | return this.casbinRule; 661 | } 662 | } 663 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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) => { 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: collectionName, 63 | minimize: false, 64 | timestamps: timestamps 65 | }); 66 | } 67 | -------------------------------------------------------------------------------- /test/.eslintrc.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "../.eslintrc.json", 3 | "env": { 4 | "mocha": true 5 | } 6 | } 7 | -------------------------------------------------------------------------------- /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/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/fixtures/basic_policy.csv: -------------------------------------------------------------------------------- 1 | p, alice, data1, read 2 | p, bob, data2, write -------------------------------------------------------------------------------- /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/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 -------------------------------------------------------------------------------- /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 -------------------------------------------------------------------------------- /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 -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | --------------------------------------------------------------------------------