├── CHANGELOG.md ├── CONTRIBUTING.RU.md ├── CONTRIBUTING.md ├── LICENSE ├── README.RU.md ├── README.md ├── Yii2DbRbac.php ├── behaviors └── AccessBehavior.php ├── composer.json ├── controllers ├── AccessController.php └── UserController.php ├── interfaces └── UserRbacInterface.php ├── messages ├── en │ └── db_rbac.php └── pt-BR │ └── db_rbac.php └── views ├── access ├── addPermission.php ├── addRole.php ├── permission.php ├── role.php ├── updatePermission.php └── updateRole.php └── user └── view.php /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | Yii DB RBAC Change Log 2 | ======================= 3 | 4 | - new changes will go here 5 | 6 | 1.1.0 7 | ----- 8 | - Enh: Terminology and Translator Use (swartzlib7) 9 | - Enh: Configure roles that allow user to access module functionality (Pashkinz92) 10 | -------------------------------------------------------------------------------- /CONTRIBUTING.RU.md: -------------------------------------------------------------------------------- 1 | Подготовьте вашу локальную среду разработки 2 | ------------------------------------------- 3 | 4 | Следующие шаги помогут настроить локальную среду разработки. Они нужны только если это ваш первый pull request в данный репозиторий. 5 | 6 | ### 1. [Сделайте Fork](http://help.github.com/fork-a-repo/) этого репозитория на GitHub и склонируйте его в свою среду разработки. 7 | 8 | ``` 9 | git clone git@github.com:YOUR-GITHUB-USERNAME/yii2-db-rbac.git 10 | ``` 11 | 12 | 13 | ### 2. Теперь нужно добавить мой репозиторий как дополнительный удаленный через "upstream" 14 | 15 | Перейдите в директории, в которую только что склонировали репозиторий и выполните следующую команду: 16 | 17 | ``` 18 | git remote add upstream git://github.com/developeruz/yii2-db-rbac.git 19 | ``` 20 | 21 | 22 | Работа над ошибками и улучшениями 23 | --------------------------------- 24 | 25 | После подготовки локальной среды так как было указано выше, можно начинать работать над багами или улучшениями. 26 | 27 | ### 1. Получаем последнюю версию кода из основного репозитория 28 | 29 | ``` 30 | git fetch upstream 31 | ``` 32 | 33 | 34 | ### 2. Создаем новую ветку от ветки master 35 | 36 | Каждый баг-фикс или улучшение должны делаться в своей ветке. Имя ветки должно отражать суть изменений. 37 | Пример: 38 | 39 | ``` 40 | git checkout upstream/master 41 | git checkout -b name-of-your-branch-goes-here 42 | ``` 43 | 44 | ### 3. Творим свою магию 45 | 46 | Убедитесь что она работает :) 47 | 48 | ### 4. Обновляем CHANGELOG 49 | 50 | Внесите описание ваших изменений в файл CHANGELOG в начале файла. Строка изменений должна выглядеть так: 51 | 52 | ``` 53 | Bug: a description of the bug fix (Your Name) 54 | Enh: a description of the enhancement (Your Name) 55 | ``` 56 | 57 | 58 | ### 5. Закомитьте ваши изменения 59 | 60 | Добавьте измененые файлы в git 61 | 62 | ``` 63 | git add path/to/my/file.php 64 | ``` 65 | 66 | Закомитьте ваши изменения с кратиким описанием их сути. 67 | 68 | ``` 69 | git commit -m "A brief description of this change" 70 | ``` 71 | 72 | ### 6. Стяните последние изменения с основного репозитория 73 | 74 | ``` 75 | git pull upstream master 76 | ``` 77 | 78 | Если есть какие-то конфликты, вы должны исправить их прежде чем создавать pull request. Это позволит принять ваши изменения в один клик. 79 | 80 | ### 7. После исправления конфликтов, пушим изменения в свой репозиторий 81 | 82 | ``` 83 | git push -u origin name-of-your-branch-goes-here 84 | ``` 85 | 86 | ### 8. Создаем [pull request](http://help.github.com/send-pull-requests/) для основного репозитория. 87 | 88 | Откройте свой репозиторий на Github и кликните "Pull Request". 89 | 90 | ### Спасибо за сотрудничество! ### 91 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | Prepare your development environment 2 | ------------------------------------ 3 | 4 | The following steps will create a development environment. These steps only need to be done the first time you contribute. 5 | 6 | ### 1. [Fork](http://help.github.com/fork-a-repo/) this repository on GitHub and clone your fork to your development environment 7 | 8 | ``` 9 | git clone git@github.com:YOUR-GITHUB-USERNAME/yii2-db-rbac.git 10 | ``` 11 | 12 | 13 | ### 2. Add the main repository as an additional git remote called "upstream" 14 | 15 | Change to the directory where you cloned. Then enter the following command: 16 | 17 | ``` 18 | git remote add upstream git://github.com/developeruz/yii2-db-rbac.git 19 | ``` 20 | 21 | 22 | Working on bugs and features 23 | ---------------------------- 24 | 25 | Having prepared your develop environment as explained above you can now start working on the feature or bugfix. 26 | 27 | ### 1. Fetch the latest code from the main repository 28 | 29 | ``` 30 | git fetch upstream 31 | ``` 32 | 33 | You should start at this point for every new contribution to make sure you are working on the latest code. 34 | 35 | ### 2. Create a new branch for your feature based on the current master branch 36 | 37 | Each separate bug fix or change should go in its own branch. Branch names should be descriptive. 38 | For example: 39 | 40 | ``` 41 | git checkout upstream/master 42 | git checkout -b name-of-your-branch-goes-here 43 | ``` 44 | 45 | ### 3. Do your magic, write your code 46 | 47 | Make sure it works :) 48 | 49 | ### 4. Update the CHANGELOG 50 | 51 | Edit the CHANGELOG file to include your change. The line in the change log should look like one of the following: 52 | 53 | ``` 54 | Bug: a description of the bug fix (Your Name) 55 | Enh: a description of the enhancement (Your Name) 56 | ``` 57 | 58 | 59 | ### 5. Commit your changes 60 | 61 | add the files/changes you want to commit to the [staging area](http://gitref.org/basic/#add) with 62 | 63 | ``` 64 | git add path/to/my/file.php 65 | ``` 66 | 67 | Commit your changes with a descriptive commit message. 68 | 69 | ``` 70 | git commit -m "A brief description of this change" 71 | ``` 72 | 73 | ### 6. Pull the latest Yii code from upstream into your branch 74 | 75 | ``` 76 | git pull upstream master 77 | ``` 78 | 79 | This ensures you have the latest code in your branch before you open your pull request. If there are any merge conflicts, 80 | you should fix them now and commit the changes again. This ensures that it's easy to merge your changes with one click. 81 | 82 | ### 7. Having resolved any conflicts, push your code to GitHub 83 | 84 | ``` 85 | git push -u origin name-of-your-branch-goes-here 86 | ``` 87 | 88 | ### 8. Open a [pull request](http://help.github.com/send-pull-requests/) against upstream. 89 | 90 | Go to your repository on GitHub and click "Pull Request", choose your branch on the right and enter some more details 91 | in the comment box. 92 | 93 | ### Thank you for cooperation!### 94 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2014 Elvira Sheina 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | 23 | -------------------------------------------------------------------------------- /README.RU.md: -------------------------------------------------------------------------------- 1 | Динамическая настройка прав доступа для Yii2 2 | ============ 3 | 4 | Простой способ настроить права доступа в Yii без необходимости писать код. 5 | 6 | Модуль для создания ролей и прав доступа через веб-интерфейс, так же имеющий веб интерфейс для назначения ролей пользователям 7 | Поведение для приложения, проверяющее право доступа к action по внесенным в модуле правилам. 8 | 9 | ### Установка:### 10 | 11 | ```bash 12 | $ php composer.phar require developeruz/yii2-db-rbac "*" 13 | ``` 14 | 15 | Для корректной работы модуля необходимо настроить authManager в конфиге приложения (common/config/main.php для advanced или config/web.php и config/console для basic приложения) 16 | ```php 17 | 'components' => [ 18 | 'authManager' => [ 19 | 'class' => 'yii\rbac\DbManager', 20 | ], 21 | ... 22 | ] 23 | ``` 24 | 25 | И выполнить миграции, создающие таблицы для DbManager (подразумевается, что коннект к БД для приложения уже настроен) 26 | ```bash 27 | $ yii migrate --migrationPath=@yii/rbac/migrations/ 28 | ``` 29 | 30 | Подключение модуля 31 | ================== 32 | 33 | В конфиге приложения (backend/config/main.php для advanced или config/web.php для basic приложения) прописываем модуль 34 | ```php 35 | 'modules' => [ 36 | 'permit' => [ 37 | 'class' => 'developeruz\db_rbac\Yii2DbRbac', 38 | ], 39 | ], 40 | ``` 41 | Если нужно передать layout это можно сделать так: 42 | ```php 43 | 'modules' => [ 44 | 'permit' => [ 45 | 'class' => 'developeruz\db_rbac\Yii2DbRbac', 46 | 'layout' => '//admin' 47 | ], 48 | ], 49 | ``` 50 | 51 | Если вы используете ЧПУ, то убедитесь что у вас прописаны правила роутинга для модулей 52 | ```php 53 | '//' => '//', 54 | '///' => '//', 55 | ``` 56 | 57 | **Добавляем ссылки в меню** 58 | 59 | **/permit/access/role - управление ролями** 60 | 61 | **/permit/access/permission - управление правами доступа** 62 | 63 | ### Назначение ролей пользователям ### 64 | По многочисленным просьбам в модуль добавлен интерфейс для назначения ролей пользователям. 65 | 66 | Для корректной работы модуля нужно указать в параметрах модуля класс `User`. 67 | ```php 68 | 'modules' => [ 69 | 'permit' => [ 70 | 'class' => 'app\modules\db_rbac\Yii2DbRbac', 71 | 'params' => [ 72 | 'userClass' => 'app\models\User' 73 | ] 74 | ], 75 | ], 76 | ``` 77 | 78 | Класс User должен реализовывать интерфейс `developeruz\db_rbac\interfaces\UserRbacInterface`. 79 | В большинстве случаев придется дописать в нем 1 функцию `getUserName()` которая будет возвращать отображаемое имя пользователя. 80 | ```php 81 | use developeruz\db_rbac\interfaces\UserRbacInterface; 82 | 83 | class User extends ActiveRecord implements IdentityInterface, UserRbacInterface 84 | { 85 | ... 86 | public function getUserName() 87 | { 88 | return $this->username; 89 | } 90 | } 91 | ``` 92 | 93 | **Управление ролью пользователя происходит на странице `/permit/user/view/1` для пользователя с id=1.** 94 | Удобнее всего дописать кнопку на эту страницу в Grid со списком пользователей. 95 | ```php 96 | echo GridView::widget([ 97 | 'dataProvider' => $dataProvider, 98 | 'columns' => [ 99 | ['class' => 'yii\grid\SerialColumn'], 100 | 101 | 'id', 102 | 'username', 103 | 'email:email', 104 | 105 | ['class' => 'yii\grid\ActionColumn', 106 | 'template' => '{view}  {update}  {permit}  {delete}', 107 | 'buttons' => 108 | [ 109 | 'permit' => function ($url, $model) { 110 | return Html::a('', Url::to(['/permit/user/view', 'id' => $model->id]), [ 111 | 'title' => Yii::t('yii', 'Change user role') 112 | ]); }, 113 | ] 114 | ], 115 | ], 116 | ]); 117 | ``` 118 | 119 | Присвоить роль пользователю можно и в коде, например при создании нового пользователя. 120 | ```php 121 | $userRole = Yii::$app->authManager->getRole('name_of_role'); 122 | Yii::$app->authManager->assign($userRole, $user->getId()); 123 | ``` 124 | 125 | Проверить, имеет ли пользователь право на действие можно через метод `can()` компонента User 126 | ```php 127 | Yii::$app->user->can($permissionName); 128 | ``` 129 | $permissionName - может быть как ролью так и правом 130 | 131 | ### Ограничение доступа к модулю на основе ролей ### 132 | 133 | В конфиге модуля можно передать список ролей, у которых есть доступ к функционалу модуля. 134 | ```php 135 | 'modules' => [ 136 | 'permit' => [ 137 | 'class' => 'app\modules\db_rbac\Yii2DbRbac', 138 | 'params' => [ 139 | 'userClass' => 'app\models\User', 140 | 'accessRoles' => ['admin'] 141 | ] 142 | ], 143 | ], 144 | ``` 145 | 146 | 147 | Поведение, динамически проверяющее наличие прав 148 | =============================================== 149 | 150 | Данное поведение позволяет не писать Yii::$app->user->can($permissionName); в каждом action, а проверять права доступа на лету. 151 | Это удобно для гибкой настройки прав при использовании сторонних модулей. 152 | 153 | ### Подключение поведения ### 154 | В конфиге того приложения, доступ к которому следует проверять на лету, необходимо подключить поведение 155 | ```php 156 | use developeruz\db_rbac\behaviors\AccessBehavior; 157 | 158 | 'as AccessBehavior' => [ 159 | 'class' => \developeruz\db_rbac\behaviors\AccessBehavior::className(), 160 | ] 161 | ``` 162 | С этого момента, после обработки запроса (событие EVENT_BEFORE_ACTION) проверяются права текущего пользователя (Yii::$app->user) на выполнение запрашиваемого действия (Yii::$app->user->can()) 163 | Действие считается разрешенным, если: 164 | - пользователю разрешен доступ к конкретному action (правило записано как: module/controller/action) 165 | - пользователю разрешен доступ к любым action данного контроллера (правило записано как: module/controller) 166 | - пользователю разрешен доступ к любым action данного модуля (правило записано как: module) 167 | 168 | ### Настройка редиректа при отсутствии доступа### 169 | По умолчанию, при отсутствии у пользователя доступа, поведение бросает **ForbiddenHttpException**, который может обрабатываться приложением так как ему нужно. 170 | 171 | Так-же можно настроить **login_url** для редиректа не авторизованного пользователя, в случаи отсутствия у него прав доступа к данной странице и **redirect_url** для перенаправления вне зависимости от авторизованности пользователя 172 | ```php 173 | 'as AccessBehavior' => [ 174 | 'class' => \developeruz\db_rbac\behaviors\AccessBehavior::className(), 175 | 'redirect_url' => '/forbidden', 176 | 'login_url' => Yii::$app->user->loginUrl 177 | ] 178 | ``` 179 | 180 | ### Настройка прав доступа по умолчанию ### 181 | После подключения поведения, доступ становится возможен только авторизованному пользователю, имеющему некие права. 182 | Для исключений из этого правила можно прописать доступы по умолчанию в том же формате AccessControl, что и в контроллере: 183 | ```php 184 | 'as AccessBehavior' => [ 185 | 'class' => \developeruz\db_rbac\behaviors\AccessBehavior::className(), 186 | 'rules' => 187 | ['site' => 188 | [ 189 | [ 190 | 'actions' => ['login', 'index'], 191 | 'allow' => true, 192 | ], 193 | [ 194 | 'actions' => ['about'], 195 | 'allow' => true, 196 | 'roles' => ['admin'], 197 | ], 198 | ] 199 | ] 200 | ] 201 | ``` 202 | В приведенном выше примере разрешен доступ любому пользователю к site/login и site/index и доступ пользователя с ролью admin к site/about 203 | Правила прописанные в конфиге имеют приоритет над динамически настраиваемыми правилами. 204 | 205 | ### Настройка зоны ответственности поведения 206 | По умолчанию действует правило "запрещено все, что не разрещено". Если поведение должно защищать только некоторые пути, 207 | а все остальные должны быть доступны всем, то в настройках поведения можно задать параметр `protect`: 208 | ```php 209 | 'as AccessBehavior' => [ 210 | 'class' => \developeruz\db_rbac\behaviors\AccessBehavior::className(), 211 | 'protect' => ['admin', 'user', 'site/about'], 212 | 'rules' => [ 213 | 'user' => [['actions' => ['login'], 'allow' => true ], 214 | ['actions' => ['logout'], 'roles' => ['@'], 'allow' => true ]] 215 | ] 216 | ], 217 | 218 | ``` 219 | В данном примере поведение будет проверять права пользователя на доступ к странице только для путей начинающихся с `admin`, `user` и `site/about`. 220 | Все остальные пути становятся доступными всем (не проверяются данным поведением). Как видно из примера, параметр `protect` можно комбинировать с `rules`. 221 | 222 | Сотрудничество 223 | ============== 224 | 225 | Я с удовольствием и благодарностью приму ваши предложения по улучшению модуля. Все предложения следует подавать через Pull Request. 226 | О том как создать Pull Request смотрите в [CONTRIBUTING](CONTRIBUTING.RU.md). 227 | 228 | License 229 | ======= 230 | 231 | The MIT License (MIT). Please see [License File](LICENSE.md) for more information. 232 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Dynamic Access Control for Yii2 2 | ============================================ 3 | 4 | ##### НА РУССКОМ [ТУТ](https://github.com/developeruz/yii2-db-rbac/blob/master/README.RU.md) 5 | 6 | The easiest way to create access control in Yii2 without changes in the code. 7 | 8 | This module allows creating roles and rules for Yii role base access (RBAC) via UI. 9 | It also allows assigning roles and rules for user via UI. 10 | Behaviour that checks access by the modules rules. 11 | 12 | ### Integrations 13 | CMS | Module 14 | ------------ | ------------- 15 | EasyiiCMS | https://github.com/developeruz/easyii-rbac-module 16 | *Feel free to request integration with any CMS/Packages which is written on Yii2* 17 | 18 | ### Installation guide 19 | ```bash 20 | $ php composer.phar require developeruz/yii2-db-rbac "*" 21 | ``` 22 | 23 | To work correctly, you must configure the module `authManager` in the application config file (`common/config/main.php` for advanced app 24 | or `config/web.php` and `config/console` for basic app) 25 | ```php 26 | 'components' => [ 27 | 'authManager' => [ 28 | 'class' => 'yii\rbac\DbManager', 29 | ], 30 | ... 31 | ] 32 | ``` 33 | 34 | Run migration to create `DbManager` table (it means that a connection to the database is already configured for the application) 35 | ```bash 36 | $ yii migrate --migrationPath=@yii/rbac/migrations/ 37 | ``` 38 | 39 | Add the module 40 | ============== 41 | 42 | Include module to the config file (`backend/config/main.php` for advanced app or `config/web.php` for basic app) 43 | ```php 44 | 'modules' => [ 45 | 'permit' => [ 46 | 'class' => 'developeruz\db_rbac\Yii2DbRbac', 47 | ], 48 | ], 49 | ``` 50 | 51 | If you want to setup layout, put it in the following way 52 | ```php 53 | 'modules' => [ 54 | 'permit' => [ 55 | 'class' => 'developeruz\db_rbac\Yii2DbRbac', 56 | 'layout' => '//admin' 57 | ], 58 | ], 59 | ``` 60 | 61 | If you use CNC, be sure that you have correct routing rules for modules 62 | ```php 63 | '//' => '//', 64 | '///' => '//', 65 | ``` 66 | 67 | **Adding links** 68 | 69 | **/permit/access/role - manage roles** 70 | 71 | **/permit/access/permission - manage access** 72 | 73 | ### Assigning role to a user 74 | 75 | The module also has an interface for assigning roles to users. 76 | 77 | To work correctly, the module should be specified with `User` class in the module parameters. 78 | ```php 79 | 'modules' => [ 80 | 'permit' => [ 81 | 'class' => 'app\modules\db_rbac\Yii2DbRbac', 82 | 'params' => [ 83 | 'userClass' => 'app\models\User' 84 | ] 85 | ], 86 | ], 87 | ``` 88 | 89 | User class should implement `developeruz\db_rbac\interfaces\UserRbacInterface`. 90 | In most cases, you have to add function `getUserName()` which should return user's name. 91 | 92 | ```php 93 | use developeruz\db_rbac\interfaces\UserRbacInterface; 94 | 95 | class User extends ActiveRecord implements IdentityInterface, UserRbacInterface 96 | { 97 | ... 98 | public function getUserName() 99 | { 100 | return $this->username; 101 | } 102 | } 103 | ``` 104 | 105 | **For managing role for user with id=1, visit `/permit/user/view/1`** 106 | 107 | The easiest way is to add this as a button in `GridView` with users list. 108 | ```php 109 | echo GridView::widget([ 110 | 'dataProvider' => $dataProvider, 111 | 'columns' => [ 112 | ['class' => 'yii\grid\SerialColumn'], 113 | 114 | 'id', 115 | 'username', 116 | 'email:email', 117 | 118 | ['class' => 'yii\grid\ActionColumn', 119 | 'template' => '{view}  {update}  {permit}  {delete}', 120 | 'buttons' => 121 | [ 122 | 'permit' => function ($url, $model) { 123 | return Html::a('', Url::to(['/permit/user/view', 'id' => $model->id]), [ 124 | 'title' => Yii::t('yii', 'Change user role') 125 | ]); }, 126 | ] 127 | ], 128 | ], 129 | ]); 130 | ``` 131 | 132 | You can also assign a role to the user in the code, for example when user has been created. 133 | ```php 134 | $userRole = Yii::$app->authManager->getRole('name_of_role'); 135 | Yii::$app->authManager->assign($userRole, $user->getId()); 136 | ``` 137 | 138 | You also can check if a user has access in code thought `can()` method in User class 139 | ```php 140 | Yii::$app->user->can($permissionName); 141 | ``` 142 | $permissionName - could be a role name or a permission name. 143 | 144 | ### Configure module's Access Control ### 145 | 146 | In the config you can set the list of roles that have access to module functionality. 147 | ```php 148 | 'modules' => [ 149 | 'permit' => [ 150 | 'class' => 'app\modules\db_rbac\Yii2DbRbac', 151 | 'params' => [ 152 | 'userClass' => 'app\models\User', 153 | 'accessRoles' => ['admin'] 154 | ] 155 | ], 156 | ], 157 | ``` 158 | 159 | Behaviour that checks access by the modules rules 160 | ================================================= 161 | 162 | By using this behaviour you don't need to write `Yii::$app->user->can($permissionName)` in each action. Behaviour will check it automatically. 163 | It is also useful for access control with the third party modules. 164 | 165 | ### Configure behaviour 166 | 167 | You have to include behaviour to the app config file, if you want to check access automatically. 168 | 169 | ```php 170 | use developeruz\db_rbac\behaviors\AccessBehavior; 171 | 172 | 'as AccessBehavior' => [ 173 | 'class' => \developeruz\db_rbac\behaviors\AccessBehavior::className(), 174 | ] 175 | ``` 176 | 177 | On `EVENT_BEFORE_ACTION` behaviour will check access for current user (`Yii::$app->user`) to the action. 178 | Action is allowed if: 179 | - a user has access to the action (rule: module/controller/action) 180 | - a user has acceess to any action in the controller (rule: module/controller) 181 | - a user has access to any action in the module (rule: module) 182 | 183 | ### Redirection if access denied 184 | By default if a user doesn't have access, behaviour will throw `ForbiddenHttpException`. Application can handle this exception as needed. 185 | 186 | You also can configure `login_url` where unauthorized user will be redirected, or `redirect_url` for redirecting a user when access is denied. 187 | ```php 188 | 'as AccessBehavior' => [ 189 | 'class' => \developeruz\db_rbac\behaviors\AccessBehavior::className(), 190 | 'redirect_url' => '/forbidden', 191 | 'login_url' => Yii::$app->user->loginUrl 192 | ] 193 | ``` 194 | 195 | ### Configure default access rules 196 | 197 | After connecting behavior, access is available only to authorized users with certain rights. 198 | You can create default access rights in config file in the same way as you do in controller (`AccessControl`): 199 | ```php 200 | 'as AccessBehavior' => [ 201 | 'class' => \developeruz\db_rbac\behaviors\AccessBehavior::className(), 202 | 'rules' => 203 | ['site' => 204 | [ 205 | [ 206 | 'actions' => ['login', 'index'], 207 | 'allow' => true, 208 | ], 209 | [ 210 | 'actions' => ['about'], 211 | 'allow' => true, 212 | 'roles' => ['admin'], 213 | ], 214 | ] 215 | ] 216 | ] 217 | ``` 218 | 219 | In this example any user has access to `site/login` and `site/index` and only user with role `admin` has access to `site/about`. 220 | The rules described in the configuration take precedence over dynamically configurable rules. 221 | 222 | ### Configure areas of behavior responsibility 223 | By default, the rule is "all is prohibited unless is allowed." If the behavior is supposed to protect only certain routes, 224 | and all others should be accessible for all, please set up `protect` parameter 225 | ```php 226 | 'as AccessBehavior' => [ 227 | 'class' => \developeruz\db_rbac\behaviors\AccessBehavior::className(), 228 | 'protect' => ['admin', 'user', 'site/about'], 229 | 'rules' => [ 230 | 'user' => [['actions' => ['login'], 'allow' => true ], 231 | ['actions' => ['logout'], 'roles' => ['@'], 'allow' => true ]] 232 | ] 233 | ], 234 | 235 | ``` 236 | In this example, the behavior will check the user's permission to access the page only for paths beginning 237 | with `admin`,` user` and `site / about`. All other routes are available for all (not verified by the behavior). 238 | As you can see in the example, the parameter `protect` can be combined with `rules`. 239 | 240 | Contributing 241 | ============ 242 | 243 | Contributions are **welcome** and will be fully **credited**. 244 | I accept contributions via Pull Requests. Please see [CONTRIBUTING](CONTRIBUTING.md) for details. 245 | 246 | License 247 | ======= 248 | 249 | The MIT License (MIT). Please see [License File](LICENSE.md) for more information. 250 | -------------------------------------------------------------------------------- /Yii2DbRbac.php: -------------------------------------------------------------------------------- 1 | 6 | * @version 1.1 7 | * @package Yii2DbRbac for Yii2 8 | * 9 | */ 10 | namespace developeruz\db_rbac; 11 | 12 | use Yii; 13 | 14 | class Yii2DbRbac extends \yii\base\Module 15 | { 16 | public $controllerNamespace = 'developeruz\db_rbac\controllers'; 17 | public $theme = false; 18 | public $userClass; 19 | public $accessRoles; 20 | 21 | public function init() 22 | { 23 | parent::init(); 24 | $this->registerTranslations(); 25 | 26 | if ($this->theme) { 27 | Yii::$app->view->theme = new \yii\base\Theme($this->theme); 28 | } 29 | } 30 | 31 | public function registerTranslations() 32 | { 33 | if (!isset(Yii::$app->i18n->translations['db_rbac'])) { 34 | Yii::$app->i18n->translations['db_rbac'] = [ 35 | 'class' => 'yii\i18n\PhpMessageSource', 36 | 'sourceLanguage' => 'ru-Ru', 37 | 'basePath' => '@developeruz/db_rbac/messages', 38 | ]; 39 | } 40 | } 41 | 42 | public static function t($category, $message, $params = [], $language = null) 43 | { 44 | return Yii::t('modules/db_rbac/' . $category, $message, $params, $language); 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /behaviors/AccessBehavior.php: -------------------------------------------------------------------------------- 1 | 6 | * @version 0.1 7 | * @package AccessBehavior for Yii2 8 | * 9 | */ 10 | namespace developeruz\db_rbac\behaviors; 11 | 12 | use Yii; 13 | use yii\behaviors\AttributeBehavior; 14 | use yii\di\Instance; 15 | use yii\base\Module; 16 | use yii\web\Application; 17 | use yii\web\User; 18 | use yii\filters\AccessControl; 19 | use yii\web\ForbiddenHttpException; 20 | 21 | class AccessBehavior extends AttributeBehavior 22 | { 23 | 24 | public $rules = []; 25 | public $redirect_url = false; 26 | public $login_url = false; 27 | public $protect = []; 28 | 29 | private $_rules = []; 30 | 31 | public function events() 32 | { 33 | return [ 34 | Module::EVENT_BEFORE_ACTION => 'interception', 35 | ]; 36 | } 37 | 38 | public function interception($event) 39 | { 40 | if (!isset(Yii::$app->i18n->translations['db_rbac'])) { 41 | Yii::$app->i18n->translations['db_rbac'] = [ 42 | 'class' => 'yii\i18n\PhpMessageSource', 43 | 'sourceLanguage' => 'ru-Ru', 44 | 'basePath' => '@developeruz/db_rbac/messages', 45 | ]; 46 | } 47 | 48 | $route = Yii::$app->getRequest()->resolve(); 49 | 50 | //Проверяем нужно ли вообще проверять 51 | if (!empty($this->protect)) { 52 | $needToBeProtected = false; 53 | $routes = $this->createPartRoutes($route); 54 | foreach ($routes as $routeVariant) { 55 | if (in_array($routeVariant, $this->protect)) { 56 | $needToBeProtected = true; 57 | break; 58 | } 59 | } 60 | if (!$needToBeProtected) { 61 | return; 62 | } 63 | } 64 | 65 | //Проверяем права по конфигу 66 | $this->createRule(); 67 | $user = Instance::ensure(Yii::$app->user, User::className()); 68 | $request = Yii::$app->getRequest(); 69 | $action = $event->action; 70 | 71 | if (!$this->cheсkByRule($action, $user, $request)) { 72 | //И по AuthManager 73 | if (!$this->checkPermission($route)) { 74 | //Если задан $login_url и пользователь не авторизован 75 | if (Yii::$app->user->isGuest && $this->login_url) { 76 | Yii::$app->response->redirect($this->login_url)->send(); 77 | exit(); 78 | } 79 | //Если задан $redirect_url 80 | if ($this->redirect_url) { 81 | Yii::$app->response->redirect($this->redirect_url)->send(); 82 | exit(); 83 | } else { 84 | throw new ForbiddenHttpException(Yii::t('db_rbac', 'Недостаточно прав')); 85 | } 86 | } 87 | } 88 | } 89 | 90 | protected function createRule() 91 | { 92 | foreach ($this->rules as $controller => $rule) { 93 | foreach ($rule as $singleRule) { 94 | if (is_array($singleRule)) { 95 | $option = [ 96 | 'controllers' => [$controller], 97 | 'class' => 'yii\filters\AccessRule' 98 | ]; 99 | $this->_rules[] = Yii::createObject(array_merge($option, $singleRule)); 100 | } 101 | } 102 | } 103 | } 104 | 105 | protected function cheсkByRule($action, $user, $request) 106 | { 107 | foreach ($this->_rules as $rule) { 108 | if ($rule->allows($action, $user, $request)) { 109 | return true; 110 | } 111 | } 112 | return false; 113 | } 114 | 115 | protected function checkPermission($route) 116 | { 117 | //$route[0] - is the route, $route[1] - is the associated parameters 118 | $routes = $this->createPartRoutes($route); 119 | foreach ($routes as $routeVariant) { 120 | if (Yii::$app->user->can($routeVariant, $route[1])) { 121 | return true; 122 | } 123 | } 124 | return false; 125 | } 126 | 127 | protected function createPartRoutes($route) 128 | { 129 | //$route[0] - is the route, $route[1] - is the associated parameters 130 | 131 | $routePathTmp = explode('/', trim($route[0], '/')); 132 | $result = []; 133 | $routeVariant = array_shift($routePathTmp); 134 | $result[] = $routeVariant; 135 | 136 | foreach ($routePathTmp as $routePart) { 137 | $routeVariant .= '/' . $routePart; 138 | $result[] = $routeVariant; 139 | } 140 | return $result; 141 | } 142 | } 143 | -------------------------------------------------------------------------------- /composer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "developeruz/yii2-db-rbac", 3 | "description": "Dynamic control of access rights in YII2", 4 | "keywords": ["yii", "rbac"], 5 | "type": "yii2-extension", 6 | "license": "MIT", 7 | "authors": [ 8 | { 9 | "name": "Elvira Sheina", 10 | "email": "elleuz@gmail.com", 11 | "homepage": "http://developer.uz" 12 | } 13 | ], 14 | "require": { 15 | "yiisoft/yii2": "*" 16 | }, 17 | "support": { 18 | "issues": "https://github.com/developeruz/yii2-db-rbac/issues" 19 | }, 20 | "autoload": { 21 | "psr-4": { 22 | "developeruz\\db_rbac\\": "" 23 | } 24 | } 25 | } -------------------------------------------------------------------------------- /controllers/AccessController.php: -------------------------------------------------------------------------------- 1 | 6 | * @version 0.1 7 | * @package AccessController for Yii2 8 | * 9 | */ 10 | namespace developeruz\db_rbac\controllers; 11 | 12 | use Yii; 13 | use yii\web\Controller; 14 | use yii\web\BadRequestHttpException; 15 | use yii\rbac\Role; 16 | use yii\rbac\Permission; 17 | use yii\helpers\ArrayHelper; 18 | use yii\helpers\Url; 19 | use yii\validators\RegularExpressionValidator; 20 | 21 | class AccessController extends Controller 22 | { 23 | protected $error; 24 | protected $pattern4Role = '/^[a-zA-Z0-9_-]+$/'; 25 | protected $pattern4Permission = '/^[a-zA-Z0-9_\/-]+$/'; 26 | 27 | public function behaviors() 28 | { 29 | if (!empty(Yii::$app->controller->module->params['accessRoles'])) { 30 | return [ 31 | 'access' => [ 32 | 'class' => \yii\filters\AccessControl::className(), 33 | 'rules' => [ 34 | [ 35 | 'allow' => true, 36 | 'roles' => Yii::$app->controller->module->params['accessRoles'], 37 | ], 38 | ], 39 | ], 40 | ]; 41 | } else return []; 42 | } 43 | 44 | public function actions() 45 | { 46 | return [ 47 | 'error' => [ 48 | 'class' => 'yii\web\ErrorAction', 49 | ], 50 | ]; 51 | } 52 | 53 | public function actionRole() 54 | { 55 | return $this->render('role'); 56 | } 57 | 58 | public function actionAddRole() 59 | { 60 | if (Yii::$app->request->post('name') 61 | && $this->validate(Yii::$app->request->post('name'), $this->pattern4Role) 62 | && $this->isUnique(Yii::$app->request->post('name')) 63 | ) { 64 | $role = Yii::$app->authManager->createRole(Yii::$app->request->post('name')); 65 | $role->description = Yii::$app->request->post('description'); 66 | Yii::$app->authManager->add($role); 67 | $this->setPermissions(Yii::$app->request->post('permissions', []), $role); 68 | return $this->redirect(Url::toRoute([ 69 | 'update-role', 70 | 'name' => $role->name 71 | ])); 72 | } 73 | 74 | $permissions = ArrayHelper::map(Yii::$app->authManager->getPermissions(), 'name', 'description'); 75 | return $this->render( 76 | 'addRole', 77 | [ 78 | 'permissions' => $permissions, 79 | 'error' => $this->error 80 | ] 81 | ); 82 | } 83 | 84 | public function actionUpdateRole($name) 85 | { 86 | $role = Yii::$app->authManager->getRole($name); 87 | 88 | $permissions = ArrayHelper::map(Yii::$app->authManager->getPermissions(), 'name', 'description'); 89 | $role_permit = array_keys(Yii::$app->authManager->getPermissionsByRole($name)); 90 | 91 | if ($role instanceof Role) { 92 | if (Yii::$app->request->post('name') 93 | && $this->validate(Yii::$app->request->post('name'), $this->pattern4Role) 94 | ) { 95 | if (Yii::$app->request->post('name') != $name && !$this->isUnique(Yii::$app->request->post('name'), 'role')) { 96 | return $this->render( 97 | 'updateRole', 98 | [ 99 | 'role' => $role, 100 | 'permissions' => $permissions, 101 | 'role_permit' => $role_permit, 102 | 'error' => $this->error 103 | ] 104 | ); 105 | } 106 | $role = $this->setAttribute($role, Yii::$app->request->post()); 107 | Yii::$app->authManager->update($name, $role); 108 | $this->updatePermissions($permissions, Yii::$app->request->post('permissions', []), $role); 109 | return $this->redirect(Url::toRoute([ 110 | 'update-role', 111 | 'name' => $role->name 112 | ])); 113 | } 114 | 115 | return $this->render( 116 | 'updateRole', 117 | [ 118 | 'role' => $role, 119 | 'permissions' => $permissions, 120 | 'role_permit' => $role_permit, 121 | 'error' => $this->error 122 | ] 123 | ); 124 | } else { 125 | throw new BadRequestHttpException(Yii::t('db_rbac', 'Страница не найдена')); 126 | } 127 | } 128 | 129 | public function actionDeleteRole($name) 130 | { 131 | $role = Yii::$app->authManager->getRole($name); 132 | if ($role) { 133 | Yii::$app->authManager->removeChildren($role); 134 | Yii::$app->authManager->remove($role); 135 | } 136 | return $this->redirect(Url::toRoute(['role'])); 137 | } 138 | 139 | 140 | public function actionPermission() 141 | { 142 | return $this->render('permission'); 143 | } 144 | 145 | public function actionAddPermission() 146 | { 147 | $permission = $this->clear(Yii::$app->request->post('name')); 148 | if ($permission 149 | && $this->validate($permission, $this->pattern4Permission) 150 | && $this->isUnique($permission, 'permission') 151 | ) { 152 | $permit = Yii::$app->authManager->createPermission($permission); 153 | $permit->description = Yii::$app->request->post('description', ''); 154 | Yii::$app->authManager->add($permit); 155 | return $this->redirect(Url::toRoute([ 156 | 'update-permission', 157 | 'name' => $permit->name 158 | ])); 159 | } 160 | 161 | return $this->render('addPermission', ['error' => $this->error]); 162 | } 163 | 164 | public function actionUpdatePermission($name) 165 | { 166 | $permit = Yii::$app->authManager->getPermission($name); 167 | if ($permit instanceof Permission) { 168 | $permission = $this->clear(Yii::$app->request->post('name')); 169 | if ($permission && $this->validate($permission, $this->pattern4Permission) 170 | ) { 171 | if ($permission != $name && !$this->isUnique($permission)) { 172 | return $this->render('updatePermission', [ 173 | 'permit' => $permit, 174 | 'error' => $this->error 175 | ]); 176 | } 177 | 178 | $permit->name = $permission; 179 | $permit->description = Yii::$app->request->post('description', ''); 180 | Yii::$app->authManager->update($name, $permit); 181 | return $this->redirect(Url::toRoute([ 182 | 'update-permission', 183 | 'name' => $permit->name 184 | ])); 185 | } 186 | 187 | return $this->render('updatePermission', [ 188 | 'permit' => $permit, 189 | 'error' => $this->error 190 | ]); 191 | } else { 192 | throw new BadRequestHttpException(Yii::t('db_rbac', 'Страница не найдена')); 193 | } 194 | } 195 | 196 | public function actionDeletePermission($name) 197 | { 198 | $permit = Yii::$app->authManager->getPermission($name); 199 | if ($permit) { 200 | Yii::$app->authManager->remove($permit); 201 | } 202 | return $this->redirect(Url::toRoute(['permission'])); 203 | } 204 | 205 | protected function setAttribute($object, $data) 206 | { 207 | $object->name = $data['name']; 208 | $object->description = $data['description']; 209 | return $object; 210 | } 211 | 212 | protected function setPermissions($permissions, $role) 213 | { 214 | foreach ($permissions as $permit) { 215 | $new_permit = Yii::$app->authManager->getPermission($permit); 216 | Yii::$app->authManager->addChild($role, $new_permit); 217 | } 218 | } 219 | 220 | protected function updatePermissions($allPermissions, $selectedPermissions, $role) 221 | { 222 | foreach ($allPermissions as $permit => $description) { 223 | $permission = Yii::$app->authManager->getPermission($permit); 224 | if (in_array($permit, $selectedPermissions)) { 225 | if (!Yii::$app->authManager->hasChild($role, $permission)) { 226 | Yii::$app->authManager->addChild($role, $permission); 227 | } 228 | } elseif (Yii::$app->authManager->hasChild($role, $permission)) { 229 | Yii::$app->authManager->removeChild($role, $permission); 230 | } 231 | } 232 | } 233 | 234 | protected function validate($field, $regex) 235 | { 236 | $validator = new RegularExpressionValidator(['pattern' => $regex]); 237 | if ($validator->validate($field)) { 238 | return true; 239 | } else { 240 | $this->error[] = Yii::t('db_rbac', 'Значение "{field}" содержит недопустимые символы', ['field' => $field]); 241 | return false; 242 | } 243 | } 244 | 245 | protected function isUnique($name) 246 | { 247 | $role = Yii::$app->authManager->getRole($name); 248 | $permission = Yii::$app->authManager->getPermission($name); 249 | if ($permission instanceof Permission) { 250 | $this->error[] = Yii::t('db_rbac', 'Разрешение с таким именем уже существует') . ':' . $name; 251 | return false; 252 | } 253 | if ($role instanceof Role) { 254 | $this->error[] = Yii::t('db_rbac', 'Роль с таким именем уже существует') . ':' . $name; 255 | return false; 256 | } 257 | return true; 258 | } 259 | 260 | protected function clear($value) 261 | { 262 | if (!empty($value)) { 263 | $value = trim($value, "/ \t\n\r\0\x0B"); 264 | } 265 | 266 | return $value; 267 | } 268 | } 269 | -------------------------------------------------------------------------------- /controllers/UserController.php: -------------------------------------------------------------------------------- 1 | 6 | * @version 0.1 7 | * @package UserController for Yii2 8 | * 9 | */ 10 | namespace developeruz\db_rbac\controllers; 11 | 12 | use Yii; 13 | use yii\filters\VerbFilter; 14 | use yii\helpers\ArrayHelper; 15 | use yii\helpers\Url; 16 | use yii\web\Controller; 17 | use yii\web\BadRequestHttpException; 18 | use developeruz\db_rbac\interfaces\UserRbacInterface; 19 | use yii\web\NotFoundHttpException; 20 | 21 | class UserController extends Controller 22 | { 23 | public $moduleName = 'permit'; 24 | 25 | public function beforeAction($action) 26 | { 27 | if (empty(Yii::$app->controller->module->params['userClass'])) { 28 | throw new BadRequestHttpException(Yii::t('db_rbac', 'Необходимо указать класс User в настройках модуля')); 29 | } 30 | 31 | $user = new Yii::$app->controller->module->params['userClass'](); 32 | 33 | if (!$user instanceof UserRbacInterface) { 34 | throw new BadRequestHttpException(Yii::t('db_rbac', 35 | 'UserClass должен реализовывать интерфейс developeruz\db_rbac\UserRbacInterface')); 36 | } 37 | 38 | return parent::beforeAction($action); 39 | } 40 | 41 | public function actions() 42 | { 43 | return [ 44 | 'error' => [ 45 | 'class' => 'yii\web\ErrorAction', 46 | ], 47 | ]; 48 | } 49 | 50 | public function behaviors() 51 | { 52 | $behavior = [ 53 | 'verbs' => [ 54 | 'class' => VerbFilter::className(), 55 | 'actions' => [ 56 | 'update' => ['post'], 57 | '*' => ['get'], 58 | ], 59 | ] 60 | ]; 61 | 62 | if (!empty(Yii::$app->controller->module->params['accessRoles'])) { 63 | $behavior['access'] = [ 64 | 'class' => \yii\filters\AccessControl::className(), 65 | 'rules' => [ 66 | [ 67 | 'allow' => true, 68 | 'roles' => Yii::$app->controller->module->params['accessRoles'], 69 | ], 70 | ], 71 | ]; 72 | } 73 | 74 | return $behavior; 75 | } 76 | 77 | public function actionView($id) 78 | { 79 | $roles = ArrayHelper::map(Yii::$app->authManager->getRoles(), 'name', 'description'); 80 | $user_permit = array_keys(Yii::$app->authManager->getRolesByUser($id)); 81 | $user = $this->findUser($id); 82 | return $this->render('view', [ 83 | 'user' => $user, 84 | 'roles' => $roles, 85 | 'user_permit' => $user_permit, 86 | 'moduleName' => Yii::$app->controller->module->id 87 | ]); 88 | } 89 | 90 | public function actionUpdate($id) 91 | { 92 | $user = $this->findUser($id); 93 | Yii::$app->authManager->revokeAll($user->getId()); 94 | if (Yii::$app->request->post('roles')) { 95 | foreach (Yii::$app->request->post('roles') as $role) { 96 | $new_role = Yii::$app->authManager->getRole($role); 97 | Yii::$app->authManager->assign($new_role, $user->getId()); 98 | } 99 | } 100 | return $this->redirect(Url::to([ 101 | "view", 102 | 'id' => $user->getId() 103 | ])); 104 | } 105 | 106 | private function findUser($id) 107 | { 108 | $class = new Yii::$app->controller->module->params['userClass'](); 109 | $user = $class::findIdentity($id); 110 | if (empty($user)) { 111 | throw new NotFoundHttpException(Yii::t('db_rbac', 'Пользователь не найден')); 112 | } else { 113 | return $user; 114 | } 115 | } 116 | } 117 | -------------------------------------------------------------------------------- /interfaces/UserRbacInterface.php: -------------------------------------------------------------------------------- 1 | 'Role with the same name already exists', 4 | 'Разрешение с таким именем уже существует' => 'Permission with the same name already exists', 5 | 'Значение "{field}" содержит недопустимые символы' => 'Value "{field}" contains invalid characters', 6 | 'Страница не найдена' => 'Page not found', 7 | 'Недостаточно прав' => 'You not allow to access', 8 | 'Необходимо указать класс User в настройках модуля' => 'UserClass params must be set in config file', 9 | 'UserClass должен реализовывать интерфейс developeruz\db_rbac\UserRbacInterface' => 'UserClass must implements developeruz\db_rbac\UserRbacInterface', 10 | 'Пользователь не найден' => 'User not found', 11 | 'Новое правило' => 'Add Permission', 12 | 'Правила доступа' => 'Permissions', 13 | 'Текстовое описание' => 'Description', 14 | 'Разрешенный доступ' => 'Allowed Access', 15 | '
* Формат: module/controller/action
site/article - доступ к странице "site/article"
site - доступ к любым action контроллера "site"' => 16 | '
* Format: module/controller/action
site/article - access to page "site/article"
site - access to any action in "site" controller', 17 | 'Сохранить' => 'Save', 18 | 'Новая роль' => 'Add Role', 19 | 'Управление ролями' => 'Roles', 20 | 'Название роли' => 'Title for Role', 21 | 'Добавить новое правило' => 'Add Permission', 22 | 'Правило' => 'Permission', 23 | 'Описание' => 'Description', 24 | 'Добавить роль' => 'Add Role', 25 | 'Роль' => 'Role', 26 | 'Редактирование правила: ' => 'Edit Permission', 27 | 'Редактирование правила' => 'Edit Permission', 28 | 'Редактирование роли: ' => 'Edit Role', 29 | 'Редактирование' => 'Editing', 30 | 'Управление ролями пользователя' => 'Manage user Roles', 31 | 'Разрешенные доступы' => 'Permissions', 32 | '* только латинские буквы, цифры и _ -' => '* only letters, numbers and _ -', 33 | ]; 34 | -------------------------------------------------------------------------------- /messages/pt-BR/db_rbac.php: -------------------------------------------------------------------------------- 1 | 'Regra com esse nome já existe', 4 | 'Разрешение с таким именем уже существует' => 'Permissão com o esse nome já existe', 5 | 'Значение "{field}" содержит недопустимые символы' => 'Valor "{field}" possui caracteres inválidos', 6 | 'Страница не найдена' => 'Pagina não encontrada', 7 | 'Недостаточно прав' => 'Você não possui permissão de acesso', 8 | 'Необходимо указать класс User в настройках модуля' => 'Parametros de UserClass precisam estar especificados no arquivo de configuração', 9 | 'UserClass должен реализовывать интерфейс developeruz\db_rbac\UserRbacInterface' => 'UserClass deve implementar de developeruz\db_rbac\UserRbacInterface', 10 | 'Пользователь не найден' => 'Usuário não encontrado', 11 | 'Новое правило' => 'Adicionar Permissão', 12 | 'Правила доступа' => 'Permissões', 13 | 'Текстовое описание' => 'Descrição', 14 | 'Разрешенный доступ' => 'Permitir Acesso', 15 | '
* Формат: module/controller/action
site/article - доступ к странице "site/article"
site - доступ к любым action контроллера "site"' => 16 | '
* Formato: module/controller/action
site/article - acessa a pagina "site/article"
site - acessa qualquer action no controller "site"', 17 | 'Сохранить' => 'Gravar', 18 | 'Новая роль' => 'Adicionar Regra', 19 | 'Управление ролями' => 'Regras', 20 | 'Название роли' => 'Título para regra', 21 | 'Добавить новое правило' => 'Adicionar Permissão', 22 | 'Правило' => 'Permissão', 23 | 'Описание' => 'Descrição', 24 | 'Добавить роль' => 'Adicionar Função', 25 | 'Роль' => 'Função', 26 | 'Редактирование правила: ' => 'Alterar Permissão', 27 | 'Редактирование правила' => 'Alterar Permissão', 28 | 'Редактирование роли: ' => 'Alterar Função', 29 | 'Редактирование' => 'Alteração', 30 | 'Управление ролями пользователя' => 'Gerenciar Regras de Usuários', 31 | 'Разрешенные доступы' => 'Permissões', 32 | '* только латинские буквы, цифры и _ -' => '* apenas letras, numeros e _ -', 33 | ]; 34 | -------------------------------------------------------------------------------- /views/access/addPermission.php: -------------------------------------------------------------------------------- 1 | title = Yii::t('db_rbac', 'Новое правило'); 12 | $this->params['breadcrumbs'][] = ['label' => Yii::t('db_rbac', 'Правила доступа'), 'url' => ['permission']]; 13 | $this->params['breadcrumbs'][] = Yii::t('db_rbac', 'Новое правило'); 14 | ?> 15 |
16 | 17 |

