diff --git a/backend/config/main.php b/backend/config/main.php index 3ea1918..5520950 100644 --- a/backend/config/main.php +++ b/backend/config/main.php @@ -16,7 +16,7 @@ return [ 'bootstrap' => ['log'], 'modules' => [ 'permit' => [ - 'class' => 'developeruz\db_rbac\Yii2DbRbac', + 'class' => 'common\components\developeruz\db_rbac\Yii2DbRbac', 'params' => [ 'userClass' => 'common\models\User' ] diff --git a/common/components/developeruz/db_rbac/LICENSE b/common/components/developeruz/db_rbac/LICENSE new file mode 100644 index 0000000..bc2f342 --- /dev/null +++ b/common/components/developeruz/db_rbac/LICENSE @@ -0,0 +1,22 @@ +The MIT License (MIT) + +Copyright (c) 2014 Elvira Sheina + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + diff --git a/common/components/developeruz/db_rbac/README.md b/common/components/developeruz/db_rbac/README.md new file mode 100644 index 0000000..5cb0a09 --- /dev/null +++ b/common/components/developeruz/db_rbac/README.md @@ -0,0 +1,169 @@ +Динамическая настройка прав доступа для Yii2 +============ + +Модуль для создания ролей и прав доступа через веб-интерфейс, так же имеющий веб интерфейс для назначения ролей пользователям +Поведение для приложения, проверяющее право доступа к action по внесенным в модуле правилам. + +###Установка:### +```bash +$ php composer.phar require developeruz/yii2-db-rbac "*" +``` + +Для корректной работы модуля необходимо настроить authManager в конфиге приложения (common/config/main.php для advanced или config/web.php и config/console для basic приложения) +```php + 'components' => [ + 'authManager' => [ + 'class' => 'yii\rbac\DbManager', + ], + ... + ] +``` + +И выполнить миграции, создающие таблицы для DbManager (подразумевается, что коннект к БД для приложения уже настроен) +```bash +$ yii migrate --migrationPath=@yii/rbac/migrations/ +``` + +##Подключение модуля## +В конфиге приложения (backend/config/main.php для advanced или config/web.php для basic приложения) прописываем модуль +```php + 'modules' => [ + 'permit' => [ + 'class' => 'developeruz\db_rbac\Yii2DbRbac', + ], + ], +``` +Если нужно передать layout это можно сделать так: +```php + 'modules' => [ + 'permit' => [ + 'class' => 'developeruz\db_rbac\Yii2DbRbac', + 'layout' => '//admin' + ], + ], +``` + +Если вы используете ЧПУ, то убедитесь что у вас прописаны правила роутинга для модулей +```php +'//' => '//', +'///' => '//', +``` + +**Добавляем ссылки в меню** + +**/permit/access/role - управление ролями** + +**/permit/access/permission - управление правами доступа** + +###Назначение ролей пользователям### +По многочисленным просьбам в модуль добавлен интерфейс для назначения ролей пользователям. + +Для корректной работы модуля нужно указать в параметрах модуля класс `User`. +```php +'modules' => [ + 'permit' => [ + 'class' => 'app\modules\db_rbac\Yii2DbRbac', + 'params' => [ + 'userClass' => 'app\models\User' + ] + ], + ], +``` + +Класс User должен реализовывать интерфейс `developeruz\db_rbac\interfaces\UserRbacInterface`. +В большинстве случаев придется дописать в нем 1 функцию `getUserName()` которая будет возвращать отображаемое имя пользователя. +```php +use developeruz\db_rbac\interfaces\UserRbacInterface; + +class User extends ActiveRecord implements IdentityInterface, UserRbacInterface +{ +... + public function getUserName() + { + return $this->username; + } +} +``` + +**Управление ролью пользователя происходит на странице `/permit/user/view/1` для пользователя с id=1.** +Удобнее всего дописать кнопку на эту страницу в Grid со списком пользователей. +```php +echo GridView::widget([ + 'dataProvider' => $dataProvider, + 'columns' => [ + ['class' => 'yii\grid\SerialColumn'], + + 'id', + 'username', + 'email:email', + + ['class' => 'yii\grid\ActionColumn', + 'template' => '{view}  {update}  {permit}  {delete}', + 'buttons' => + [ + 'permit' => function ($url, $model) { + return Html::a('', Url::to(['/permit/user/view', 'id' => $model->id]), [ + 'title' => Yii::t('yii', 'Change user role') + ]); }, + ] + ], + ], +]); +``` + +Присвоить роль пользователю можно и в коде, например при создании нового пользователя. +```php +$userRole = Yii::$app->authManager->getRole('name_of_role'); +Yii::$app->authManager->assign($userRole, $user->getId()); +``` + +Проверить, имеет ли пользователь право на действие можно через метод `can()` компонента User +```php +Yii::$app->user->can($permissionName); +``` +$permissionName - может быть как ролью так и правом + +##Поведение, динамически проверяющее наличие прав## + +Данное поведение позволяет не писать Yii::$app->user->can($permissionName); в каждом action, а проверять права доступа на лету. +Это удобно для гибкой настройки прав при использовании сторонних модулей. + +###Подключение поведения### +В конфиге того приложения, доступ к которому следует проверять на лету, необходимо подключить поведение +```php +use developeruz\db_rbac\behaviors\AccessBehavior; + + 'as AccessBehavior' => [ + 'class' => AccessBehavior::className(), + ] +``` +С этого момента, после обработки запроса (событие EVENT_AFTER_REQUEST) проверяются права текущего пользователя (Yii::$app->user) на выполнение запрашиваемого действия (Yii::$app->user->can()) +Действие считается разрешенным, если: + - пользователю разрешен доступ к конкретному action (правило записано как: module/controller/action) + - пользователю разрешен доступ к любым action данного контроллера (правило записано как: module/controller) + - пользователю разрешен доступ к любым action данного модуля (правило записано как: module) + +###Настройка прав доступа по умолчанию### +После подключения поведения, доступ становится возможен только авторизованному пользователю, имеющему некие права. +Для исключений из этого правила можно прописать доступы по умолчанию в том же формате AccessControl, что и в контроллере: +```php + 'as AccessBehavior' => [ + 'class' => AccessBehavior::className(), + 'rules' => + ['site' => + [ + [ + 'actions' => ['login', 'index'], + 'allow' => true, + ], + [ + 'actions' => ['about'], + 'allow' => true, + 'roles' => ['admin'], + ], + ] + ] + ] +``` +В приведенном выше примере разрешен доступ любому пользователю к site/login и site/index и доступ пользователя с ролью admin к site/about +Правила прописанные в конфиге имеют приоритет над динамически настраиваемыми правилами. \ No newline at end of file diff --git a/common/components/developeruz/db_rbac/Yii2DbRbac.php b/common/components/developeruz/db_rbac/Yii2DbRbac.php new file mode 100644 index 0000000..a3dba7b --- /dev/null +++ b/common/components/developeruz/db_rbac/Yii2DbRbac.php @@ -0,0 +1,38 @@ + + * @version 0.1 + * @package Yii2DbRbac for Yii2 + * + */ +namespace common\components\developeruz\db_rbac; + +use Yii; + +class Yii2DbRbac extends \yii\base\Module +{ + public $controllerNamespace = 'common\components\developeruz\db_rbac\controllers'; + public $userClass; + + public function init() + { + parent::init(); + $this->registerTranslations(); + } + + public function registerTranslations() + { + Yii::$app->i18n->translations['db_rbac'] = [ + 'class' => 'yii\i18n\PhpMessageSource', + 'sourceLanguage' => 'ru-Ru', + 'basePath' => '@developeruz/db_rbac/messages', + ]; + } + + public static function t($category, $message, $params = [], $language = null) + { + return Yii::t('modules/db_rbac/' . $category, $message, $params, $language); + } +} diff --git a/common/components/developeruz/db_rbac/behaviors/AccessBehavior.php b/common/components/developeruz/db_rbac/behaviors/AccessBehavior.php new file mode 100644 index 0000000..1489e4a --- /dev/null +++ b/common/components/developeruz/db_rbac/behaviors/AccessBehavior.php @@ -0,0 +1,103 @@ + + * @version 0.1 + * @package AccessBehavior for Yii2 + * + */ +namespace developeruz\db_rbac\behaviors; + +use Yii; +use yii\behaviors\AttributeBehavior; +use yii\di\Instance; +use yii\base\Module; +use yii\web\Application; +use yii\web\User; +use yii\filters\AccessControl; +use yii\web\ForbiddenHttpException; + +class AccessBehavior extends AttributeBehavior { + + public $rules=[]; + + private $_rules = []; + + public function events() + { + return [ + Module::EVENT_BEFORE_ACTION => 'interception', + ]; + } + + public function interception($event) + { + if(!isset( Yii::$app->i18n->translations['db_rbac'])){ + Yii::$app->i18n->translations['db_rbac'] = [ + 'class' => 'yii\i18n\PhpMessageSource', + 'sourceLanguage' => 'ru-Ru', + 'basePath' => '@developeruz/db_rbac/messages', + ]; + } + + $route = Yii::$app->getRequest()->resolve(); + + //Проверяем права по конфигу + $this->createRule(); + $user = Instance::ensure(Yii::$app->user, User::className()); + $request = Yii::$app->getRequest(); + $action = $event->action; + + if(!$this->cheсkByRule($action, $user, $request)) + { + //И по AuthManager + if(!$this->checkPermission($route)) + throw new ForbiddenHttpException(Yii::t('db_rbac','Недостаточно прав')); + } + } + + protected function createRule() + { + foreach($this->rules as $controller => $rule) + { + foreach ($rule as $singleRule) { + if (is_array($singleRule)) { + $option = [ + 'controllers' => [$controller], + 'class' => 'yii\filters\AccessRule' + ]; + $this->_rules[] = Yii::createObject(array_merge($option, $singleRule)); + } + } + } + } + + protected function cheсkByRule($action, $user, $request) + { + foreach ($this->_rules as $rule) { + if ($rule->allows($action, $user, $request)) + return true; + } + return false; + } + + protected function checkPermission($route) + { + //$route[0] - is the route, $route[1] - is the associated parameters + + $routePathTmp = explode('/', $route[0]); + $routeVariant = array_shift($routePathTmp); + if(Yii::$app->user->can($routeVariant, $route[1])) + return true; + + foreach($routePathTmp as $routePart) + { + $routeVariant .= '/'.$routePart; + if(Yii::$app->user->can($routeVariant, $route[1])) + return true; + } + + return false; + } +} \ No newline at end of file diff --git a/common/components/developeruz/db_rbac/composer.json b/common/components/developeruz/db_rbac/composer.json new file mode 100644 index 0000000..20b7fc1 --- /dev/null +++ b/common/components/developeruz/db_rbac/composer.json @@ -0,0 +1,25 @@ +{ + "name": "developeruz/yii2-db-rbac", + "description": "Dynamic control of access rights in YII2", + "keywords": ["yii", "rbac"], + "type": "yii2-extension", + "license": "MIT", + "authors": [ + { + "name": "Elvira Sheina", + "email": "elleuz@gmail.com", + "homepage": "http://developer.uz" + } + ], + "require": { + "yiisoft/yii2": "*" + }, + "support": { + "issues": "https://github.com/developeruz/yii2-db-rbac/issues" + }, + "autoload": { + "psr-4": { + "developeruz\\db_rbac\\": "" + } + } +} \ No newline at end of file diff --git a/common/components/developeruz/db_rbac/controllers/AccessController.php b/common/components/developeruz/db_rbac/controllers/AccessController.php new file mode 100644 index 0000000..0547f26 --- /dev/null +++ b/common/components/developeruz/db_rbac/controllers/AccessController.php @@ -0,0 +1,238 @@ + + * @version 0.1 + * @package AccessController for Yii2 + * + */ +namespace common\components\developeruz\db_rbac\controllers; + +use Yii; +use yii\web\Controller; +use yii\web\BadRequestHttpException; +use yii\rbac\Role; +use yii\rbac\Permission; +use yii\helpers\ArrayHelper; +use yii\helpers\Url; +use yii\validators\RegularExpressionValidator; + +class AccessController extends Controller +{ + protected $error; + protected $pattern4Role = '/^[a-zA-Z0-9_-]+$/'; + protected $pattern4Permission = '/^[a-zA-Z0-9_\/-]+$/'; + + public function actions() + { + return [ + 'error' => [ + 'class' => 'yii\web\ErrorAction', + ], + ]; + } + + public function actionRole() + { + return $this->render('role'); + } + + public function actionAddRole() + { + if (Yii::$app->request->post('name') + && $this->validate(Yii::$app->request->post('name'), $this->pattern4Role) + && $this->isUnique(Yii::$app->request->post('name'), 'role') + ) { + $role = Yii::$app->authManager->createRole(Yii::$app->request->post('name')); + $role->description = Yii::$app->request->post('description'); + Yii::$app->authManager->add($role); + $this->setPermissions(Yii::$app->request->post('permissions', []), $role); + return $this->redirect(Url::toRoute([ + 'update-role', + 'name' => $role->name + ])); + } + + $permissions = ArrayHelper::map(Yii::$app->authManager->getPermissions(), 'name', 'description'); + return $this->render( + 'addRole', + [ + 'permissions' => $permissions, + 'error' => $this->error + ] + ); + } + + public function actionUpdateRole($name) + { + $role = Yii::$app->authManager->getRole($name); + + $permissions = ArrayHelper::map(Yii::$app->authManager->getPermissions(), 'name', 'description'); + $role_permit = array_keys(Yii::$app->authManager->getPermissionsByRole($name)); + + if ($role instanceof Role) { + if (Yii::$app->request->post('name') + && $this->validate(Yii::$app->request->post('name'), $this->pattern4Role) + ) { + if (Yii::$app->request->post('name') != $name && !$this->isUnique(Yii::$app->request->post('name'), 'role')) { + return $this->render( + 'updateRole', + [ + 'role' => $role, + 'permissions' => $permissions, + 'role_permit' => $role_permit, + 'error' => $this->error + ] + ); + } + $role = $this->setAttribute($role, Yii::$app->request->post()); + Yii::$app->authManager->update($name, $role); + Yii::$app->authManager->removeChildren($role); + $this->setPermissions(Yii::$app->request->post('permissions', []), $role); + return $this->redirect(Url::toRoute([ + 'update-role', + 'name' => $role->name + ])); + } + + return $this->render( + 'updateRole', + [ + 'role' => $role, + 'permissions' => $permissions, + 'role_permit' => $role_permit, + 'error' => $this->error + ] + ); + } else { + throw new BadRequestHttpException(Yii::t('db_rbac', 'Страница не найдена')); + } + } + + public function actionDeleteRole($name) + { + $role = Yii::$app->authManager->getRole($name); + if ($role) { + Yii::$app->authManager->removeChildren($role); + Yii::$app->authManager->remove($role); + } + return $this->redirect(Url::toRoute(['role'])); + } + + + public function actionPermission() + { + return $this->render('permission'); + } + + public function actionAddPermission() + { + $permission = $this->clear(Yii::$app->request->post('name')); + if ($permission + && $this->validate($permission, $this->pattern4Permission) + && $this->isUnique($permission, 'permission') + ) { + $permit = Yii::$app->authManager->createPermission($permission); + $permit->description = Yii::$app->request->post('description', ''); + Yii::$app->authManager->add($permit); + return $this->redirect(Url::toRoute([ + 'update-permission', + 'name' => $permit->name + ])); + } + + return $this->render('addPermission', ['error' => $this->error]); + } + + public function actionUpdatePermission($name) + { + $permit = Yii::$app->authManager->getPermission($name); + if ($permit instanceof Permission) { + $permission = $this->clear(Yii::$app->request->post('name')); + if ($permission && $this->validate($permission, $this->pattern4Permission) + ) { + if($permission!= $name && !$this->isUnique($permission, 'permission')) + { + return $this->render('updatePermission', [ + 'permit' => $permit, + 'error' => $this->error + ]); + } + + $permit->name = $permission; + $permit->description = Yii::$app->request->post('description', ''); + Yii::$app->authManager->update($name, $permit); + return $this->redirect(Url::toRoute([ + 'update-permission', + 'name' => $permit->name + ])); + } + + return $this->render('updatePermission', [ + 'permit' => $permit, + 'error' => $this->error + ]); + } else throw new BadRequestHttpException(Yii::t('db_rbac', 'Страница не найдена')); + } + + public function actionDeletePermission($name) + { + $permit = Yii::$app->authManager->getPermission($name); + if ($permit) + Yii::$app->authManager->remove($permit); + return $this->redirect(Url::toRoute(['permission'])); + } + + protected function setAttribute($object, $data) + { + $object->name = $data['name']; + $object->description = $data['description']; + return $object; + } + + protected function setPermissions($permissions, $role) + { + foreach ($permissions as $permit) { + $new_permit = Yii::$app->authManager->getPermission($permit); + Yii::$app->authManager->addChild($role, $new_permit); + } + } + + protected function validate($field, $regex) + { + $validator = new RegularExpressionValidator(['pattern' => $regex]); + if ($validator->validate($field, $error)) + return true; + else { + $this->error[] = Yii::t('db_rbac', 'Значение "{field}" содержит не допустимые символы', ['field' => $field]); + return false; + } + } + + protected function isUnique($name, $type) + { + if ($type == 'role') { + $role = Yii::$app->authManager->getRole($name); + if ($role instanceof Role) { + $this->error[] = Yii::t('db_rbac', 'Роль с таким именем уже существует: ') . $name; + return false; + } else return true; + } elseif ($type == 'permission') { + $permission = Yii::$app->authManager->getPermission($name); + if ($permission instanceof Permission) { + $this->error[] = Yii::t('db_rbac', 'Правило с таким именем уже существует: ') . $name; + return false; + } else return true; + } + } + + protected function clear($value) + { + if (!empty($value)) { + $value = trim($value, "/ \t\n\r\0\x0B"); + } + + return $value; + } +} \ No newline at end of file diff --git a/common/components/developeruz/db_rbac/controllers/UserController.php b/common/components/developeruz/db_rbac/controllers/UserController.php new file mode 100644 index 0000000..c067913 --- /dev/null +++ b/common/components/developeruz/db_rbac/controllers/UserController.php @@ -0,0 +1,100 @@ + + * @version 0.1 + * @package UserController for Yii2 + * + */ +namespace common\components\developeruz\db_rbac\controllers; + +use Yii; +use yii\filters\VerbFilter; +use yii\helpers\ArrayHelper; +use yii\helpers\Url; +use yii\web\Controller; +use yii\web\BadRequestHttpException; +use developeruz\db_rbac\interfaces\UserRbacInterface; +use yii\web\NotFoundHttpException; + +class UserController extends Controller +{ + public $moduleName = 'permit'; + + public function beforeAction($action) + { + if(empty(Yii::$app->controller->module->params['userClass'])){ + throw new BadRequestHttpException(Yii::t('db_rbac','Необходимо указать класс User в настройках модуля')); + } + + $user = new Yii::$app->controller->module->params['userClass'](); + + if(! $user instanceof UserRbacInterface) + { + throw new BadRequestHttpException(Yii::t('db_rbac', 'UserClass должен реализовывать интерфейс developeruz\db_rbac\UserRbacInterface')); + } + + return parent::beforeAction($action); + } + + public function actions() + { + return [ + 'error' => [ + 'class' => 'yii\web\ErrorAction', + ], + ]; + } + + public function behaviors() + { + return [ + 'verbs' => [ + 'class' => VerbFilter::className(), + 'actions' => [ + 'update' => ['post'], + '*' => ['get'], + ], + ], + ]; + } + + public function actionView($id) + { + $roles = ArrayHelper::map(Yii::$app->authManager->getRoles(), 'name', 'description'); + $user_permit = array_keys(Yii::$app->authManager->getRolesByUser($id)); + $user = $this->findUser($id); + return $this->render('view', [ + 'user' => $user, + 'roles' => $roles, + 'user_permit' => $user_permit, + 'moduleName' => Yii::$app->controller->module->id + ]); + } + + public function actionUpdate($id) + { + $user = $this->findUser($id); + Yii::$app->authManager->revokeAll($user->getId()); + if(Yii::$app->request->post('roles')){ + foreach(Yii::$app->request->post('roles') as $role) + { + $new_role = Yii::$app->authManager->getRole($role); + Yii::$app->authManager->assign($new_role, $user->getId()); + } + } + return $this->redirect(Url::to(["/".Yii::$app->controller->module->id."/user/view", 'id' => $user->getId()])); + } + + private function findUser($id) + { + $class = new Yii::$app->controller->module->params['userClass'](); + $user = $class::findIdentity($id); + if(empty($user)){ + throw new NotFoundHttpException(Yii::t('db_rbac', 'Пользователь не найден')); + } else { + return $user; + } + } +} \ No newline at end of file diff --git a/common/components/developeruz/db_rbac/interfaces/UserRbacInterface.php b/common/components/developeruz/db_rbac/interfaces/UserRbacInterface.php new file mode 100644 index 0000000..d19bf2e --- /dev/null +++ b/common/components/developeruz/db_rbac/interfaces/UserRbacInterface.php @@ -0,0 +1,10 @@ + 'Permission with the same name already exists: ', + 'Роль с таким именем уже существует: ' => 'Role with the same name already exists: ', + 'Значение "{field}" содержит недопустимые символы' => '"{field}" value contains invalid characters', + 'Страница не найдена' => 'Page not found', + 'Недостаточно прав' => 'You not allow to access', + 'Необходимо указать класс User в настройках модуля' => 'UserClass params must be set in config file', + 'UserClass должен реализовывать интерфейс developeruz\db_rbac\UserRbacInterface' => 'UserClass must implements developeruz\db_rbac\UserRbacInterface', + 'Пользователь не найден' => 'User not found' +]; diff --git a/common/components/developeruz/db_rbac/views/access/addPermission.php b/common/components/developeruz/db_rbac/views/access/addPermission.php new file mode 100644 index 0000000..7f79870 --- /dev/null +++ b/common/components/developeruz/db_rbac/views/access/addPermission.php @@ -0,0 +1,55 @@ +title = Yii::t('db_rbac', 'Новое правило'); +$this->params['breadcrumbs'][] = ['label' => Yii::t('db_rbac', 'Правила доступа'), 'url' => ['permission']]; +$this->params['breadcrumbs'][] = Yii::t('db_rbac', 'Новое правило'); +?> +
+ +

title) ?>

+ + +
diff --git a/common/components/developeruz/db_rbac/views/access/addRole.php b/common/components/developeruz/db_rbac/views/access/addRole.php new file mode 100644 index 0000000..4730c0f --- /dev/null +++ b/common/components/developeruz/db_rbac/views/access/addRole.php @@ -0,0 +1,57 @@ +title = Yii::t('db_rbac', 'Новая роль'); +$this->params['breadcrumbs'][] = ['label' => Yii::t('db_rbac', 'Управление ролями'), 'url' => ['role']]; +$this->params['breadcrumbs'][] = 'Новая роль'; +?> +
+ +

title) ?>

+ + +
\ No newline at end of file diff --git a/common/components/developeruz/db_rbac/views/access/permission.php b/common/components/developeruz/db_rbac/views/access/permission.php new file mode 100644 index 0000000..664badd --- /dev/null +++ b/common/components/developeruz/db_rbac/views/access/permission.php @@ -0,0 +1,69 @@ +title = Yii::t('db_rbac', 'Правила доступа'); +$this->params['breadcrumbs'][] = $this->title; +?> +
+ +

title) ?>

