├── .github ├── semantic.yml └── workflows │ └── build.yml ├── .gitignore ├── .releaserc.yml ├── LICENSE ├── README.md ├── composer.json ├── config ├── casbin-basic-model.conf └── permission.php ├── phpunit.xml ├── src ├── Adapter.php ├── Permission.php ├── components │ ├── PermissionChecker.php │ ├── PermissionControl.php │ └── PermissionPolicy.php └── models │ └── CasbinRule.php └── tests ├── AdapterTest.php ├── LocalizationTest.php ├── TestCase.php ├── support ├── TestController.php └── UserIdentity.php └── test.php /.github/semantic.yml: -------------------------------------------------------------------------------- 1 | # Always validate the PR title AND all the commits 2 | titleAndCommits: true 3 | -------------------------------------------------------------------------------- /.github/workflows/build.yml: -------------------------------------------------------------------------------- 1 | name: build 2 | 3 | on: 4 | push: 5 | branches: [ master ] 6 | pull_request: 7 | branches: [ master ] 8 | 9 | jobs: 10 | test: 11 | runs-on: ubuntu-latest 12 | 13 | services: 14 | mysql: 15 | image: mysql:5.7 16 | env: 17 | MYSQL_ALLOW_EMPTY_PASSWORD: yes 18 | MYSQL_DATABASE: casbin 19 | ports: 20 | - 3306:3306 21 | options: --health-cmd="mysqladmin ping" --health-interval=10s --health-timeout=5s --health-retries=3 22 | 23 | strategy: 24 | fail-fast: true 25 | matrix: 26 | php: [ 8.0, 8.1, 8.2, 8.3 ] 27 | stability: [ prefer-lowest, prefer-stable ] 28 | 29 | name: PHP ${{ matrix.php }} - ${{ matrix.stability }} 30 | 31 | steps: 32 | - name: Checkout code 33 | uses: actions/checkout@v2 34 | 35 | - name: Setup PHP 36 | uses: shivammathur/setup-php@v2 37 | with: 38 | php-version: ${{ matrix.php }} 39 | tools: composer:v2 40 | coverage: xdebug 41 | 42 | - name: Validate composer.json and composer.lock 43 | run: composer validate 44 | 45 | - name: Install dependencies 46 | if: steps.composer-cache.outputs.cache-hit != 'true' 47 | run: | 48 | composer install --prefer-dist --no-progress --no-suggest 49 | 50 | - name: Run test suite 51 | run: ./vendor/bin/phpunit 52 | 53 | - name: Run Coveralls 54 | env: 55 | COVERALLS_REPO_TOKEN: ${{ secrets.GITHUB_TOKEN }} 56 | COVERALLS_PARALLEL: true 57 | COVERALLS_FLAG_NAME: ${{ runner.os }} - ${{ matrix.php }} 58 | run: | 59 | composer global require php-coveralls/php-coveralls:^2.4 60 | php-coveralls --coverage_clover=build/logs/clover.xml -v 61 | 62 | upload-coverage: 63 | runs-on: ubuntu-latest 64 | needs: [ test ] 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 | semantic-release: 73 | runs-on: ubuntu-latest 74 | needs: [ test, upload-coverage ] 75 | steps: 76 | - uses: actions/checkout@v2 77 | - uses: actions/setup-node@v2 78 | with: 79 | node-version: 'lts/*' 80 | 81 | - name: Run semantic-release 82 | env: 83 | GITHUB_TOKEN: ${{ secrets.GH_TOKEN }} 84 | run: npx semantic-release 85 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /vendor/ 2 | 3 | composer.lock 4 | 5 | .idea/ 6 | *.iml 7 | 8 | # coverage report 9 | /build 10 | .phpunit* -------------------------------------------------------------------------------- /.releaserc.yml: -------------------------------------------------------------------------------- 1 | plugins: 2 | - "@semantic-release/commit-analyzer" 3 | - "@semantic-release/release-notes-generator" 4 | - "@semantic-release/github" -------------------------------------------------------------------------------- /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 | # Yii-Permission 2 | 3 | [![Build Status](https://github.com/php-casbin/yii-permission/actions/workflows/build.yml/badge.svg?branch=master)](https://github.com/php-casbin/yii-permission/actions/workflows/build.yml) 4 | [![Coverage Status](https://coveralls.io/repos/github/php-casbin/yii-permission/badge.svg)](https://coveralls.io/github/php-casbin/yii-permission) 5 | [![Latest Stable Version](https://poser.pugx.org/casbin/yii-permission/v/stable)](https://packagist.org/packages/casbin/yii-permission) 6 | [![Total Downloads](https://poser.pugx.org/casbin/yii-permission/downloads)](https://packagist.org/packages/casbin/yii-permission) 7 | [![License](https://poser.pugx.org/casbin/yii-permission/license)](https://packagist.org/packages/casbin/yii-permission) 8 | 9 | Use [Casbin](https://github.com/php-casbin/php-casbin) in Yii 2.0 PHP Framework. 10 | 11 | ## Installation 12 | 13 | ### Getting Composer package 14 | 15 | Require this package in the `composer.json` of your Yii 2.0 project. This will download the package. 16 | 17 | ``` 18 | composer require casbin/yii-permission 19 | ``` 20 | 21 | ### Configuring application 22 | 23 | To use this extension, you have to configure the `Casbin` class in your application configuration: 24 | 25 | ```php 26 | return [ 27 | //.... 28 | 'components' => [ 29 | 'permission' => [ 30 | 'class' => \yii\permission\Permission::class, 31 | 32 | /* 33 | * Casbin model setting. 34 | */ 35 | 'model' => [ 36 | // Available Settings: "file", "text" 37 | 'config_type' => 'file', 38 | 'config_file_path' => '/path/to/casbin-model.conf', 39 | 'config_text' => '', 40 | ], 41 | 42 | // Casbin adapter . 43 | 'adapter' => \yii\permission\Adapter::class, 44 | 45 | /* 46 | * Casbin database setting. 47 | */ 48 | 'database' => [ 49 | // Database connection for following tables. 50 | 'connection' => '', 51 | // CasbinRule tables and model. 52 | 'casbin_rules_table' => '{{%casbin_rule}}', 53 | ], 54 | ], 55 | ] 56 | ]; 57 | ``` 58 | 59 | 60 | ## Usage 61 | 62 | ### Quick start 63 | 64 | Once installed you can do stuff like this: 65 | 66 | ```php 67 | 68 | $permission = \Yii::$app->permission; 69 | 70 | // adds permissions to a user 71 | $permission->addPermissionForUser('eve', 'articles', 'read'); 72 | // adds a role for a user. 73 | $permission->addRoleForUser('eve', 'writer'); 74 | // adds permissions to a rule 75 | $permission->addPolicy('writer', 'articles','edit'); 76 | 77 | ``` 78 | 79 | You can check if a user has a permission like this: 80 | 81 | ```php 82 | // to check if a user has permission 83 | if ($permission->enforce("eve", "articles", "edit")) { 84 | // permit eve to edit articles 85 | } else { 86 | // deny the request, show an error 87 | } 88 | 89 | ``` 90 | 91 | ### Using Enforcer Api 92 | 93 | It provides a very rich api to facilitate various operations on the Policy: 94 | 95 | Gets all roles: 96 | 97 | ```php 98 | $permission->getAllRoles(); // ['writer', 'reader'] 99 | ``` 100 | 101 | Gets all the authorization rules in the policy.: 102 | 103 | ```php 104 | $permission->getPolicy(); 105 | ``` 106 | 107 | Gets the roles that a user has. 108 | 109 | ```php 110 | $permission->getRolesForUser('eve'); // ['writer'] 111 | ``` 112 | 113 | Gets the users that has a role. 114 | 115 | ```php 116 | $permission->getUsersForRole('writer'); // ['eve'] 117 | ``` 118 | 119 | Determines whether a user has a role. 120 | 121 | ```php 122 | $permission->hasRoleForUser('eve', 'writer'); // true or false 123 | ``` 124 | 125 | Adds a role for a user. 126 | 127 | ```php 128 | $permission->addRoleForUser('eve', 'writer'); 129 | ``` 130 | 131 | Adds a permission for a user or role. 132 | 133 | ```php 134 | // to user 135 | $permission->addPermissionForUser('eve', 'articles', 'read'); 136 | // to role 137 | $permission->addPermissionForUser('writer', 'articles','edit'); 138 | ``` 139 | 140 | Deletes a role for a user. 141 | 142 | ```php 143 | $permission->deleteRoleForUser('eve', 'writer'); 144 | ``` 145 | 146 | Deletes all roles for a user. 147 | 148 | ```php 149 | $permission->deleteRolesForUser('eve'); 150 | ``` 151 | 152 | Deletes a role. 153 | 154 | ```php 155 | $permission->deleteRole('writer'); 156 | ``` 157 | 158 | Deletes a permission. 159 | 160 | ```php 161 | $permission->deletePermission('articles', 'read'); // returns false if the permission does not exist (aka not affected). 162 | ``` 163 | 164 | Deletes a permission for a user or role. 165 | 166 | ```php 167 | $permission->deletePermissionForUser('eve', 'articles', 'read'); 168 | ``` 169 | 170 | Deletes permissions for a user or role. 171 | 172 | ```php 173 | // to user 174 | $permission->deletePermissionsForUser('eve'); 175 | // to role 176 | $permission->deletePermissionsForUser('writer'); 177 | ``` 178 | 179 | Gets permissions for a user or role. 180 | 181 | ```php 182 | $permission->getPermissionsForUser('eve'); // return array 183 | ``` 184 | 185 | Determines whether a user has a permission. 186 | 187 | ```php 188 | $permission->hasPermissionForUser('eve', 'articles', 'read'); // true or false 189 | ``` 190 | 191 | ### Using Yii Authorization 192 | 193 | It allows you to integrate Yii's authorization with the Casbin permission management system. 194 | 195 | **(1) AccessChecker** 196 | 197 | Add the accessChecker configuration in your application's `config/web.php` file: 198 | 199 | ```php 200 | $config = [ 201 | 'components' => [ 202 | 'user' => [ 203 | ... 204 | 'accessChecker' => 'yii\permission\components\PermissionChecker', 205 | ] 206 | ]; 207 | ``` 208 | 209 | Once configured, you can use the `can()` method to check if a user has permission to perform certain actions: 210 | 211 | ```php 212 | $user->can('acrticles,read'); 213 | ``` 214 | 215 | **(2) Behaviors** 216 | 217 | The `PermissionControl` behavior allows you to enforce permission checks at the controller level. Add the PermissionControl behavior to your controller's behaviors() method: 218 | 219 | ```php 220 | public function behaviors() 221 | { 222 | return [ 223 | 'permission' => [ 224 | 'class' => \yii\permission\components\PermissionControl::class, 225 | 'user' => $user, // optional, defaults to \Yii::$app->user 226 | 'only' => ['read-articles', 'write-articles'], 227 | 'policy' => [ 228 | [ 229 | 'allow' => true, 230 | 'actions' => ['read-articles'], 231 | 'enforce' => ['articles', 'read'] 232 | ], 233 | [ 234 | 'allow' => true, 235 | 'actions' => ['write-articles'], 236 | 'enforce' => ['articles', 'write'] 237 | ] 238 | ], 239 | 'denyCallback' => function ($policy, $action) { 240 | // custom action when access is denied 241 | } // optional, defaults to throwing an exception 242 | ] 243 | ]; 244 | } 245 | ``` 246 | 247 | **Note:** Additionally,You can also configure a `denyCallback` for each `policy`, which will be invoked when the user does not meet the required permission. This callback takes precedence. The configuration is similar to Yii's official [AccessControl](https://www.yiiframework.com/doc/guide/2.0/en/security-authorization#access-control-filter). 248 | 249 | See [Casbin API](https://casbin.org/docs/en/management-api) for more APIs. 250 | 251 | ## Define your own model.conf 252 | 253 | [Supported models](https://github.com/php-casbin/php-casbin#supported-models). 254 | 255 | ## Learning Casbin 256 | 257 | You can find the full documentation of Casbin [on the website](https://casbin.org/). 258 | -------------------------------------------------------------------------------- /composer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "casbin/yii-permission", 3 | "keywords": [ 4 | "casbin", 5 | "yii", 6 | "rbac", 7 | "abac", 8 | "acl", 9 | "permission", 10 | "casbin-adapter", 11 | "database" 12 | ], 13 | "description": "Use Casbin in Yii2 PHP Framework, Casbin is a powerful and efficient open-source access control library.", 14 | "authors": [ 15 | { 16 | "name": "TechLee", 17 | "email": "techlee@qq.com" 18 | } 19 | ], 20 | "license": "Apache-2.0", 21 | "require": { 22 | "php": ">=8.0", 23 | "yiisoft/yii2": "~2.0.49", 24 | "casbin/casbin": "~4.0" 25 | }, 26 | "require-dev": { 27 | "phpunit/phpunit": "~9.0", 28 | "php-coveralls/php-coveralls": "^2.1", 29 | "yiisoft/yii2-app-basic": "~2.0.49" 30 | }, 31 | "autoload": { 32 | "psr-4": { 33 | "yii\\permission\\": "src/" 34 | } 35 | }, 36 | "autoload-dev": { 37 | "psr-4": { 38 | "yii\\permission\\tests\\": "tests/" 39 | } 40 | }, 41 | "repositories": [ 42 | { 43 | "type": "composer", 44 | "url": "https://asset-packagist.org" 45 | } 46 | ], 47 | "config": { 48 | "allow-plugins": { 49 | "yiisoft/yii2-composer": true 50 | } 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /config/casbin-basic-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 -------------------------------------------------------------------------------- /config/permission.php: -------------------------------------------------------------------------------- 1 | \yii\permission\Permission::class, 5 | /* 6 | * Yii-casbin model setting. 7 | */ 8 | 'model' => [ 9 | // Available Settings: "file", "text" 10 | 'config_type' => 'file', 11 | 12 | 'config_file_path' => __DIR__ . '/casbin-basic-model.conf', 13 | 14 | 'config_text' => '', 15 | ], 16 | 17 | // Yii-casbin logger. 18 | 'log' => [ 19 | // changes whether YiiPermission will log messages to the Logger. 20 | 'enabled' => false, 21 | // Casbin Logger, Supported: \Psr\Log\LoggerInterface|string 22 | 'logger' => 'log', 23 | ], 24 | 25 | // Yii-casbin adapter . 26 | 'adapter' => \yii\permission\Adapter::class, 27 | 28 | /* 29 | * Yii-casbin database setting. 30 | */ 31 | 'database' => [ 32 | // Database connection for following tables. 33 | 'connection' => '', 34 | 35 | // CasbinRule tables and model. 36 | 'casbin_rules_table' => '{{%casbin_rule}}', 37 | ], 38 | ]; 39 | -------------------------------------------------------------------------------- /phpunit.xml: -------------------------------------------------------------------------------- 1 | 2 | 11 | 12 | 13 | ./tests/ 14 | 15 | 16 | 17 | 18 | ./src 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | -------------------------------------------------------------------------------- /src/Adapter.php: -------------------------------------------------------------------------------- 1 | casbinRule = $casbinRule; 34 | } 35 | 36 | public function savePolicyLine($ptype, array $rule) 37 | { 38 | $col['ptype'] = $ptype; 39 | foreach ($rule as $key => $value) { 40 | $col['v' . strval($key) . ''] = $value; 41 | } 42 | $ar = clone $this->casbinRule; 43 | $ar->setAttributes($col); 44 | $ar->save(); 45 | } 46 | 47 | /** 48 | * loads all policy rules from the storage. 49 | * 50 | * @param Model $model 51 | */ 52 | public function loadPolicy(Model $model): void 53 | { 54 | $ar = clone $this->casbinRule; 55 | $rows = $ar->find()->all(); 56 | 57 | foreach ($rows as $row) { 58 | $line = implode(', ', array_filter(array_slice($row->toArray(), 1), function ($val) { 59 | return '' != $val && !is_null($val); 60 | })); 61 | $this->loadPolicyLine(trim($line), $model); 62 | } 63 | } 64 | 65 | /** 66 | * saves all policy rules to the storage. 67 | * 68 | * @param Model $model 69 | */ 70 | public function savePolicy(Model $model): void 71 | { 72 | foreach ($model['p'] as $ptype => $ast) { 73 | foreach ($ast->policy as $rule) { 74 | $this->savePolicyLine($ptype, $rule); 75 | } 76 | } 77 | 78 | foreach ($model['g'] as $ptype => $ast) { 79 | foreach ($ast->policy as $rule) { 80 | $this->savePolicyLine($ptype, $rule); 81 | } 82 | } 83 | } 84 | 85 | /** 86 | * adds a policy rule to the storage. 87 | * This is part of the Auto-Save feature. 88 | * 89 | * @param string $sec 90 | * @param string $ptype 91 | * @param array $rule 92 | */ 93 | public function addPolicy(string $sec, string $ptype, array $rule): void 94 | { 95 | $this->savePolicyLine($ptype, $rule); 96 | } 97 | 98 | /** 99 | * Adds a policy rules to the storage. 100 | * This is part of the Auto-Save feature. 101 | * 102 | * @param string $sec 103 | * @param string $ptype 104 | * @param string[][] $rules 105 | */ 106 | public function addPolicies(string $sec, string $ptype, array $rules): void 107 | { 108 | $rows = []; 109 | $columns = array_keys($rules[0]); 110 | array_walk($columns, function (&$item) { 111 | $item = 'v' . strval($item); 112 | }); 113 | array_unshift($columns, 'ptype'); 114 | 115 | foreach ($rules as $rule) { 116 | $temp['`ptype`'] = $ptype; 117 | foreach ($rule as $key => $value) { 118 | $temp['`v'. strval($key) . '`'] = $value; 119 | } 120 | $rows[] = $temp; 121 | $temp = []; 122 | } 123 | 124 | $command = $this->casbinRule->getDb()->createCommand(); 125 | $tableName = $this->casbinRule->tableName(); 126 | $command->batchInsert($tableName, $columns, $rows)->execute(); 127 | } 128 | 129 | /** 130 | * This is part of the Auto-Save feature. 131 | * 132 | * @param string $sec 133 | * @param string $ptype 134 | * @param array $rule 135 | */ 136 | public function removePolicy(string $sec, string $ptype, array $rule): void 137 | { 138 | $where = []; 139 | $where['ptype'] = $ptype; 140 | 141 | foreach ($rule as $key => $value) { 142 | $where['v' . strval($key)] = $value; 143 | } 144 | 145 | $this->casbinRule->deleteAll($where); 146 | } 147 | 148 | /** 149 | * Removes policy rules from the storage. 150 | * This is part of the Auto-Save feature. 151 | * 152 | * @param string $sec 153 | * @param string $ptype 154 | * @param string[][] $rules 155 | */ 156 | public function removePolicies(string $sec, string $ptype, array $rules): void 157 | { 158 | $transaction = $this->casbinRule->getDb()->beginTransaction(); 159 | try { 160 | foreach ($rules as $rule) { 161 | $this->removePolicy($sec, $ptype, $rule); 162 | } 163 | $transaction->commit(); 164 | } catch (\Exception $e) { 165 | $transaction->rollBack(); 166 | throw $e; 167 | } 168 | } 169 | 170 | /** 171 | * @param string $sec 172 | * @param string $ptype 173 | * @param int $fieldIndex 174 | * @param string|null ...$fieldValues 175 | * @return array 176 | * @throws Throwable 177 | */ 178 | public function _removeFilteredPolicy(string $sec, string $ptype, int $fieldIndex, ?string ...$fieldValues): array 179 | { 180 | $where = []; 181 | $where['ptype'] = $ptype; 182 | 183 | foreach (range(0, 5) as $value) { 184 | if ($fieldIndex <= $value && $value < $fieldIndex + count($fieldValues)) { 185 | if ('' != $fieldValues[$value - $fieldIndex]) { 186 | $where['v' . strval($value)] = $fieldValues[$value - $fieldIndex]; 187 | } 188 | } 189 | } 190 | 191 | $removedRules = $this->casbinRule->find()->where($where)->all(); 192 | $this->casbinRule->deleteAll($where); 193 | 194 | array_walk($removedRules, function (&$removedRule) { 195 | unset($removedRule->id); 196 | unset($removedRule->ptype); 197 | $removedRule = $removedRule->toArray(); 198 | $removedRule = $this->filterRule($removedRule); 199 | }); 200 | 201 | return $removedRules; 202 | } 203 | 204 | /** 205 | * RemoveFilteredPolicy removes policy rules that match the filter from the storage. 206 | * This is part of the Auto-Save feature. 207 | * 208 | * @param string $sec 209 | * @param string $ptype 210 | * @param int $fieldIndex 211 | * @param string ...$fieldValues 212 | */ 213 | public function removeFilteredPolicy(string $sec, string $ptype, int $fieldIndex, string ...$fieldValues): void 214 | { 215 | $this->_removeFilteredPolicy($sec, $ptype, $fieldIndex, ...$fieldValues); 216 | } 217 | 218 | /** 219 | * Loads only policy rules that match the filter. 220 | * 221 | * @param Model $model 222 | * @param mixed $filter 223 | */ 224 | public function loadFilteredPolicy(Model $model, $filter): void 225 | { 226 | $entity = clone $this->casbinRule; 227 | $entity = $entity->find(); 228 | 229 | if (is_string($filter)) { 230 | $entity->where($filter); 231 | } elseif ($filter instanceof Filter) { 232 | foreach ($filter->p as $k => $v) { 233 | $where[$v] = $filter->g[$k]; 234 | $entity->where([$v => $filter->g[$k]]); 235 | } 236 | } elseif ($filter instanceof \Closure) { 237 | $filter($entity); 238 | } else { 239 | throw new InvalidFilterTypeException('invalid filter type'); 240 | } 241 | 242 | $rows = $entity->all(); 243 | foreach ($rows as $row) { 244 | unset($row->id); 245 | $row = $row->toArray(); 246 | $line = implode(', ', array_filter($row, function ($val) { 247 | return '' != $val && !is_null($val); 248 | })); 249 | $this->loadPolicyLine(trim($line), $model); 250 | } 251 | $this->setFiltered(true); 252 | } 253 | 254 | /** 255 | * Updates a policy rule from storage. 256 | * This is part of the Auto-Save feature. 257 | * 258 | * @param string $sec 259 | * @param string $ptype 260 | * @param string[] $oldRule 261 | * @param string[] $newPolicy 262 | */ 263 | public function updatePolicy(string $sec, string $ptype, array $oldRule, array $newPolicy): void 264 | { 265 | $entity = clone $this->casbinRule; 266 | 267 | $condition['ptype'] = $ptype; 268 | foreach ($oldRule as $k => $v) { 269 | $condition['v' . $k] = $v; 270 | } 271 | $item = $entity->findOne($condition); 272 | foreach ($newPolicy as $k => $v) { 273 | $key = 'v' . $k; 274 | $item->$key = $v; 275 | } 276 | $item->update(); 277 | } 278 | 279 | /** 280 | * UpdatePolicies updates some policy rules to storage, like db, redis. 281 | * 282 | * @param string $sec 283 | * @param string $ptype 284 | * @param string[][] $oldRules 285 | * @param string[][] $newRules 286 | * @return void 287 | */ 288 | public function updatePolicies(string $sec, string $ptype, array $oldRules, array $newRules): void 289 | { 290 | $transaction = $this->casbinRule->getDb()->beginTransaction(); 291 | try { 292 | foreach ($oldRules as $i => $oldRule) { 293 | $this->updatePolicy($sec, $ptype, $oldRule, $newRules[$i]); 294 | } 295 | $transaction->commit(); 296 | } catch (\Exception $e) { 297 | $transaction->rollBack(); 298 | throw $e; 299 | } 300 | } 301 | 302 | /** 303 | * UpdateFilteredPolicies deletes old rules and adds new rules. 304 | * 305 | * @param string $sec 306 | * @param string $ptype 307 | * @param array $newPolicies 308 | * @param integer $fieldIndex 309 | * @param string ...$fieldValues 310 | * @return array 311 | */ 312 | public function updateFilteredPolicies(string $sec, string $ptype, array $newRules, int $fieldIndex, ?string ...$fieldValues): array 313 | { 314 | $oldRules = []; 315 | $transaction = $this->casbinRule->getDb()->beginTransaction(); 316 | try { 317 | $oldRules = $this->_removeFilteredPolicy($sec, $ptype, $fieldIndex, ...$fieldValues); 318 | $this->addPolicies($sec, $ptype, $newRules); 319 | $transaction->commit(); 320 | } catch (\Exception $e) { 321 | $transaction->rollBack(); 322 | throw $e; 323 | } 324 | 325 | return $oldRules; 326 | } 327 | 328 | /** 329 | * Filter the rule. 330 | * 331 | * @param array $rule 332 | * @return array 333 | */ 334 | public function filterRule(array $rule): array 335 | { 336 | $rule = array_values($rule); 337 | 338 | $i = count($rule) - 1; 339 | for (; $i >= 0; $i--) { 340 | if ($rule[$i] != "" && !is_null($rule[$i])) { 341 | break; 342 | } 343 | } 344 | 345 | return array_slice($rule, 0, $i + 1); 346 | } 347 | 348 | /** 349 | * Returns true if the loaded policy has been filtered. 350 | * 351 | * @return bool 352 | */ 353 | public function isFiltered(): bool 354 | { 355 | return $this->filtered; 356 | } 357 | 358 | /** 359 | * Sets filtered parameter. 360 | * 361 | * @param bool $filtered 362 | */ 363 | public function setFiltered(bool $filtered): void 364 | { 365 | $this->filtered = $filtered; 366 | } 367 | } 368 | -------------------------------------------------------------------------------- /src/Permission.php: -------------------------------------------------------------------------------- 1 | config = $this->mergeConfig( 33 | require dirname(__DIR__) . '/config/permission.php', 34 | $config 35 | ); 36 | 37 | $this->adapter = Yii::$container->get($this->config['adapter']); 38 | 39 | $this->model = new Model(); 40 | if ('file' == $this->config['model']['config_type']) { 41 | $this->model->loadModel($this->config['model']['config_file_path']); 42 | } elseif ('text' == $this->config['model']['config_type']) { 43 | $this->model->loadModelFromText($this->config['model']['config_text']); 44 | } 45 | 46 | if ($logger = $this->config['log']['logger']) { 47 | if ($logger === 'log') { 48 | $this->logger = new DefaultLogger(); 49 | } else { 50 | $this->logger = new DefaultLogger(Yii::$container->get($logger)); 51 | } 52 | 53 | Log::setLogger($this->logger); 54 | } 55 | } 56 | 57 | /** 58 | * Initializes the object. 59 | * This method is invoked at the end of the constructor after the object is initialized with the 60 | * given configuration. 61 | */ 62 | public function init() 63 | { 64 | $db = CasbinRule::getDb(); 65 | $tableName = CasbinRule::tableName(); 66 | $table = $db->getTableSchema($tableName); 67 | if (!$table) { 68 | $res = $db->createCommand()->createTable($tableName, [ 69 | 'id' => 'pk', 70 | 'ptype' => 'string', 71 | 'v0' => 'string', 72 | 'v1' => 'string', 73 | 'v2' => 'string', 74 | 'v3' => 'string', 75 | 'v4' => 'string', 76 | 'v5' => 'string', 77 | ])->execute(); 78 | } 79 | } 80 | 81 | public function enforcer($newInstance = false) 82 | { 83 | if ($newInstance || is_null($this->enforcer)) { 84 | $this->init(); 85 | $this->enforcer = new Enforcer($this->model, $this->adapter, $this->logger, !is_null($this->logger)); 86 | } 87 | 88 | return $this->enforcer; 89 | } 90 | 91 | private function mergeConfig(array $a, array $b) 92 | { 93 | foreach ($a as $key => $val) { 94 | if (isset($b[$key])) { 95 | if (gettype($a[$key]) != gettype($b[$key])) { 96 | continue; 97 | } 98 | if (is_array($a[$key])) { 99 | $a[$key] = $this->mergeConfig($a[$key], $b[$key]); 100 | } else { 101 | $a[$key] = $b[$key]; 102 | } 103 | } 104 | } 105 | 106 | return $a; 107 | } 108 | 109 | /** 110 | * Calls the named method which is not a class method. 111 | * 112 | * This method will check if any attached behavior has 113 | * the named method and will execute it if available. 114 | * 115 | * Do not call this method directly as it is a PHP magic method that 116 | * will be implicitly called when an unknown method is being invoked. 117 | * 118 | * @param string $name the method name 119 | * @param array $params method parameters 120 | * 121 | * @return mixed the method return value 122 | * 123 | * @throws UnknownMethodException when calling unknown method 124 | */ 125 | public function __call($name, $params) 126 | { 127 | foreach ($this->getBehaviors() as $object) { 128 | if ($object->hasMethod($name)) { 129 | return call_user_func_array([$object, $name], $params); 130 | } 131 | } 132 | 133 | return call_user_func_array([$this->enforcer(), $name], $params); 134 | } 135 | } 136 | -------------------------------------------------------------------------------- /src/components/PermissionChecker.php: -------------------------------------------------------------------------------- 1 | permission->enforce($userId, ...$params); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/components/PermissionControl.php: -------------------------------------------------------------------------------- 1 | 'yii\permission\components\PermissionPolicy']; 27 | 28 | /** 29 | * @var array the policies. 30 | */ 31 | public $policy = []; 32 | 33 | /** 34 | * Initializes the PermissionControl component. 35 | * 36 | * @return void 37 | */ 38 | public function init() 39 | { 40 | parent::init(); 41 | if ($this->user !== false) { 42 | $this->user = Instance::ensure($this->user, User::class); 43 | } 44 | foreach ($this->policy as $i => $policy) { 45 | if (is_array($policy)) { 46 | $this->policy[$i] = Yii::createObject(array_merge($this->policyConfig, $policy)); 47 | } 48 | } 49 | } 50 | 51 | /** 52 | * Checks if the current user has permission to perform the given action. 53 | * 54 | * @param Action $action the action to be performed 55 | * @throws ForbiddenHttpException if the user does not have permission 56 | * @return bool true if the user has permission, false otherwise 57 | */ 58 | public function beforeAction($action) 59 | { 60 | $user = $this->user; 61 | foreach ($this->policy as $policy) { 62 | if ($allow = $policy->allows($action, $user)) { 63 | return true; 64 | } elseif ($allow === false) { 65 | if (isset($policy->denyCallback)) { 66 | call_user_func($policy->denyCallback, $policy, $action); 67 | } elseif ($this->denyCallback !== null) { 68 | call_user_func($this->denyCallback, $policy, $action); 69 | } else { 70 | $this->denyAccess($user); 71 | } 72 | 73 | return false; 74 | } 75 | } 76 | 77 | if ($this->denyCallback !== null) { 78 | call_user_func($this->denyCallback, null, $action); 79 | } else { 80 | $this->denyAccess($user); 81 | } 82 | return false; 83 | } 84 | /** 85 | * Denies the access of the user. 86 | * The default implementation will redirect the user to the login page if he is a guest; 87 | * if the user is already logged, a 403 HTTP exception will be thrown. 88 | * 89 | * @param User|false $user the current user or boolean `false` in case of detached User component 90 | * @throws ForbiddenHttpException if the user is already logged in or in case of detached User component. 91 | */ 92 | protected function denyAccess($user) 93 | { 94 | if ($user !== false && $user->getIsGuest()) { 95 | $user->loginRequired(); 96 | } else { 97 | throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.')); 98 | } 99 | } 100 | } 101 | -------------------------------------------------------------------------------- /src/components/PermissionPolicy.php: -------------------------------------------------------------------------------- 1 | matchAction($action) 43 | && $this->matchEnforce($user, $this->enforce) 44 | ) { 45 | return $this->allow ? true : false; 46 | } 47 | 48 | return null; 49 | } 50 | 51 | /** 52 | * Checks if the rule applies to the specified action. 53 | * 54 | * @param Action $action the action 55 | * @return bool whether the rule applies to the action 56 | */ 57 | protected function matchAction($action) 58 | { 59 | return empty($this->actions) || in_array($action->id, $this->actions, true); 60 | } 61 | 62 | /** 63 | * Checks if the rule applies to the specified user. 64 | * 65 | * @param User $user 66 | * @param array $params 67 | * 68 | * @return bool 69 | */ 70 | protected function matchEnforce($user, $params) 71 | { 72 | return Yii::$app->permission->enforce($user->getId(), ...$params); 73 | } 74 | } 75 | -------------------------------------------------------------------------------- /src/models/CasbinRule.php: -------------------------------------------------------------------------------- 1 | permission->config['database']['casbin_rules_table']; 15 | } 16 | 17 | /** 18 | * getDb. 19 | * 20 | * @return yii\db\Connection 21 | */ 22 | public static function getDb() 23 | { 24 | $db = \Yii::$app->permission->config['database']['connection'] ?: 'db'; 25 | 26 | return \Yii::$app->{$db}; 27 | } 28 | 29 | public function rules() 30 | { 31 | return [ 32 | [['ptype', 'v0'], 'required'], 33 | [['ptype', 'v0', 'v1', 'v2', 'v3', 'v4', 'v5'], 'safe'], 34 | ]; 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /tests/AdapterTest.php: -------------------------------------------------------------------------------- 1 | assertTrue(Yii::$app->permission->enforce('alice', 'data1', 'read')); 15 | 16 | $this->assertFalse(Yii::$app->permission->enforce('bob', 'data1', 'read')); 17 | $this->assertTrue(Yii::$app->permission->enforce('bob', 'data2', 'write')); 18 | 19 | $this->assertTrue(Yii::$app->permission->enforce('alice', 'data2', 'read')); 20 | $this->assertTrue(Yii::$app->permission->enforce('alice', 'data2', 'write')); 21 | } 22 | 23 | public function testAddPolicy() 24 | { 25 | $this->assertFalse(Yii::$app->permission->enforce('eve', 'data3', 'read')); 26 | Yii::$app->permission->addPermissionForUser('eve', 'data3', 'read'); 27 | $this->assertTrue(Yii::$app->permission->enforce('eve', 'data3', 'read')); 28 | } 29 | 30 | public function testAddPolicies() 31 | { 32 | $policies = [ 33 | ['u1', 'd1', 'read'], 34 | ['u2', 'd2', 'read'], 35 | ['u3', 'd3', 'read'], 36 | ]; 37 | Yii::$app->permission->clearPolicy(); 38 | $this->assertEquals([], Yii::$app->permission->getPolicy()); 39 | Yii::$app->permission->addPolicies($policies); 40 | $this->assertEquals($policies, Yii::$app->permission->getPolicy()); 41 | } 42 | 43 | public function testSavePolicy() 44 | { 45 | $this->assertFalse(Yii::$app->permission->enforce('alice', 'data4', 'read')); 46 | 47 | $model = Yii::$app->permission->getModel(); 48 | $model->clearPolicy(); 49 | $model->addPolicy('p', 'p', ['alice', 'data4', 'read']); 50 | 51 | $adapter = Yii::$app->permission->getAdapter(); 52 | $adapter->savePolicy($model); 53 | $this->assertTrue(Yii::$app->permission->enforce('alice', 'data4', 'read')); 54 | } 55 | 56 | public function testRemovePolicy() 57 | { 58 | $this->assertFalse(Yii::$app->permission->enforce('alice', 'data5', 'read')); 59 | 60 | Yii::$app->permission->addPermissionForUser('alice', 'data5', 'read'); 61 | $this->assertTrue(Yii::$app->permission->enforce('alice', 'data5', 'read')); 62 | 63 | Yii::$app->permission->deletePermissionForUser('alice', 'data5', 'read'); 64 | $this->assertFalse(Yii::$app->permission->enforce('alice', 'data5', 'read')); 65 | } 66 | 67 | public function testRemovePolicies() 68 | { 69 | $this->assertEquals([ 70 | ['alice', 'data1', 'read'], 71 | ['bob', 'data2', 'write'], 72 | ['data2_admin', 'data2', 'read'], 73 | ['data2_admin', 'data2', 'write'], 74 | ], Yii::$app->permission->getPolicy()); 75 | 76 | Yii::$app->permission->removePolicies([ 77 | ['data2_admin', 'data2', 'read'], 78 | ['data2_admin', 'data2', 'write'], 79 | ]); 80 | 81 | $this->assertEquals([ 82 | ['alice', 'data1', 'read'], 83 | ['bob', 'data2', 'write'] 84 | ], Yii::$app->permission->getPolicy()); 85 | } 86 | 87 | public function testRemoveFilteredPolicy() 88 | { 89 | $this->assertTrue(Yii::$app->permission->enforce('alice', 'data1', 'read')); 90 | Yii::$app->permission->removeFilteredPolicy(1, 'data1'); 91 | $this->assertFalse(Yii::$app->permission->enforce('alice', 'data1', 'read')); 92 | $this->assertTrue(Yii::$app->permission->enforce('bob', 'data2', 'write')); 93 | $this->assertTrue(Yii::$app->permission->enforce('alice', 'data2', 'read')); 94 | $this->assertTrue(Yii::$app->permission->enforce('alice', 'data2', 'write')); 95 | Yii::$app->permission->removeFilteredPolicy(1, 'data2', 'read'); 96 | $this->assertTrue(Yii::$app->permission->enforce('bob', 'data2', 'write')); 97 | $this->assertFalse(Yii::$app->permission->enforce('alice', 'data2', 'read')); 98 | $this->assertTrue(Yii::$app->permission->enforce('alice', 'data2', 'write')); 99 | Yii::$app->permission->removeFilteredPolicy(2, 'write'); 100 | $this->assertFalse(Yii::$app->permission->enforce('bob', 'data2', 'write')); 101 | $this->assertFalse(Yii::$app->permission->enforce('alice', 'data2', 'write')); 102 | } 103 | 104 | public function testUpdatePolicy() 105 | { 106 | $this->assertEquals([ 107 | ['alice', 'data1', 'read'], 108 | ['bob', 'data2', 'write'], 109 | ['data2_admin', 'data2', 'read'], 110 | ['data2_admin', 'data2', 'write'], 111 | ], Yii::$app->permission->getPolicy()); 112 | 113 | Yii::$app->permission->updatePolicy( 114 | ['alice', 'data1', 'read'], 115 | ['alice', 'data1', 'write'] 116 | ); 117 | 118 | Yii::$app->permission->updatePolicy( 119 | ['bob', 'data2', 'write'], 120 | ['bob', 'data2', 'read'] 121 | ); 122 | 123 | $this->assertEquals([ 124 | ['alice', 'data1', 'write'], 125 | ['bob', 'data2', 'read'], 126 | ['data2_admin', 'data2', 'read'], 127 | ['data2_admin', 'data2', 'write'], 128 | ], Yii::$app->permission->getPolicy()); 129 | } 130 | 131 | public function testUpdatePolicies() 132 | { 133 | $this->assertEquals([ 134 | ['alice', 'data1', 'read'], 135 | ['bob', 'data2', 'write'], 136 | ['data2_admin', 'data2', 'read'], 137 | ['data2_admin', 'data2', 'write'], 138 | ], Yii::$app->permission->getPolicy()); 139 | 140 | $oldPolicies = [ 141 | ['alice', 'data1', 'read'], 142 | ['bob', 'data2', 'write'] 143 | ]; 144 | $newPolicies = [ 145 | ['alice', 'data1', 'write'], 146 | ['bob', 'data2', 'read'] 147 | ]; 148 | 149 | Yii::$app->permission->updatePolicies($oldPolicies, $newPolicies); 150 | 151 | $this->assertEquals([ 152 | ['alice', 'data1', 'write'], 153 | ['bob', 'data2', 'read'], 154 | ['data2_admin', 'data2', 'read'], 155 | ['data2_admin', 'data2', 'write'], 156 | ], Yii::$app->permission->getPolicy()); 157 | } 158 | 159 | public function arrayEqualsWithoutOrder(array $expected, array $actual) 160 | { 161 | if (method_exists($this, 'assertEqualsCanonicalizing')) { 162 | $this->assertEqualsCanonicalizing($expected, $actual); 163 | } else { 164 | array_multisort($expected); 165 | array_multisort($actual); 166 | $this->assertEquals($expected, $actual); 167 | } 168 | } 169 | 170 | public function testUpdateFilteredPolicies() 171 | { 172 | $this->assertEquals([ 173 | ['alice', 'data1', 'read'], 174 | ['bob', 'data2', 'write'], 175 | ['data2_admin', 'data2', 'read'], 176 | ['data2_admin', 'data2', 'write'], 177 | ], Yii::$app->permission->getPolicy()); 178 | 179 | Yii::$app->permission->updateFilteredPolicies([["alice", "data1", "write"]], 0, "alice", "data1", "read"); 180 | Yii::$app->permission->updateFilteredPolicies([["bob", "data2", "read"]], 0, "bob", "data2", "write"); 181 | 182 | $policies = [ 183 | ['data2_admin', 'data2', 'read'], 184 | ['data2_admin', 'data2', 'write'], 185 | ['alice', 'data1', 'write'], 186 | ['bob', 'data2', 'read'], 187 | ]; 188 | $this->arrayEqualsWithoutOrder($policies, Yii::$app->permission->getPolicy()); 189 | 190 | // test use updateFilteredPolicies to update all policies of a user 191 | $this->initTable(); 192 | $this->refreshApplication(); 193 | 194 | $policies = [ 195 | ['alice', 'data2', 'write'], 196 | ['bob', 'data1', 'read'] 197 | ]; 198 | 199 | Yii::$app->permission->addPolicies($policies); 200 | $this->arrayEqualsWithoutOrder([ 201 | ['alice', 'data1', 'read'], 202 | ['bob', 'data2', 'write'], 203 | ['data2_admin', 'data2', 'read'], 204 | ['data2_admin', 'data2', 'write'], 205 | ['alice', 'data2', 'write'], 206 | ['bob', 'data1', 'read'] 207 | ], Yii::$app->permission->getPolicy()); 208 | 209 | Yii::$app->permission->updateFilteredPolicies([['alice', 'data1', 'write'], ['alice', 'data2', 'read']], 0, 'alice'); 210 | Yii::$app->permission->updateFilteredPolicies([['bob', 'data1', 'write'], ["bob", "data2", "read"]], 0, 'bob'); 211 | 212 | $policies = [ 213 | ['alice', 'data1', 'write'], 214 | ['alice', 'data2', 'read'], 215 | ['bob', 'data1', 'write'], 216 | ['bob', 'data2', 'read'], 217 | ['data2_admin', 'data2', 'read'], 218 | ['data2_admin', 'data2', 'write'] 219 | ]; 220 | 221 | $this->arrayEqualsWithoutOrder($policies, Yii::$app->permission->getPolicy()); 222 | 223 | // test if $fieldValues contains empty string 224 | $this->initTable(); 225 | $this->refreshApplication(); 226 | 227 | $policies = [ 228 | ['alice', 'data2', 'write'], 229 | ['bob', 'data1', 'read'] 230 | ]; 231 | Yii::$app->permission->addPolicies($policies); 232 | 233 | $this->assertEquals([ 234 | ['alice', 'data1', 'read'], 235 | ['bob', 'data2', 'write'], 236 | ['data2_admin', 'data2', 'read'], 237 | ['data2_admin', 'data2', 'write'], 238 | ['alice', 'data2', 'write'], 239 | ['bob', 'data1', 'read'] 240 | ], Yii::$app->permission->getPolicy()); 241 | 242 | Yii::$app->permission->updateFilteredPolicies([['alice', 'data1', 'write'], ['alice', 'data2', 'read']], 0, 'alice', '', ''); 243 | Yii::$app->permission->updateFilteredPolicies([['bob', 'data1', 'write'], ["bob", "data2", "read"]], 0, 'bob', '', ''); 244 | 245 | $policies = [ 246 | ['alice', 'data1', 'write'], 247 | ['alice', 'data2', 'read'], 248 | ['bob', 'data1', 'write'], 249 | ['bob', 'data2', 'read'], 250 | ['data2_admin', 'data2', 'read'], 251 | ['data2_admin', 'data2', 'write'] 252 | ]; 253 | 254 | $this->arrayEqualsWithoutOrder($policies, Yii::$app->permission->getPolicy()); 255 | 256 | // test if $fieldIndex is not zero 257 | $this->initTable(); 258 | $this->refreshApplication(); 259 | 260 | $policies = [ 261 | ['alice', 'data2', 'write'], 262 | ['bob', 'data1', 'read'] 263 | ]; 264 | Yii::$app->permission->addPolicies($policies); 265 | 266 | $this->assertEquals([ 267 | ['alice', 'data1', 'read'], 268 | ['bob', 'data2', 'write'], 269 | ['data2_admin', 'data2', 'read'], 270 | ['data2_admin', 'data2', 'write'], 271 | ['alice', 'data2', 'write'], 272 | ['bob', 'data1', 'read'] 273 | ], Yii::$app->permission->getPolicy()); 274 | 275 | Yii::$app->permission->updateFilteredPolicies([['alice', 'data1', 'edit'], ['bob', 'data1', 'edit']], 2, 'read'); 276 | Yii::$app->permission->updateFilteredPolicies([['alice', 'data2', 'read'], ["bob", "data2", "read"]], 2, 'write'); 277 | 278 | $policies = [ 279 | ['alice', 'data1', 'edit'], 280 | ['alice', 'data2', 'read'], 281 | ['bob', 'data1', 'edit'], 282 | ['bob', 'data2', 'read'], 283 | ]; 284 | 285 | $this->arrayEqualsWithoutOrder($policies, Yii::$app->permission->getPolicy()); 286 | } 287 | 288 | public function testLoadFilteredPolicy() 289 | { 290 | Yii::$app->permission->clearPolicy(); 291 | $adapter = Yii::$app->permission->getAdapter(); 292 | $adapter->setFiltered(true); 293 | $this->assertEquals([], Yii::$app->permission->getPolicy()); 294 | 295 | // invalid filter type 296 | try { 297 | $filter = ['alice', 'data1', 'read']; 298 | Yii::$app->permission->loadFilteredPolicy($filter); 299 | $exception = InvalidFilterTypeException::class; 300 | $this->fail("Expected exception $exception not thrown"); 301 | } catch (InvalidFilterTypeException $exception) { 302 | $this->assertEquals("invalid filter type", $exception->getMessage()); 303 | } 304 | 305 | // string 306 | $filter = "v0 = 'bob'"; 307 | Yii::$app->permission->loadFilteredPolicy($filter); 308 | $this->assertEquals([ 309 | ['bob', 'data2', 'write'] 310 | ], Yii::$app->permission->getPolicy()); 311 | 312 | // Filter 313 | $filter = new Filter(['v2'], ['read']); 314 | Yii::$app->permission->loadFilteredPolicy($filter); 315 | $this->assertEquals([ 316 | ['alice', 'data1', 'read'], 317 | ['data2_admin', 'data2', 'read'], 318 | ], Yii::$app->permission->getPolicy()); 319 | 320 | // Closure 321 | Yii::$app->permission->loadFilteredPolicy(function (ActiveQueryInterface &$entity) { 322 | $entity->where(['v1' => 'data1']); 323 | }); 324 | 325 | $this->assertEquals([ 326 | ['alice', 'data1', 'read'], 327 | ], Yii::$app->permission->getPolicy()); 328 | } 329 | } 330 | -------------------------------------------------------------------------------- /tests/LocalizationTest.php: -------------------------------------------------------------------------------- 1 | initBaseBehaviors(); 21 | } 22 | 23 | public static function permissionCheckerProvider() 24 | { 25 | return [ 26 | ['alice', 'data1,read', true], 27 | ['bob', 'data1,read', false], 28 | ['bob', 'data2,write', true], 29 | ['alice', 'data2,read', true], 30 | ['alice', 'data2,write', true] 31 | ]; 32 | } 33 | 34 | /** 35 | * @dataProvider permissionCheckerProvider 36 | */ 37 | public function testPermissionChecker($sub, $params, $expected) 38 | { 39 | $user = $this->mockUser($sub); 40 | $auth = $this->mockAuthManager(); 41 | 42 | $user->accessChecker = $auth; 43 | $this->assertEquals($expected, $user->can($params)); 44 | } 45 | 46 | public function testPermissionControlBasic() 47 | { 48 | $controller = new TestController('test', $this->app, [ 49 | 'behaviors' => [ 50 | 'permission' => $this->baseBehaviors 51 | ], 52 | ]); 53 | $this->assertEquals('create success', $controller->runAction('create-post')); 54 | $this->assertEquals('update success', $controller->runAction('update-post')); 55 | 56 | // try contained actions 57 | try { 58 | $controller->runAction('delete-post'); 59 | $this->fail('Expected exception not thrown'); 60 | } catch (ForbiddenHttpException $e) { 61 | $this->assertInstanceOf(ForbiddenHttpException::class, $e); 62 | } 63 | 64 | // try not contained actions 65 | try { 66 | $controller->runAction('comment'); 67 | $this->fail('Expected exception not thrown'); 68 | } catch (ForbiddenHttpException $e) { 69 | $this->assertInstanceOf(ForbiddenHttpException::class, $e); 70 | } 71 | 72 | // try 73 | } 74 | 75 | public function testPermissionControlWithGlobalDenyCallback() 76 | { 77 | $this->baseBehaviors['denyCallback'] = function ($rule, $action) { 78 | throw new ForbiddenHttpException('forbidden by global'); 79 | }; 80 | $controller = new TestController('test', $this->app, [ 81 | 'behaviors' => [ 82 | 'permission' => $this->baseBehaviors 83 | ] 84 | ]); 85 | 86 | // try contained actions 87 | try { 88 | $controller->runAction('delete-post'); 89 | $this->fail('Expected exception not thrown'); 90 | } catch (ForbiddenHttpException $e) { 91 | $this->assertEquals('forbidden by global', $e->getMessage()); 92 | } 93 | } 94 | 95 | public function testPermissionControlWithDenyCallback() 96 | { 97 | // try local denyCallback when `allow` is false 98 | $this->baseBehaviors['policy'][0]['allow'] = false; 99 | $this->baseBehaviors['policy'][0]['denyCallback'] = function ($rule, $action) { 100 | throw new ForbiddenHttpException('forbidden by local'); 101 | }; 102 | $controller = new TestController('test', $this->app, [ 103 | 'behaviors' => [ 104 | 'permission' => $this->baseBehaviors 105 | ] 106 | ]); 107 | 108 | try { 109 | $controller->runAction('create-post'); 110 | $this->fail('Expected exception not thrown'); 111 | } catch (ForbiddenHttpException $e) { 112 | $this->assertEquals('forbidden by local', $e->getMessage()); 113 | } 114 | 115 | // try global denyCallback when `allow` is false 116 | $this->baseBehaviors['policy'][0]['denyCallback'] = null; 117 | $controller = new TestController('test', $this->app, [ 118 | 'behaviors' => [ 119 | 'permission' => $this->baseBehaviors 120 | ] 121 | ]); 122 | 123 | try { 124 | $controller->runAction('create-post'); 125 | $this->fail('Expected exception not thrown'); 126 | } catch (ForbiddenHttpException $e) { 127 | $this->assertEquals(Yii::t('yii', 'You are not allowed to perform this action.'), $e->getMessage()); 128 | } 129 | 130 | // try custom global denyCallback when `allow` is false 131 | $this->baseBehaviors['denyCallback'] = function ($rule, $action) { 132 | throw new ForbiddenHttpException('forbidden by global'); 133 | }; 134 | $controller = new TestController('test', $this->app, [ 135 | 'behaviors' => [ 136 | 'permission' => $this->baseBehaviors 137 | ] 138 | ]); 139 | 140 | try { 141 | $controller->runAction('create-post'); 142 | $this->fail('Expected exception not thrown'); 143 | } catch (ForbiddenHttpException $e) { 144 | $this->assertEquals('forbidden by global', $e->getMessage()); 145 | } 146 | 147 | // try denyCallback with not thrown exception when `allow` is false 148 | $this->baseBehaviors['denyCallback'] = function ($rule, $action) {}; 149 | $controller = new TestController('test', $this->app, [ 150 | 'behaviors' => [ 151 | 'permission' => $this->baseBehaviors 152 | ] 153 | ]); 154 | $this->assertNull($controller->runAction('delete-post')); 155 | 156 | // try denyCallback with not thrown exception when `allow` is true 157 | $this->baseBehaviors['policy'][0]['allow'] = true; 158 | $controller = new TestController('test', $this->app, [ 159 | 'behaviors' => [ 160 | 'permission' => $this->baseBehaviors 161 | ] 162 | ]); 163 | $this->assertNull($controller->runAction('delete-post')); 164 | } 165 | 166 | protected function initBaseBehaviors() 167 | { 168 | $this->baseBehaviors = [ 169 | 'class' => PermissionControl::class, 170 | 'user' => $this->mockUser('alice'), 171 | 'only' => ['create-post', 'update-post', 'delete-post', 'comment'], 172 | 'policy' => [ 173 | [ 174 | 'allow' => true, 175 | 'actions' => ['create-post', 'update-post'], 176 | 'enforce' => ['data1', 'read'] 177 | ], 178 | [ 179 | 'allow' => true, 180 | 'actions' => ['delete-post'], 181 | 'enforce' => ['data1', 'write'] 182 | ] 183 | ] 184 | ]; 185 | } 186 | 187 | protected function mockUser($userId) 188 | { 189 | $user = new User([ 190 | 'identityClass' => UserIdentity::class, 191 | 'enableAutoLogin' => false, 192 | ]); 193 | $user->setIdentity(UserIdentity::findIdentity($userId)); 194 | return $user; 195 | } 196 | 197 | protected function mockAuthManager() 198 | { 199 | $auth = new PermissionChecker(); 200 | return $auth; 201 | } 202 | } 203 | -------------------------------------------------------------------------------- /tests/TestCase.php: -------------------------------------------------------------------------------- 1 | env('DB_HOST', '127.0.0.1') . ';port=' . $this->env('DB_PORT', '3306') . ';dbname=' . $this->env('DB_DATABASE', 'casbin'); 20 | $config['components']['db']['username'] = $this->env('DB_USERNAME', 'root'); 21 | $config['components']['db']['password'] = $this->env('DB_PASSWORD', ''); 22 | 23 | return new Application($config); 24 | } 25 | 26 | /** 27 | * init table. 28 | */ 29 | protected function initTable() 30 | { 31 | $db = CasbinRule::getDb(); 32 | $tableName = CasbinRule::tableName(); 33 | $table = $db->getTableSchema($tableName); 34 | if ($table) { 35 | $db->createCommand()->dropTable($tableName)->execute(); 36 | } 37 | 38 | Yii::$app->permission->init(); 39 | 40 | Yii::$app->db->createCommand()->batchInsert( 41 | $tableName, 42 | ['ptype', 'v0', 'v1', 'v2'], 43 | [ 44 | ['p', 'alice', 'data1', 'read'], 45 | ['p', 'bob', 'data2', 'write'], 46 | ['p', 'data2_admin', 'data2', 'read'], 47 | ['p', 'data2_admin', 'data2', 'write'], 48 | ['g', 'alice', 'data2_admin', null], 49 | ] 50 | )->execute(); 51 | } 52 | 53 | /** 54 | * Refresh the application instance. 55 | */ 56 | protected function refreshApplication() 57 | { 58 | $this->app = $this->createApplication(); 59 | } 60 | 61 | /** 62 | * This method is called before each test. 63 | */ 64 | protected function setUp(): void/* The :void return type declaration that should be here would cause a BC issue */ 65 | { 66 | if (!$this->app) { 67 | $this->refreshApplication(); 68 | } 69 | 70 | $this->initTable(); 71 | } 72 | 73 | /** 74 | * This method is called after each test. 75 | */ 76 | protected function tearDown(): void/* The :void return type declaration that should be here would cause a BC issue */ {} 77 | 78 | protected function env($key, $default = null) 79 | { 80 | $value = getenv($key); 81 | if (is_null($default)) { 82 | return $value; 83 | } 84 | 85 | return false === $value ? $default : $value; 86 | } 87 | } 88 | -------------------------------------------------------------------------------- /tests/support/TestController.php: -------------------------------------------------------------------------------- 1 | behaviors; 14 | } 15 | 16 | public function actionCreatePost() 17 | { 18 | return 'create success'; 19 | } 20 | 21 | public function actionUpdatePost() 22 | { 23 | return 'update success'; 24 | } 25 | 26 | public function actionDeletePost() 27 | { 28 | return 'delete success'; 29 | } 30 | 31 | public function actionComment() 32 | { 33 | return 'comment success'; 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /tests/support/UserIdentity.php: -------------------------------------------------------------------------------- 1 | 'alice', 17 | 'token2' => 'bob' 18 | ]; 19 | 20 | private $_id; 21 | 22 | private $_token; 23 | 24 | public static function findIdentity($id) 25 | { 26 | if (in_array($id, static::$ids)) { 27 | $identitiy = new static(); 28 | $identitiy->_id = $id; 29 | return $identitiy; 30 | } 31 | } 32 | 33 | public static function findIdentityByAccessToken($token, $type = null) 34 | { 35 | if (isset(static::$tokens[$token])) { 36 | $id = static::$tokens[$token]; 37 | $identitiy = new static(); 38 | $identitiy->_id = $id; 39 | $identitiy->_token = $token; 40 | return $identitiy; 41 | } 42 | } 43 | 44 | public function getId() 45 | { 46 | return $this->_id; 47 | } 48 | 49 | public function getAuthKey() 50 | { 51 | return null; 52 | } 53 | 54 | public function validateAuthKey($authKey) 55 | { 56 | return true; 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /tests/test.php: -------------------------------------------------------------------------------- 1 |