title) ?>

18 | 19 | 52 |
53 | -------------------------------------------------------------------------------- /views/access/addRole.php: -------------------------------------------------------------------------------- 1 | title = Yii::t('db_rbac', 'Новая роль'); 13 | $this->params['breadcrumbs'][] = ['label' => Yii::t('db_rbac', 'Управление ролями'), 'url' => ['role']]; 14 | $this->params['breadcrumbs'][] = Yii::t('db_rbac', 'Новая роль'); 15 | ?> 16 |
17 | 18 |

title) ?>

19 | 20 | 57 |
-------------------------------------------------------------------------------- /views/access/permission.php: -------------------------------------------------------------------------------- 1 | title = Yii::t('db_rbac', 'Правила доступа'); 12 | $this->params['breadcrumbs'][] = $this->title; 13 | ?> 14 |
15 | 16 |

title) ?>

17 | 18 |

19 | 'btn btn-success']) ?> 20 |

21 | Yii::$app->authManager->getPermissions(), 24 | 'sort' => [ 25 | 'attributes' => ['name', 'description'], 26 | ], 27 | 'pagination' => [ 28 | 'pageSize' => 10, 29 | ], 30 | ]); 31 | ?> 32 | 33 | $dataProvider, 35 | 'columns' => [ 36 | ['class' => 'yii\grid\SerialColumn'], 37 | [ 38 | 'class' => DataColumn::className(), 39 | 'attribute' => 'name', 40 | 'label' => Yii::t('db_rbac', 'Правило') 41 | ], 42 | [ 43 | 'class' => DataColumn::className(), 44 | 'attribute' => 'description', 45 | 'label' => Yii::t('db_rbac', 'Описание') 46 | ], 47 | ['class' => 'yii\grid\ActionColumn', 48 | 'template' => '{update} {delete}', 49 | 'buttons' => 50 | [ 51 | 'update' => function ($url, $model) { 52 | return Html::a('', Url::toRoute(['update-permission', 'name' => $model->name]), [ 53 | 'title' => Yii::t('yii', 'Update'), 54 | 'data-pjax' => '0', 55 | ]); }, 56 | 'delete' => function ($url, $model) { 57 | return Html::a('', Url::toRoute(['delete-permission','name' => $model->name]), [ 58 | 'title' => Yii::t('yii', 'Delete'), 59 | 'data-confirm' => Yii::t('yii', 'Are you sure you want to delete this item?'), 60 | 'data-method' => 'post', 61 | 'data-pjax' => '0', 62 | ]); 63 | } 64 | ] 65 | ], 66 | ] 67 | ]); 68 | ?> 69 |
-------------------------------------------------------------------------------- /views/access/role.php: -------------------------------------------------------------------------------- 1 | title = Yii::t('db_rbac', 'Управление ролями'); 13 | $this->params['breadcrumbs'][] = $this->title; 14 | ?> 15 |
16 | 17 |