+ +

+ 'btn btn-success']) ?> +

+ Yii::$app->authManager->getPermissions(), + 'sort' => [ + 'attributes' => ['name', 'description'], + ], + 'pagination' => [ + 'pageSize' => 10, + ], + ]); +?> + + $dataProvider, + 'columns' => [ + ['class' => 'yii\grid\SerialColumn'], + [ + 'class' => DataColumn::className(), + 'attribute' => 'name', + 'label' => Yii::t('db_rbac', 'Правило') + ], + [ + 'class' => DataColumn::className(), + 'attribute' => 'description', + 'label' => Yii::t('db_rbac', 'Описание') + ], + ['class' => 'yii\grid\ActionColumn', + 'template' => '{update} {delete}', + 'buttons' => + [ + 'update' => function ($url, $model) { + return Html::a('', Url::toRoute(['update-permission', 'name' => $model->name]), [ + 'title' => Yii::t('yii', 'Update'), + 'data-pjax' => '0', + ]); }, + 'delete' => function ($url, $model) { + return Html::a('', Url::toRoute(['delete-permission','name' => $model->name]), [ + 'title' => Yii::t('yii', 'Delete'), + 'data-confirm' => Yii::t('yii', 'Are you sure you want to delete this item?'), + 'data-method' => 'post', + 'data-pjax' => '0', + ]); + } + ] + ], + ] + ]); +?> +
\ No newline at end of file diff --git a/common/components/developeruz/db_rbac/views/access/role.php b/common/components/developeruz/db_rbac/views/access/role.php new file mode 100644 index 0000000..f5bef67 --- /dev/null +++ b/common/components/developeruz/db_rbac/views/access/role.php @@ -0,0 +1,76 @@ +title = Yii::t('db_rbac', 'Управление ролями'); +$this->params['breadcrumbs'][] = $this->title; +?> +
+ +

