├── .eslintrc ├── .github └── workflows │ └── ci.yml ├── .gitignore ├── .prettierrc ├── LICENSE ├── README.md ├── docker-compose.yml ├── examples ├── rbac_model.conf └── rbac_policy.csv ├── jest.config.js ├── mysql_init.sql ├── package.json ├── src ├── adapter.ts └── casbinRule.ts ├── test └── adapter.test.ts ├── tsconfig.json └── yarn.lock /.eslintrc: -------------------------------------------------------------------------------- 1 | { 2 | "root": true, 3 | "parser": "@typescript-eslint/parser", 4 | "plugins": ["@typescript-eslint"], 5 | "extends": [ 6 | "plugin:@typescript-eslint/recommended", 7 | "prettier", 8 | "prettier/@typescript-eslint", 9 | "eslint:recommended" 10 | ], 11 | "rules": { 12 | "@typescript-eslint/array-type": ["error", { "default": "array-simple" }], 13 | "@typescript-eslint/explicit-member-accessibility": ["off"], 14 | "@typescript-eslint/no-non-null-assertion": ["off"], 15 | "@typescript-eslint/no-use-before-define": ["off"], 16 | "@typescript-eslint/no-parameter-properties": ["off"], 17 | "@typescript-eslint/no-unused-vars": [ 18 | "error", 19 | { "argsIgnorePattern": "^_", "varsIgnorePattern": "^_" } 20 | ], 21 | "@typescript-eslint/ban-ts-comment": ["off"], 22 | "@typescript-eslint/no-empty-function": ["off"], 23 | "@typescript-eslint/explicit-function-return-type": ["off"], 24 | "@typescript-eslint/no-explicit-any": ["off"], 25 | "no-unused-vars": ["off"] 26 | }, 27 | "env": { 28 | "node": true, 29 | "jest": true, 30 | "es6": true 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | name: ci 2 | 3 | on: [push, pull_request] 4 | 5 | jobs: 6 | build: 7 | runs-on: ubuntu-latest 8 | 9 | services: 10 | mysql: 11 | image: mysql:latest 12 | ports: 13 | - 3306:3306 14 | env: 15 | MYSQL_ALLOW_EMPTY_PASSWORD: yes 16 | options: --health-cmd="mysqladmin ping" --health-interval=5s --health-timeout=2s --health-retries=3 17 | 18 | steps: 19 | - uses: actions/checkout@v2 20 | - uses: actions/setup-node@v2 21 | with: 22 | node-version: 12 23 | - run: yarn install --frozen-lockfile 24 | - run: mysql --host 127.0.0.1 --port 3306 -uroot -p -e "CREATE DATABASE casbin" 25 | - run: yarn format:check 26 | - run: yarn lint 27 | - run: yarn run jest --coverage --forceExit 28 | - name: Coveralls Parallel 29 | uses: coverallsapp/github-action@master 30 | with: 31 | github-token: ${{ secrets.github_token }} 32 | 33 | finish: 34 | needs: build 35 | runs-on: ubuntu-latest 36 | steps: 37 | - name: Coveralls Finished 38 | uses: coverallsapp/github-action@master 39 | with: 40 | github-token: ${{ secrets.github_token }} 41 | parallel-finished: true 42 | 43 | semantic-release: 44 | needs: [finish, build] 45 | runs-on: ubuntu-latest 46 | services: 47 | mysql: 48 | image: mysql:latest 49 | ports: 50 | - 3306:3306 51 | env: 52 | MYSQL_ALLOW_EMPTY_PASSWORD: yes 53 | options: --health-cmd="mysqladmin ping" --health-interval=5s --health-timeout=2s --health-retries=3 54 | steps: 55 | - uses: actions/checkout@v2 56 | - name: Run semantic-release 57 | if: github.repository == 'node-casbin/sequelize-adapter' && github.event_name == 'push' 58 | run: | 59 | yarn install --frozen-lockfile 60 | mysql --host 127.0.0.1 --port 3306 -uroot -p -e "CREATE DATABASE casbin" 61 | yarn run prepack 62 | yarn run release 63 | env: 64 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 65 | NPM_TOKEN: ${{ secrets.NPM_TOKEN }} 66 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .idea 2 | .vscode 3 | node_modules 4 | lib 5 | yarn-error.log 6 | -------------------------------------------------------------------------------- /.prettierrc: -------------------------------------------------------------------------------- 1 | { 2 | "singleQuote": true, 3 | "endOfLine": "auto" 4 | } 5 | -------------------------------------------------------------------------------- /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 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Sequelize 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-sequelize-adapter-master) 6 | [![ci](https://github.com/node-casbin/sequelize-adapter/actions/workflows/ci.yml/badge.svg)](https://github.com/node-casbin/sequelize-adapter/actions/workflows/ci.yml) 7 | [![Coverage Status](https://coveralls.io/repos/github/node-casbin/sequelize-adapter/badge.svg?branch=master)](https://coveralls.io/github/node-casbin/sequelize-adapter?branch=master) 8 | [![Discord](https://img.shields.io/discord/1022748306096537660?logo=discord&label=discord&color=5865F2)](https://discord.gg/S5UjpzGZjN) 9 | 10 | [npm-image]: https://img.shields.io/npm/v/casbin-sequelize-adapter.svg?style=flat-square 11 | [npm-url]: https://npmjs.org/package/casbin-sequelize-adapter 12 | [download-image]: https://img.shields.io/npm/dm/casbin-sequelize-adapter.svg?style=flat-square 13 | [download-url]: https://npmjs.org/package/casbin-sequelize-adapter 14 | 15 | Sequelize Adapter is the [Sequelize](https://github.com/sequelize/sequelize) adapter for [Node-Casbin](https://github.com/casbin/node-casbin). With this library, Node-Casbin can load policy from Sequelize supported database or save policy to it. 16 | 17 | Based on [Officially Supported Databases](http://docs.sequelizejs.com/), the current supported databases are: 18 | 19 | - PostgreSQL 20 | - MySQL 21 | - SQLite 22 | - MSSQL 23 | 24 | You may find other 3rd-party supported DBs in Sequelize website or other places. 25 | 26 | ## Installation 27 | 28 | NPM Install 29 | 30 | ```bash 31 | npm install casbin-sequelize-adapter --save 32 | ``` 33 | 34 | Yarn Install 35 | 36 | ```bash 37 | yarn add casbin-sequelize-adapter 38 | ``` 39 | 40 | ## Testing Locally 41 | 42 | Start mysql for tests: 43 | 44 | ```bash 45 | docker compose up -d 46 | ``` 47 | 48 | ```bash 49 | yarn test 50 | ``` 51 | 52 | ## Simple Example 53 | 54 | ```typescript 55 | import casbin from 'casbin'; 56 | import { SequelizeAdapter } from 'casbin-sequelize-adapter'; 57 | 58 | async function myFunction() { 59 | // Initialize a Sequelize adapter and use it in a Node-Casbin enforcer: 60 | // The adapter can not automatically create database. 61 | // But the adapter will automatically and use the table named "casbin_rule". 62 | // The second boolean argument: autoCreateTable determines whether the adapter will automatically create the "casbin_rule" table. 63 | // ORM should not create databases automatically. 64 | const a = await SequelizeAdapter.newAdapter( 65 | { 66 | username: 'root', 67 | password: '', 68 | database: 'casbin', 69 | dialect: 'mysql', 70 | }, 71 | true, 72 | ); 73 | 74 | const e = await casbin.newEnforcer('examples/rbac_model.conf', a); 75 | 76 | // Check the permission. 77 | e.enforce('alice', 'data1', 'read'); 78 | 79 | // Modify the policy. 80 | // await e.addPolicy(...); 81 | // await e.removePolicy(...); 82 | 83 | // Save the policy back to DB. 84 | await e.savePolicy(); 85 | } 86 | ``` 87 | 88 | ## Getting Help 89 | 90 | - [Node-Casbin](https://github.com/casbin/node-casbin) 91 | 92 | ## License 93 | 94 | This project is under Apache 2.0 License. See the [LICENSE](LICENSE) file for the full license text. 95 | -------------------------------------------------------------------------------- /docker-compose.yml: -------------------------------------------------------------------------------- 1 | # Use root/example as user/password credentials 2 | version: '3.1' 3 | 4 | services: 5 | db: 6 | image: mysql:latest 7 | restart: always 8 | ports: 9 | - 3306:3306 10 | environment: 11 | MYSQL_ALLOW_EMPTY_PASSWORD: yes 12 | volumes: 13 | - ./mysql_init.sql:/docker-entrypoint-initdb.d/mysql_init.sql 14 | -------------------------------------------------------------------------------- /examples/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 -------------------------------------------------------------------------------- /examples/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 -------------------------------------------------------------------------------- /jest.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | testEnvironment: 'node', 3 | transform: { 4 | '^.+\\.(ts|tsx)$': 'ts-jest', 5 | }, 6 | moduleNameMapper: { 7 | 'csv-parse': '/node_modules/csv-parse/dist/cjs/sync.cjs', 8 | }, 9 | moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json'], 10 | }; 11 | -------------------------------------------------------------------------------- /mysql_init.sql: -------------------------------------------------------------------------------- 1 | CREATE DATABASE casbin; 2 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "casbin-sequelize-adapter", 3 | "version": "2.2.0", 4 | "description": "Sequelize adapter for Casbin", 5 | "main": "lib/adapter.js", 6 | "typings": "lib/adapter.d.ts", 7 | "scripts": { 8 | "precommit": "lint-staged", 9 | "build": "rimraf lib && tsc", 10 | "lint": "eslint --ext .ts src/ test/", 11 | "test": "jest --forceExit", 12 | "format": "yarn format:check --write", 13 | "format:check": "prettier --check \"{src,test}/**/*.ts\"", 14 | "prepack": "run-s lint build", 15 | "release": "npx -p semantic-release -p @semantic-release/git -p @semantic-release/changelog semantic-release" 16 | }, 17 | "devDependencies": { 18 | "@types/jest": "^25.2.3", 19 | "@types/node": "^14.14.37", 20 | "@types/validator": "^13.1.3", 21 | "@typescript-eslint/eslint-plugin": "5.55.0", 22 | "@typescript-eslint/parser": "5.55.0", 23 | "casbin": "<=5.9.0 || >5.9.1", 24 | "coveralls": "^3.1.0", 25 | "eslint": "^7.2.0", 26 | "eslint-config-prettier": "^6.11.0", 27 | "husky": "^4.2.5", 28 | "jest": "^26.0.1", 29 | "lint-staged": "^10.2.9", 30 | "mysql2": "^2.1.0", 31 | "npm-run-all": "^4.1.5", 32 | "prettier": "^2.0.5", 33 | "rimraf": "^3.0.2", 34 | "ts-jest": "^26.1.0", 35 | "tslint": "^6.1.2", 36 | "typescript": "^4.9.5" 37 | }, 38 | "peerDependencies": { 39 | "casbin": "<=5.9.0 || >5.9.1" 40 | }, 41 | "dependencies": { 42 | "reflect-metadata": "^0.1.13", 43 | "sequelize": "6.29.3", 44 | "sequelize-typescript": "^2.1.6" 45 | }, 46 | "files": [ 47 | "lib", 48 | "examples" 49 | ], 50 | "homepage": "https://casbin.org", 51 | "repository": { 52 | "type": "git", 53 | "url": "https://github.com/node-casbin/sequelize-adapter.git" 54 | }, 55 | "keywords": [ 56 | "casbin", 57 | "node-casbin", 58 | "adapter", 59 | "sequelize", 60 | "access-control", 61 | "authorization", 62 | "auth", 63 | "authz", 64 | "acl", 65 | "rbac", 66 | "abac", 67 | "orm" 68 | ], 69 | "author": "Node-Casbin", 70 | "licenses": [ 71 | { 72 | "type": "Apache-2.0", 73 | "url": "http://www.apache.org/licenses/LICENSE-2.0" 74 | } 75 | ], 76 | "bugs": { 77 | "url": "https://github.com/node-casbin/sequelize-adapter/issues" 78 | }, 79 | "lint-staged": { 80 | "*.{ts}": [ 81 | "tslint --fix", 82 | "git add" 83 | ] 84 | }, 85 | "publishConfig": { 86 | "registry": "https://registry.yarnpkg.com" 87 | }, 88 | "jest": { 89 | "testURL": "http://localhost", 90 | "transform": { 91 | "^.+\\.(ts|tsx)$": "ts-jest" 92 | }, 93 | "testMatch": [ 94 | "**/test/*.+(ts|tsx)" 95 | ], 96 | "moduleFileExtensions": [ 97 | "ts", 98 | "tsx", 99 | "js", 100 | "jsx", 101 | "json", 102 | "node" 103 | ] 104 | } 105 | } 106 | -------------------------------------------------------------------------------- /src/adapter.ts: -------------------------------------------------------------------------------- 1 | // Copyright 2018 The Casbin Authors. 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 { Adapter, Helper, Model } from 'casbin'; 16 | import { Op } from 'sequelize'; 17 | import { Sequelize, SequelizeOptions } from 'sequelize-typescript'; 18 | import { createCasbinRule, CasbinRule } from './casbinRule'; 19 | 20 | export interface SequelizeAdapterOptions extends SequelizeOptions { 21 | tableName?: string; 22 | schema?: string; 23 | } 24 | 25 | /** 26 | * SequelizeAdapter represents the Sequelize adapter for policy storage. 27 | */ 28 | export class SequelizeAdapter implements Adapter { 29 | private readonly option: SequelizeAdapterOptions; 30 | private sequelize: Sequelize; 31 | private filtered = false; 32 | private autoCreateTable = true; 33 | private CasbinRule: typeof CasbinRule; 34 | 35 | constructor(option: SequelizeAdapterOptions, autoCreateTable = true) { 36 | this.option = option; 37 | this.autoCreateTable = autoCreateTable; 38 | } 39 | 40 | public isFiltered(): boolean { 41 | return this.filtered; 42 | } 43 | 44 | public enabledFiltered(enabled: boolean): void { 45 | this.filtered = enabled; 46 | } 47 | 48 | /** 49 | * newAdapter is the constructor. 50 | * @param option sequelize connection option 51 | */ 52 | public static async newAdapter( 53 | option: SequelizeAdapterOptions, 54 | autoCreateTable?: boolean 55 | ): Promise { 56 | const a = new SequelizeAdapter(option, autoCreateTable); 57 | await a.open(); 58 | 59 | return a; 60 | } 61 | 62 | private async open(): Promise { 63 | this.sequelize = new Sequelize(this.option); 64 | this.CasbinRule = createCasbinRule( 65 | this.option.tableName, 66 | this.option.schema 67 | ); // Set the property here 68 | await this.sequelize.authenticate(); 69 | this.sequelize.addModels([this.CasbinRule]); 70 | if (this.autoCreateTable) { 71 | await this.createTable(); 72 | } 73 | } 74 | 75 | public async close(): Promise { 76 | await this.sequelize.close(); 77 | } 78 | 79 | private async createTable(): Promise { 80 | await this.sequelize.sync(); 81 | } 82 | 83 | private loadPolicyLine(line: CasbinRule, model: Model): void { 84 | const result = 85 | line.ptype + 86 | ', ' + 87 | [line.v0, line.v1, line.v2, line.v3, line.v4, line.v5] 88 | .filter((n) => n) 89 | .join(', '); 90 | Helper.loadPolicyLine(result, model); 91 | } 92 | 93 | /** 94 | * loadPolicy loads all policy rules from the storage. 95 | */ 96 | public async loadPolicy(model: Model): Promise { 97 | const lines = await this.sequelize.getRepository(this.CasbinRule).findAll(); 98 | 99 | for (const line of lines) { 100 | this.loadPolicyLine(line, model); 101 | } 102 | } 103 | 104 | private savePolicyLine(ptype: string, rule: string[]): CasbinRule { 105 | const line = new this.CasbinRule(); 106 | 107 | line.ptype = ptype; 108 | if (rule.length > 0) { 109 | line.v0 = rule[0]; 110 | } 111 | if (rule.length > 1) { 112 | line.v1 = rule[1]; 113 | } 114 | if (rule.length > 2) { 115 | line.v2 = rule[2]; 116 | } 117 | if (rule.length > 3) { 118 | line.v3 = rule[3]; 119 | } 120 | if (rule.length > 4) { 121 | line.v4 = rule[4]; 122 | } 123 | if (rule.length > 5) { 124 | line.v5 = rule[5]; 125 | } 126 | 127 | return line; 128 | } 129 | 130 | /** 131 | * savePolicy saves all policy rules to the storage. 132 | */ 133 | public async savePolicy(model: Model): Promise { 134 | await this.sequelize.transaction(async (tx) => { 135 | // truncate casbin table 136 | await this.sequelize 137 | .getRepository(this.CasbinRule) 138 | .destroy({ where: {}, truncate: true, transaction: tx }); 139 | 140 | const lines: CasbinRule[] = []; 141 | 142 | let astMap = model.model.get('p')!; 143 | for (const [ptype, ast] of astMap) { 144 | for (const rule of ast.policy) { 145 | const line = this.savePolicyLine(ptype, rule); 146 | lines.push(line); 147 | } 148 | } 149 | 150 | astMap = model.model.get('g')!; 151 | for (const [ptype, ast] of astMap) { 152 | for (const rule of ast.policy) { 153 | const line = this.savePolicyLine(ptype, rule); 154 | lines.push(line); 155 | } 156 | } 157 | 158 | await this.CasbinRule.bulkCreate( 159 | lines.map((l) => l.get({ plain: true })), 160 | { transaction: tx } 161 | ); 162 | }); 163 | return true; 164 | } 165 | 166 | /** 167 | * addPolicy adds a policy rule to the storage. 168 | */ 169 | public async addPolicy( 170 | sec: string, 171 | ptype: string, 172 | rule: string[] 173 | ): Promise { 174 | const line = this.savePolicyLine(ptype, rule); 175 | await line.save(); 176 | } 177 | 178 | /** 179 | * addPolicies adds a policyList rules to the storage. 180 | */ 181 | public async addPolicies( 182 | sec: string, 183 | ptype: string, 184 | rules: string[][] 185 | ): Promise { 186 | const lines: CasbinRule[] = []; 187 | for (const rule of rules) { 188 | const line = this.savePolicyLine(ptype, rule); 189 | lines.push(line); 190 | } 191 | await this.sequelize.transaction(async (tx) => { 192 | await this.CasbinRule.bulkCreate( 193 | lines.map((l) => l.get({ plain: true })), 194 | { transaction: tx } 195 | ); 196 | }); 197 | } 198 | 199 | /** 200 | * removePolicies removes a policyList rule from the storage. 201 | */ 202 | public async removePolicy( 203 | sec: string, 204 | ptype: string, 205 | rule: string[] 206 | ): Promise { 207 | const line = this.savePolicyLine(ptype, rule); 208 | const where = {}; 209 | 210 | Object.keys(line.get({ plain: true })) 211 | .filter((key) => key !== 'id') 212 | .forEach((key) => { 213 | // @ts-ignore 214 | where[key] = line[key]; 215 | }); 216 | 217 | await this.sequelize.getRepository(this.CasbinRule).destroy({ where }); 218 | } 219 | 220 | /** 221 | * removePolicies removes a policyList rule from the storage. 222 | */ 223 | public async removePolicies( 224 | sec: string, 225 | ptype: string, 226 | rules: string[][] 227 | ): Promise { 228 | await this.sequelize.transaction(async (tx) => { 229 | for (const rule of rules) { 230 | const line = this.savePolicyLine(ptype, rule); 231 | const where = {}; 232 | 233 | Object.keys(line.get({ plain: true })) 234 | .filter((key) => key !== 'id') 235 | .forEach((key) => { 236 | // @ts-ignore 237 | where[key] = line[key]; 238 | }); 239 | 240 | await this.sequelize 241 | .getRepository(this.CasbinRule) 242 | .destroy({ where, transaction: tx }); 243 | } 244 | }); 245 | } 246 | 247 | /** 248 | * loadFilteredPolicy loads policy rules that match the filter from the storage; 249 | * use an empty string for selecting all values in a certain field. 250 | */ 251 | public async loadFilteredPolicy( 252 | model: Model, 253 | filter: { [key: string]: string[][] } 254 | ): Promise { 255 | const whereStatements = Object.keys(filter).map((ptype) => { 256 | const policyPatterns = filter[ptype]; 257 | return policyPatterns.map((policyPattern) => { 258 | return { 259 | ptype, 260 | ...(policyPattern[0] && { v0: policyPattern[0] }), 261 | ...(policyPattern[1] && { v1: policyPattern[1] }), 262 | ...(policyPattern[2] && { v2: policyPattern[2] }), 263 | ...(policyPattern[3] && { v3: policyPattern[3] }), 264 | ...(policyPattern[4] && { v4: policyPattern[4] }), 265 | ...(policyPattern[5] && { v5: policyPattern[5] }), 266 | }; 267 | }); 268 | }); 269 | 270 | const where = { 271 | [Op.or]: whereStatements.reduce( 272 | (accumulator, value) => accumulator.concat(value), 273 | [] 274 | ), 275 | }; 276 | 277 | const lines = await this.sequelize 278 | .getRepository(this.CasbinRule) 279 | .findAll({ where }); 280 | 281 | lines.forEach((line) => this.loadPolicyLine(line, model)); 282 | this.enabledFiltered(true); 283 | } 284 | 285 | /** 286 | * removeFilteredPolicy removes policy rules that match the filter from the storage. 287 | */ 288 | public async removeFilteredPolicy( 289 | sec: string, 290 | ptype: string, 291 | fieldIndex: number, 292 | ...fieldValues: string[] 293 | ): Promise { 294 | const line = new this.CasbinRule(); 295 | line.ptype = ptype; 296 | 297 | const idx = fieldIndex + fieldValues.length; 298 | if (fieldIndex <= 0 && 0 < idx) { 299 | line.v0 = fieldValues[0 - fieldIndex]; 300 | } 301 | if (fieldIndex <= 1 && 1 < idx) { 302 | line.v1 = fieldValues[1 - fieldIndex]; 303 | } 304 | if (fieldIndex <= 2 && 2 < idx) { 305 | line.v2 = fieldValues[2 - fieldIndex]; 306 | } 307 | if (fieldIndex <= 3 && 3 < idx) { 308 | line.v3 = fieldValues[3 - fieldIndex]; 309 | } 310 | if (fieldIndex <= 4 && 4 < idx) { 311 | line.v4 = fieldValues[4 - fieldIndex]; 312 | } 313 | if (fieldIndex <= 5 && 5 < idx) { 314 | line.v5 = fieldValues[5 - fieldIndex]; 315 | } 316 | 317 | const where = {}; 318 | 319 | Object.keys(line.get({ plain: true })) 320 | .filter((key) => key !== 'id') 321 | .forEach((key) => { 322 | // @ts-ignore 323 | where[key] = line[key]; 324 | }); 325 | 326 | await this.sequelize.getRepository(this.CasbinRule).destroy({ 327 | where, 328 | }); 329 | } 330 | } 331 | -------------------------------------------------------------------------------- /src/casbinRule.ts: -------------------------------------------------------------------------------- 1 | // Copyright 2018 The Casbin Authors. 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 { 16 | Table, 17 | Column, 18 | Model, 19 | getOptions, 20 | setOptions, 21 | } from 'sequelize-typescript'; 22 | 23 | @Table({ timestamps: false }) 24 | export class CasbinRule extends Model { 25 | @Column 26 | public ptype: string; 27 | 28 | @Column 29 | public v0: string; 30 | 31 | @Column 32 | public v1: string; 33 | 34 | @Column 35 | public v2: string; 36 | 37 | @Column 38 | public v3: string; 39 | 40 | @Column 41 | public v4: string; 42 | 43 | @Column 44 | public v5: string; 45 | } 46 | 47 | export function createCasbinRule( 48 | tableName = 'casbin_rule', 49 | schema?: string 50 | ): typeof CasbinRule { 51 | class CustomCasbinRule extends CasbinRule {} 52 | 53 | const options = getOptions(CustomCasbinRule.prototype); 54 | options!.tableName = tableName; 55 | options!.schema = schema; 56 | setOptions(CustomCasbinRule.prototype, options!); 57 | 58 | return CustomCasbinRule; 59 | } 60 | -------------------------------------------------------------------------------- /test/adapter.test.ts: -------------------------------------------------------------------------------- 1 | // Copyright 2018 The Casbin Authors. 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 { newEnforcer, Enforcer, Util } from 'casbin'; 16 | import { SequelizeAdapter } from '../src/adapter'; 17 | 18 | async function testGetPolicy(e: Enforcer, res: string[][]): Promise { 19 | const myRes = await e.getPolicy(); 20 | console.log('Policy: ', myRes); 21 | 22 | expect(Util.array2DEquals(res, myRes)).toBe(true); 23 | } 24 | 25 | async function testGetGroupingPolicy( 26 | e: Enforcer, 27 | res: string[][] 28 | ): Promise { 29 | const myRes = await e.getGroupingPolicy(); 30 | console.log('GroupingPolicy: ', myRes); 31 | 32 | expect(Util.array2DEquals(res, myRes)).toBe(true); 33 | } 34 | 35 | test( 36 | 'TestAdapter', 37 | async () => { 38 | const a = await SequelizeAdapter.newAdapter({ 39 | username: 'root', 40 | password: '', 41 | database: 'casbin', 42 | dialect: 'mysql', 43 | tableName: 'something', 44 | }); 45 | 46 | try { 47 | // Because the DB is empty at first, 48 | // so we need to load the policy from the file adapter (.CSV) first. 49 | let e = await newEnforcer( 50 | 'examples/rbac_model.conf', 51 | 'examples/rbac_policy.csv' 52 | ); 53 | 54 | // This is a trick to save the current policy to the DB. 55 | // We can't call e.savePolicy() because the adapter in the enforcer is still the file adapter. 56 | // The current policy means the policy in the Node-Casbin enforcer (aka in memory). 57 | await a.savePolicy(e.getModel()); 58 | 59 | // Clear the current policy. 60 | e.clearPolicy(); 61 | testGetPolicy(e, []); 62 | 63 | // Load the policy from DB. 64 | await a.loadPolicy(e.getModel()); 65 | testGetPolicy(e, [ 66 | ['alice', 'data1', 'read'], 67 | ['bob', 'data2', 'write'], 68 | ['data2_admin', 'data2', 'read'], 69 | ['data2_admin', 'data2', 'write'], 70 | ]); 71 | 72 | // Note: you don't need to look at the above code 73 | // if you already have a working DB with policy inside. 74 | 75 | // Now the DB has policy, so we can provide a normal use case. 76 | // Create an adapter and an enforcer. 77 | // newEnforcer() will load the policy automatically. 78 | e = await newEnforcer('examples/rbac_model.conf', a); 79 | testGetPolicy(e, [ 80 | ['alice', 'data1', 'read'], 81 | ['bob', 'data2', 'write'], 82 | ['data2_admin', 'data2', 'read'], 83 | ['data2_admin', 'data2', 'write'], 84 | ]); 85 | 86 | // Add policy to DB 87 | await a.addPolicy('', 'p', ['role', 'res', 'action']); 88 | e = await newEnforcer('examples/rbac_model.conf', a); 89 | testGetPolicy(e, [ 90 | ['alice', 'data1', 'read'], 91 | ['bob', 'data2', 'write'], 92 | ['data2_admin', 'data2', 'read'], 93 | ['data2_admin', 'data2', 'write'], 94 | ['role', 'res', 'action'], 95 | ]); 96 | 97 | // Add policyList to DB 98 | await a.addPolicies('', 'p', [ 99 | ['role', 'res', 'GET'], 100 | ['role', 'res', 'POST'], 101 | ]); 102 | e = await newEnforcer('examples/rbac_model.conf', a); 103 | testGetPolicy(e, [ 104 | ['alice', 'data1', 'read'], 105 | ['bob', 'data2', 'write'], 106 | ['data2_admin', 'data2', 'read'], 107 | ['data2_admin', 'data2', 'write'], 108 | ['role', 'res', 'action'], 109 | ['role', 'res', 'GET'], 110 | ['role', 'res', 'POST'], 111 | ]); 112 | 113 | // Remove policy from DB 114 | await a.removePolicy('', 'p', ['role', 'res', 'action']); 115 | e = await newEnforcer('examples/rbac_model.conf', a); 116 | testGetPolicy(e, [ 117 | ['alice', 'data1', 'read'], 118 | ['bob', 'data2', 'write'], 119 | ['data2_admin', 'data2', 'read'], 120 | ['data2_admin', 'data2', 'write'], 121 | ['role', 'res', 'GET'], 122 | ['role', 'res', 'POST'], 123 | ]); 124 | 125 | // Remove policyList from DB 126 | await a.removePolicies('', 'p', [ 127 | ['role', 'res', 'GET'], 128 | ['role', 'res', 'POST'], 129 | ]); 130 | e = await newEnforcer('examples/rbac_model.conf', a); 131 | testGetPolicy(e, [ 132 | ['alice', 'data1', 'read'], 133 | ['bob', 'data2', 'write'], 134 | ['data2_admin', 'data2', 'read'], 135 | ['data2_admin', 'data2', 'write'], 136 | ]); 137 | 138 | await a.removeFilteredPolicy('', 'p', 0, 'alice'); 139 | e = await newEnforcer('examples/rbac_model.conf', a); 140 | testGetPolicy(e, [ 141 | ['bob', 'data2', 'write'], 142 | ['data2_admin', 'data2', 'read'], 143 | ['data2_admin', 'data2', 'write'], 144 | ]); 145 | 146 | testGetGroupingPolicy(e, [['alice', 'data2_admin']]); 147 | 148 | // Remove groupingPolicy from DB 149 | await e.deleteUser('alice'); 150 | testGetGroupingPolicy(e, []); 151 | 152 | // Clear the current policy. 153 | e.clearPolicy(); 154 | testGetPolicy(e, []); 155 | 156 | // test load simple filtered policy 157 | await a.loadFilteredPolicy(e.getModel(), { 158 | p: [['data2_admin']], 159 | }); 160 | testGetPolicy(e, [ 161 | ['data2_admin', 'data2', 'read'], 162 | ['data2_admin', 'data2', 'write'], 163 | ]); 164 | 165 | // Clear the current policy. 166 | e.clearPolicy(); 167 | testGetPolicy(e, []); 168 | 169 | // test load filtered policy 170 | await a.loadFilteredPolicy(e.getModel(), { 171 | p: [['data2_admin']], 172 | }); 173 | testGetPolicy(e, [ 174 | ['data2_admin', 'data2', 'read'], 175 | ['data2_admin', 'data2', 'write'], 176 | ]); 177 | 178 | // Clear the current policy. 179 | e.clearPolicy(); 180 | testGetPolicy(e, []); 181 | 182 | // test load filtered policy 183 | await a.loadFilteredPolicy(e.getModel(), { 184 | p: [['data2_admin'], ['bob']], 185 | }); 186 | testGetPolicy(e, [ 187 | ['bob', 'data2', 'write'], 188 | ['data2_admin', 'data2', 'read'], 189 | ['data2_admin', 'data2', 'write'], 190 | ]); 191 | 192 | // Clear the current policy. 193 | e.clearPolicy(); 194 | testGetPolicy(e, []); 195 | } finally { 196 | await a.close(); 197 | } 198 | }, 199 | 60 * 1000 200 | ); 201 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "target": "es6", 4 | "module": "commonjs", 5 | "moduleResolution": "node", 6 | "declaration": true, 7 | "declarationDir": "lib", 8 | "strict": true, 9 | "outDir": "lib", 10 | "strictPropertyInitialization": false, 11 | "experimentalDecorators": true, 12 | "emitDecoratorMetadata": true 13 | }, 14 | "include": ["src/**/*.ts"] 15 | } 16 | --------------------------------------------------------------------------------