title) ?>

18 | 19 |

20 | 'btn btn-success']) ?> 21 |

22 | Yii::$app->authManager->getRoles(), 25 | 'sort' => [ 26 | 'attributes' => ['name', 'description'], 27 | ], 28 | 'pagination' => [ 29 | 'pageSize' => 10, 30 | ], 31 | ]); 32 | ?> 33 | 34 | $dataProvider, 36 | 'columns' => [ 37 | ['class' => 'yii\grid\SerialColumn'], 38 | [ 39 | 'class' => DataColumn::className(), 40 | 'attribute' => 'name', 41 | 'label' => Yii::t('db_rbac', 'Роль') 42 | ], 43 | [ 44 | 'class' => DataColumn::className(), 45 | 'attribute' => 'description', 46 | 'label' => Yii::t('db_rbac', 'Описание') 47 | ], 48 | [ 49 | 'class' => DataColumn::className(), 50 | 'label' => Yii::t('db_rbac', 'Разрешенные доступы'), 51 | 'format' => ['html'], 52 | 'value' => function($data) { return implode('
',array_keys(ArrayHelper::map(Yii::$app->authManager->getPermissionsByRole($data->name), 'description', 'description')));} 53 | ], 54 | ['class' => 'yii\grid\ActionColumn', 55 | 'template' => '{update} {delete}', 56 | 'buttons' => 57 | [ 58 | 'update' => function ($url, $model) { 59 | return Html::a('', Url::toRoute(['update-role', 'name' => $model->name]), [ 60 | 'title' => Yii::t('yii', 'Update'), 61 | 'data-pjax' => '0', 62 | ]); }, 63 | 'delete' => function ($url, $model) { 64 | return Html::a('', Url::toRoute(['delete-role','name' => $model->name]), [ 65 | 'title' => Yii::t('yii', 'Delete'), 66 | 'data-confirm' => Yii::t('yii', 'Are you sure you want to delete this item?'), 67 | 'data-method' => 'post', 68 | 'data-pjax' => '0', 69 | ]); 70 | } 71 | ] 72 | ], 73 | ] 74 | ]); 75 | ?> 76 |
-------------------------------------------------------------------------------- /views/access/updatePermission.php: -------------------------------------------------------------------------------- 1 | title = Yii::t('db_rbac', 'Редактирование правила: ') . ' ' . $permit->description; 13 | $this->params['breadcrumbs'][] = ['label' => Yii::t('db_rbac', 'Правила доступа'), 'url' => ['permission']]; 14 | $this->params['breadcrumbs'][] = Yii::t('db_rbac', 'Редактирование правила'); 15 | ?> 16 |
17 | 18 |

title) ?>

19 | 20 | 53 |
-------------------------------------------------------------------------------- /views/access/updateRole.php: -------------------------------------------------------------------------------- 1 | title = Yii::t('db_rbac', 'Редактирование роли: ') . ' ' . $role->name; 9 | $this->params['breadcrumbs'][] = ['label' => Yii::t('db_rbac', 'Управление ролями'), 'url' => ['role']]; 10 | $this->params['breadcrumbs'][] = Yii::t('db_rbac', 'Редактирование'); 11 | ?> 12 |
13 | 14 |

title) ?>

15 | 16 | 54 |
55 | -------------------------------------------------------------------------------- /views/user/view.php: -------------------------------------------------------------------------------- 1 | 9 |

getUserName(); ?>

10 | ["update", 'id' => $user->getId()]]); ?> 11 | 12 | '
']); ?> 13 | 14 |
15 | 'btn btn-success']) ?> 16 |
17 | 18 | 19 | 20 | --------------------------------------------------------------------------------