title) ?>

+ +

+ 'btn btn-success']) ?> +

+ Yii::$app->authManager->getRoles(), + 'sort' => [ + 'attributes' => ['name', 'description'], + ], + 'pagination' => [ + 'pageSize' => 10, + ], + ]); +?> + + $dataProvider, + 'columns' => [ + ['class' => 'yii\grid\SerialColumn'], + [ + 'class' => DataColumn::className(), + 'attribute' => 'name', + 'label' => Yii::t('db_rbac', 'Роль') + ], + [ + 'class' => DataColumn::className(), + 'attribute' => 'description', + 'label' => Yii::t('db_rbac', 'Описание') + ], + [ + 'class' => DataColumn::className(), + 'label' => Yii::t('db_rbac', 'Разрешенные доступы'), + 'format' => ['html'], + 'value' => function($data) { return implode('
',array_keys(ArrayHelper::map(Yii::$app->authManager->getPermissionsByRole($data->name), 'description', 'description')));} + ], + ['class' => 'yii\grid\ActionColumn', + 'template' => '{update} {delete}', + 'buttons' => + [ + 'update' => function ($url, $model) { + return Html::a('', Url::toRoute(['update-role', 'name' => $model->name]), [ + 'title' => Yii::t('yii', 'Update'), + 'data-pjax' => '0', + ]); }, + 'delete' => function ($url, $model) { + return Html::a('', Url::toRoute(['delete-role','name' => $model->name]), [ + 'title' => Yii::t('yii', 'Delete'), + 'data-confirm' => Yii::t('yii', 'Are you sure you want to delete this item?'), + 'data-method' => 'post', + 'data-pjax' => '0', + ]); + } + ] + ], + ] + ]); +?> +
\ No newline at end of file diff --git a/common/components/developeruz/db_rbac/views/access/updatePermission.php b/common/components/developeruz/db_rbac/views/access/updatePermission.php new file mode 100644 index 0000000..076275a --- /dev/null +++ b/common/components/developeruz/db_rbac/views/access/updatePermission.php @@ -0,0 +1,53 @@ +title = Yii::t('db_rbac', 'Редактирование правила: ') . ' ' . $permit->description; +$this->params['breadcrumbs'][] = ['label' => Yii::t('db_rbac', 'Правила доступа'), 'url' => ['permission']]; +$this->params['breadcrumbs'][] = Yii::t('db_rbac', 'Редактирование правила'); +?> +
+ +

title) ?>

+ + +
\ No newline at end of file diff --git a/common/components/developeruz/db_rbac/views/access/updateRole.php b/common/components/developeruz/db_rbac/views/access/updateRole.php new file mode 100644 index 0000000..e8bb002 --- /dev/null +++ b/common/components/developeruz/db_rbac/views/access/updateRole.php @@ -0,0 +1,54 @@ +title = Yii::t('db_rbac', 'Редактирование роли: ') . ' ' . $role->name; +$this->params['breadcrumbs'][] = ['label' => Yii::t('db_rbac', 'Управление ролями'), 'url' => ['role']]; +$this->params['breadcrumbs'][] = Yii::t('db_rbac', 'Редактирование'); +?> +
+ +

title) ?>

+ + +
diff --git a/common/components/developeruz/db_rbac/views/user/view.php b/common/components/developeruz/db_rbac/views/user/view.php new file mode 100644 index 0000000..f88ebf2 --- /dev/null +++ b/common/components/developeruz/db_rbac/views/user/view.php @@ -0,0 +1,19 @@ + +

getUserName(); ?>

+ ["/{$moduleName}/user/update", 'id' => $user->getId()]]); ?> + + '
']); ?> + +
+ 'btn btn-success']) ?> +
+ + + diff --git a/common/config/main.php b/common/config/main.php index 5665391..4c071ec 100644 --- a/common/config/main.php +++ b/common/config/main.php @@ -2,8 +2,8 @@ return [ 'vendorPath' => dirname(dirname(__DIR__)) . '/vendor', 'modules' => [ - 'permit' => [ - 'class' => 'app\modules\db_rbac\Yii2DbRbac', + 'permit' => [ + 'class' => 'common\components\developeruz\db_rbac\Yii2DbRbac', 'params' => [ 'userClass' => 'common\models\User' ] -- libgit2 0.21.4