/** * Get assigned routes of user. * @param integer $userId * @return array */ public static function getRoutesByUser($userId) { if (!isset(self::$_userRoutes[$userId])) { $cache = Configs::cache(); if ($cache && ($routes = $cache->get([__METHOD__, $userId])) !== false) { self::$_userRoutes[$userId] = $routes; } else { $routes = static::getDefaultRoutes(); $manager = Configs::authManager(); foreach ($manager->getPermissionsByUser($userId) as $item) { if ($item->name[0] === '/') { $routes[$item->name] = true; } } self::$_userRoutes[$userId] = $routes; if ($cache) { $cache->set([__METHOD__, $userId], $routes, Configs::cacheDuration(), new TagDependency(['tags' => Configs::CACHE_TAG])); } } } return self::$_userRoutes[$userId]; }
/** * Search authitem * @param array $params * @return \yii\data\ActiveDataProvider|\yii\data\ArrayDataProvider */ public function search($params) { /* @var \yii\rbac\Manager $authManager */ $authManager = Configs::authManager(); if ($this->type == Item::TYPE_ROLE) { $items = $authManager->getRoles(); } else { $items = array_filter($authManager->getPermissions(), function ($item) { return $this->type == Item::TYPE_PERMISSION xor strncmp($item->name, '/', 1) === 0; }); } $this->load($params); if ($this->validate()) { $search = mb_strtolower(trim($this->name)); $desc = mb_strtolower(trim($this->description)); $ruleName = $this->ruleName; foreach ($items as $name => $item) { $f = (empty($search) || mb_strpos(mb_strtolower($item->name), $search) !== false) && (empty($desc) || mb_strpos(mb_strtolower($item->description), $desc) !== false) && (empty($ruleName) || $item->ruleName == $ruleName); if (!$f) { unset($items[$name]); } } } return new ArrayDataProvider(['allModels' => $items]); }
/** * Search BizRule * @param array $params * @return \yii\data\ActiveDataProvider|\yii\data\ArrayDataProvider */ public function search($params) { /* @var \yii\rbac\Manager $authManager */ $authManager = Configs::authManager(); $models = []; $included = !($this->load($params) && $this->validate() && trim($this->name) !== ''); foreach ($authManager->getRules() as $name => $item) { if ($name != RouteRule::RULE_NAME && ($included || stripos($item->name, $this->name) !== false)) { $models[$name] = new MBizRule($item); } } return new ArrayDataProvider(['allModels' => $models]); }
/** * Get all available and assigned roles/permission * @return array */ public function getItems() { $manager = Configs::authManager(); $available = []; foreach (array_keys($manager->getRoles()) as $name) { $available[$name] = 'role'; } foreach (array_keys($manager->getPermissions()) as $name) { if ($name[0] != '/') { $available[$name] = 'permission'; } } $assigned = []; foreach ($manager->getAssignments($this->id) as $item) { $assigned[$item->roleName] = $available[$item->roleName]; unset($available[$item->roleName]); } return ['available' => $available, 'assigned' => $assigned]; }
/** * Get saved routes. * @return array */ public static function getSavedRoutes() { if (self::$_routes === null) { self::$_routes = []; foreach (Configs::authManager()->getPermissions() as $name => $value) { if ($name[0] === '/' && substr($name, -1) != '*') { self::$_routes[] = $name; } } } return self::$_routes; }
<?php use yii\helpers\Html; use yii\grid\GridView; use mdm\admin\components\RouteRule; use mdm\admin\components\Configs; /* @var $this yii\web\View */ /* @var $dataProvider yii\data\ActiveDataProvider */ /* @var $searchModel mdm\admin\models\searchs\AuthItem */ /* @var $context mdm\admin\components\ItemController */ $context = $this->context; $labels = $context->labels(); $this->title = Yii::t('rbac-admin', $labels['Items']); $this->params['breadcrumbs'][] = $this->title; $rules = array_keys(Configs::authManager()->getRules()); $rules = array_combine($rules, $rules); unset($rules[RouteRule::RULE_NAME]); ?> <div class="role-index"> <h1><?php echo Html::encode($this->title); ?> </h1> <p> <?php echo Html::a(Yii::t('rbac-admin', 'Create ' . $labels['Item']), ['create'], ['class' => 'btn btn-success']); ?> </p> <?php echo GridView::widget(['dataProvider' => $dataProvider, 'filterModel' => $searchModel, 'columns' => [['class' => 'yii\\grid\\SerialColumn'], ['attribute' => 'name', 'label' => Yii::t('rbac-admin', 'Name')], ['attribute' => 'ruleName', 'label' => Yii::t('rbac-admin', 'Rule Name'), 'filter' => $rules], ['attribute' => 'description', 'label' => Yii::t('rbac-admin', 'Description')], ['class' => 'yii\\grid\\ActionColumn']]]); ?>
/** * Get items * @return array */ public function getItems() { $manager = Configs::authManager(); $avaliable = []; if ($this->type == Item::TYPE_ROLE) { foreach (array_keys($manager->getRoles()) as $name) { $avaliable[$name] = 'role'; } } foreach (array_keys($manager->getPermissions()) as $name) { $avaliable[$name] = $name[0] == '/' ? 'route' : 'permission'; } $assigned = []; foreach ($manager->getChildren($this->_item->name) as $item) { $assigned[$item->name] = $item->type == 1 ? 'role' : ($item->name[0] == '/' ? 'route' : 'permission'); unset($avaliable[$item->name]); } unset($avaliable[$this->name]); return ['avaliable' => $avaliable, 'assigned' => $assigned]; }
/** * Save model to authManager * @return boolean */ public function save() { if ($this->validate()) { $manager = Configs::authManager(); $class = $this->className; if ($this->_item === null) { $this->_item = new $class(); $isNew = true; } else { $isNew = false; $oldName = $this->_item->name; } $this->_item->name = $this->name; if ($isNew) { $manager->add($this->_item); } else { $manager->update($oldName, $this->_item); } return true; } else { return false; } }
/** * Finds the AuthItem model based on its primary key value. * If the model is not found, a 404 HTTP exception will be thrown. * @param string $id * @return AuthItem the loaded model * @throws HttpException if the model cannot be found */ protected function findModel($id) { $item = Configs::authManager()->getRule($id); if ($item) { return new BizRule($item); } else { throw new NotFoundHttpException('The requested page does not exist.'); } }
/** * Set default rule of parameterize route. */ protected function setDefaultRule() { if (Configs::authManager()->getRule(RouteRule::RULE_NAME) === null) { Configs::authManager()->add(new RouteRule()); } }
/** * Use to get assigned menu of user. * @param mixed $userId * @param integer $root * @param \Closure $callback use to reformat output. * callback should have format like * * ``` * function ($menu) { * return [ * 'label' => $menu['name'], * 'url' => [$menu['route']], * 'options' => $data, * 'items' => $menu['children'] * ] * ] * } * ``` * @param boolean $refresh * @return array */ public static function getAssignedMenu($userId, $root = null, $callback = null, $refresh = false) { $config = Configs::instance(); /* @var $manager \yii\rbac\BaseManager */ $manager = Configs::authManager(); $menus = Menu::find()->asArray()->indexBy('id')->all(); $key = [__METHOD__, $userId, $manager->defaultRoles]; $cache = $config->cache; if ($refresh || $cache === null || ($assigned = $cache->get($key)) === false) { $routes = $filter1 = $filter2 = []; if ($userId !== null) { foreach ($manager->getPermissionsByUser($userId) as $name => $value) { if ($name[0] === '/') { if (substr($name, -2) === '/*') { $name = substr($name, 0, -1); } $routes[] = $name; } } } foreach ($manager->defaultRoles as $role) { foreach ($manager->getPermissionsByRole($role) as $name => $value) { if ($name[0] === '/') { if (substr($name, -2) === '/*') { $name = substr($name, 0, -1); } $routes[] = $name; } } } $routes = array_unique($routes); sort($routes); $prefix = '\\'; foreach ($routes as $route) { if (strpos($route, $prefix) !== 0) { if (substr($route, -1) === '/') { $prefix = $route; $filter1[] = $route . '%'; } else { $filter2[] = $route; } } } $assigned = []; $query = Menu::find()->select(['id'])->asArray(); if (count($filter2)) { $assigned = $query->where(['route' => $filter2])->column(); } if (count($filter1)) { $query->where('route like :filter'); foreach ($filter1 as $filter) { $assigned = array_merge($assigned, $query->params([':filter' => $filter])->column()); } } $assigned = static::requiredParent($assigned, $menus); if ($cache !== null) { $cache->set($key, $assigned, $config->cacheDuration, new TagDependency(['tags' => Configs::CACHE_TAG])); } } $key = [__METHOD__, $assigned, $root]; if ($refresh || $callback !== null || $cache === null || ($result = $cache->get($key)) === false) { $result = static::normalizeMenu($assigned, $menus, $callback, $root); if ($cache !== null && $callback === null) { $cache->set($key, $result, $config->cacheDuration, new TagDependency(['tags' => Configs::CACHE_TAG])); } } return $result; }
<?php use yii\helpers\Html; use yii\widgets\ActiveForm; use mdm\admin\components\RouteRule; use mdm\admin\AutocompleteAsset; use yii\helpers\Json; use mdm\admin\components\Configs; /* @var $this yii\web\View */ /* @var $model mdm\admin\models\AuthItem */ /* @var $form yii\widgets\ActiveForm */ /* @var $context mdm\admin\components\ItemController */ $context = $this->context; $labels = $context->labels(); $rules = Configs::authManager()->getRules(); unset($rules[RouteRule::RULE_NAME]); $source = Json::htmlEncode(array_keys($rules)); $js = <<<JS \$('#rule_name').autocomplete({ source: {$source}, }); JS; AutocompleteAsset::register($this); $this->registerJs($js); ?> <div class="auth-item-form"> <?php $form = ActiveForm::begin(['id' => 'item-form']); ?> <div class="row">
/** * Finds the AuthItem model based on its primary key value. * If the model is not found, a 404 HTTP exception will be thrown. * @param string $id * @return AuthItem the loaded model * @throws NotFoundHttpException if the model cannot be found */ protected function findModel($id) { $auth = Configs::authManager(); $item = $this->type === Item::TYPE_ROLE ? $auth->getRole($id) : $auth->getPermission($id); if ($item) { return new AuthItem($item); } else { throw new NotFoundHttpException('The requested page does not exist.'); } }