public function actionDelete($authItemName) { $authItemName = trim($authItemName); if ($authItemName == '') { return $this->result = errorHandler()->logException(null, -1, 'XUSER_ERR_ROLE_NAME_EMPTY', array('message' => 'Role name is empty')); } $authItem = AuthItem::model()->find('name=:name', array(':name' => $authItemName)); if (!is_object($authItem)) { return $this->result = errorHandler()->logException(null, -1, 'XUSER_ERR_ROLE_NOT_FOUND', array('message' => 'Role is not found')); } // check if this role is system role if ($authItem->is_system == true) { return $this->result = errorHandler()->logException(null, -1, 'XUSER_ERR_ROLE_CANNOT_DELETE_BECAUSE_SYSTEM', array('message' => 'Cannot delete this role as it is a system role')); } // check if this role is assigned to any user $sql = 'SELECT COUNT(userid) FROM "' . SITE_ID . '_authassignment" WHERE itemname = \'' . $authItem->name . '\''; $count = app()->db->createCommand($sql)->queryScalar(); if ($count > 0) { return $this->result = errorHandler()->logException(null, -1, 'XUSER_ERR_ROLE_CANNOT_DELETE_BECAUSE_ASSIGNED', array('message' => "Cannot delete this role as it's assigned to users")); } // delete the role if (!$authItem->delete()) { return $this->result = errorHandler()->logException(null, -1, 'XUSER_ERR_ROLE_DELETE_FAILED', array('message' => 'Deleting the role has been failed')); } return $this->result = array('result' => null, 'returnCode' => 1); }
public function checkAccess($item_name) { //Если суперпользователь, то разрешено все if (isset(Yii::app()->user->role) && Yii::app()->user->role == AuthItem::ROLE_ROOT) { return true; } $auth_item = AuthItem::model()->findByPk($item_name); if (!$auth_item) { Yii::log('Задача $item_name не найдена!'); return false; } if ($auth_item->allow_for_all) { return true; } if ($auth_item->task) { if ($auth_item->task->allow_for_all) { return true; } elseif (Yii::app()->user->checkAccess($auth_item->task->name)) { return true; } } else { if (Yii::app()->user->checkAccess($auth_item->name)) { return true; } } return false; }
/** * Returns the data model based on the primary key given in the GET variable. * If the data model is not found, an HTTP exception will be raised. * @param integer $id the ID of the model to be loaded * @return AuthItem the loaded model * @throws CHttpException */ public function loadModel($id) { $model = AuthItem::model()->findByPk($id); if ($model === null) { throw new CHttpException(404, 'The requested page does not exist.'); } return $model; }
public static function newRoleId() { $rows = AuthItem::model()->FindBySql('select CAST(SUBSTRING(name,11) as SIGNED INTEGER) + 1 AS name from AuthItem where name like "rolebyuser%" order by CAST(SUBSTRING(name,11) as SIGNED INTEGER) desc limit 1'); $result = '1'; if (count((array) $rows) > 0) { $result = $rows['name']; } return $result; }
public function actionIndex() { $moduleId = $this->get('id', ''); $model = Module::model()->find('name = :name', array(':name' => $moduleId)); if ($model && $this->generateRoutes($moduleId)) { $features = $this->getFeatures($moduleId); } $roles = AuthItem::model()->findAll('type = 2'); $this->render('index', array('model' => $model, 'features' => $features, 'roles' => $roles)); }
public function checkAccess($auth_item_name, $params = array(), $allow_caching = true) { return true; if (Yii::app()->user->isRootRole()) { return true; } $auth_item = AuthItem::model()->findByPk($auth_item_name); if ($auth_item && $auth_item['allow_for_all']) { return true; } return parent::checkAccess($auth_item_name, $params, $allow_caching); }
public function checkName() { if ($this->isNewRecord) { if (AuthItem::model()->exists('name=LOWER(:name)', array(':name' => strtolower($this->name)))) { $this->addError('name', at('Sorry, That name is already in use.')); } } else { if (AuthItem::model()->exists('name=LOWER(:name) AND id!=:id', array(':id' => $this->id, ':name' => strtolower($this->name)))) { $this->addError('name', at('Sorry, That name is already in use.')); } } }
public function loadModel($name) { $model = AuthItem::model()->findByAttributes(array( 'name' => $name, 'type' => CAuthItem::TYPE_ROLE )); if (!$model) { $this->pageNotFound(); } return $model; }
public function actionAssignment() { $model = new Authassignment(); if (isset($_POST['Authassignment'])) { $model->attributes = $_POST['Authassignment']; if ($model->validate()) { //$this->saveModel($model); //$this->redirect(array('view','itemname'=>$model->itemname, 'userid'=>$model->userid)); $auth = Yii::app()->authManager; $auth->assign($model->itemname, $model->userid, $model->bizrule, $model->data); } } $user = User::model()->findAll(); $item = AuthItem::model()->findAll(array('condition' => 'type=2')); $this->render('assignment', array('model' => $model, 'user' => $user, 'item' => $item)); }
/** * 删除所有的action操作 * 写着玩的,不可随意执行,会把所有的operation删掉,并且删除这么operation和用户、角色之间的所有关系 * 但是也可以随便执行,因为AR模式在这里执行不了,提供个思路,哈哈。 */ public function clearOpers() { $criteria = new CDbCriteria(); $criteria->condition = "type = 0"; $actions = AuthItem::model()->findAll($criteria); foreach ($actions as $key => $action) { $criteria_child = new CDbCriteria(); $criteria_child->condition = "child = '{$action->name}'"; $flag = ItemChildren::model()->deleteAll($criteria_child); if ($flag > 0) { if ($action->delete()) { echo "{$action->name} delete success\n"; } else { echo "{$action->name} delete failed\n"; } } } }
/** * Загрузка данных из бд и распределение их по спискам */ private function getData() { $userAssign = CHtml::listData(AuthAssignment::model()->findAllByAttributes(['userid' => $this->user->id]), 'itemname', 'userid'); $authItems = AuthItem::model()->findAll(['order' => 'type DESC, description ASC']); foreach ((array) $authItems as $item) { $this->itemsGroupedByTypes[$item->type][$item->name] = $item; $this->itemsList[$item->name] = $item; // если проверять каждый элемент, то генерируется огромное количество запросов, но получается правильное дерево с отмеченными дочерними элементами // созможно стоит при сохранении ролей что-то придумать $this->permissionList[$item->name] = isset($userAssign[$item->name]); //Yii::app()->authManager->checkAccess($item->name, $this->user->id); } $authItemsChild = AuthItemChild::model()->findAll(); foreach ((array) $authItemsChild as $item) { $this->hierarchy[$item->parent][] = $item->child; $this->wereChildren[] = $item->child; } }
/** * Check if we have the access keys in the db * */ public function checkAccess($operation, $params = array()) { // First make sure we haven't already added it // without looking in the db $missingRoles = array(); if (Yii::app()->cache) { $missingRoles = Yii::app()->cache->get('missing_roles'); if ($missingRoles === false) { $missingRoles = array(); } } // Do we have that roles in the array if (!in_array($operation, $missingRoles)) { // We don't so look up the db $roleExists = AuthItem::model()->find('name=:name', array(':name' => $operation)); if (!$roleExists) { // Figure out the type first if (strpos($operation, 'op_') !== false) { $type = CAuthItem::TYPE_OPERATION; } elseif (strpos($operation, 'task_') !== false) { $type = CAuthItem::TYPE_TASK; } else { $type = CAuthItem::TYPE_ROLE; } // Create new auth item Yii::app()->authManager->createAuthItem($operation, $type, $operation, null, null); } $missingRoles[$operation] = $operation; // Save if (Yii::app()->cache) { Yii::app()->cache->set('missing_roles', $missingRoles); } } // In case we are in debug mode then return true all the time if (YII_DEBUG) { return true; } // Return parent check access return parent::checkAccess($operation, $params); }
protected function getModulesTasks() { $tasks = array(); $modules = AppManager::getModulesNames(); foreach ($modules as $module_name => $module_desc) { $operations = array(); $module_actions = AppManager::getModuleActions(ucfirst($module_name) . 'Module'); foreach ($module_actions as $controller => $actions) { $prefix = str_replace('Controller', '', $controller); foreach ($actions as $name => $description) { $name = $prefix . '_' . $name; $exists = AuthItem::model()->exists(" name = '{$name}' AND type = '" . CAuthItem::TYPE_OPERATION . "'"); $operations[] = array('name' => $name, 'description' => $description, 'exists' => $exists); } } $exists = AuthItem::model()->exists(" name = '{$module_name}' AND type = '" . CAuthItem::TYPE_TASK . "'"); $tasks[] = array('exists' => $exists, 'name' => $module_name, 'description' => $module_desc, 'operations' => $operations); } return $tasks; }
function actionTest1() { $criteria = new CDbCriteria(); $criteria->select = array('name', 'description'); $criteria->with = array('authassignments' => array('select' => array('itemname', 'IF(name = itemname,true,false) AS Checked'), 'joinType' => 'LEFT JOIN', 'on' => 'itemname = name and userid = :userid', 'params' => array(':userid' => '1'))); $criteria->condition = 'type = 2'; // $rows = AuthItem::model()->with(array('authassignments'=>array('together'=>false)))->FindAll(); // $rows = AuthAssignment::model()->with('users','authitems','authitems.authitemchildren')->FindAll(); // $rows = User::model()->with('authitems')->FindAll(); $rows = AuthItem::model()->with('authassignments')->FindAll(); // var_dump($rows[1]['authassignments']); $connection = Yii::app()->db; $sql = 'SELECT ai.NAME, ai.description, itemname, IF (ai.NAME = itemname,true,false) AS Checked FROM AuthItemChild RIGHT JOIN AuthItem ai ON parent = NAME LEFT JOIN AuthAssignment ON itemname = ai.NAME AND userid = 1 WHERE ( NOT parent IN ( SELECT b.child FROM AuthItemChild b ) OR (parent IS NULL) ) AND ai.type = 2 GROUP BY ai.NAME ORDER BY ai.NAME'; $command = $connection->createCommand(); $command->select(['NAME', 'description', 'itemname', 'IF (NAME = itemname,true,false) AS Checked'])->from(['AuthItem'])->leftJoin('AuthItemChild', 'parent = NAME')->leftJoin('AuthAssignment', ['and', 'itemname = NAME', 'userid = :userid'], [':userid' => '1'])->andWhere('not parent in (SELECT b.child FROM AuthItemChild b ) OR (parent IS NULL)')->andWhere('type=:type', [':type' => '2'])->group(['NAME'])->order(['NAME']); var_dump($command->join); var_dump($command->params); //var_dump($command->pdoStatement->getColumnMeta(0)); $rows = []; $rows = $command->queryAll(); var_dump($command->pdoStatement); // var_dump($rows); // Print Rows if (count((array) $rows) > 0) { echo '<table style="border-collapse: collapse;"><tbody>'; echo '<tr>'; foreach (array_keys($rows[0]) as $field) { echo '<th style="padding: 5px; border: 1px solid black; min-width: 50px;">' . $field . '</th>'; } echo '</tr>'; foreach ($rows as $row) { echo '<tr>'; foreach ($row as $cell) { echo '<td style="padding: 5px; border: 1px solid black; min-width: 50px;">' . $cell . '</td>'; } echo '</tr>'; } echo '</tbody></table>'; } else { echo 'empty rows'; } /* if (count((array) $rows) > 0) { echo '<table style="border-collapse: collapse;"><tbody>'; echo '<tr>'; foreach (array_keys($rows[0]->attributes) as $field) echo '<th style="padding: 5px; border: 1px solid black; min-width: 50px;">' . $field . '</th>'; echo '</tr>'; foreach ($rows as $row) { echo '<tr>'; foreach ($row->attributes as $cell) echo '<td style="padding: 5px; border: 1px solid black; min-width: 50px;">' . $cell . '</td>'; echo '</tr>'; } echo '</tbody></table>'; } else echo 'empty rows'; */ }
public function actionListAuthItem($userid) { $this->renderPartial('../item/_authitem_opt', array('authItem' => AuthItem::model()->listNotAssignedItem($userid))); }
/** * Checks if srbac is installed by checking if Auth items table exists. * @return boolean Whether srbac is installed or not */ public function isInstalled() { try { $tables = Yii::app()->authManager->db->schema->tableNames; $tableName = AuthItem::model()->tableName(); $tablePrefix = AuthItem::model()->getDbConnection()->tablePrefix; if (!is_null($tablePrefix)) { $tableName = preg_replace('/{{(.*?)}}/', $tablePrefix . '\\1', $tableName); } if (in_array($tableName, $tables)) { return true; } return false; } catch (CDbException $ex) { return false; } }
<?php /** * OpenEyes * * (C) Moorfields Eye Hospital NHS Foundation Trust, 2008-2011 * (C) OpenEyes Foundation, 2011-2013 * This file is part of OpenEyes. * OpenEyes is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. * OpenEyes is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. * You should have received a copy of the GNU General Public License along with OpenEyes in a file titled COPYING. If not, see <http://www.gnu.org/licenses/>. * * @package OpenEyes * @link http://www.openeyes.org.uk * @author OpenEyes <*****@*****.**> * @copyright Copyright (c) 2008-2011, Moorfields Eye Hospital NHS Foundation Trust * @copyright Copyright (c) 2011-2013, OpenEyes Foundation * @license http://www.gnu.org/licenses/gpl-3.0.html The GNU General Public License V3.0 */ $htmlOptions = @$disabled ? array('disabled' => 'disabled') : array(); if (isset($params['empty'])) { $htmlOptions['empty'] = $params['empty']; } $value = $row ? $row->{$params['field']} : ''; $data = AuthItem::model()->findAll(array('condition' => 'type=2', 'order' => 'name asc')); echo CHtml::dropDownList($params['field'] . "[{$i}]", $value, CHtml::listData($data, 'name', 'name'), $htmlOptions);
/** * @desc addassignments */ public function actionManage() { // get changable collumnnames $colUsername = Yii::app()->controller->module->columnUsername; $colUserid = Yii::app()->controller->module->columnUserid; // check access to view $this->checkAccess('RbacAssignmentViewer', true); if (isset($_GET['userid'])) { // warn if user is protected if (in_array($_GET['userid'], $this->protectedUsers)) { $this->messageWarnings[] = "Warning! User is protected by Controller"; } // user must exist if ($user = User::model()->findByAttributes(array("{$colUserid}" => urldecode($_GET['userid'])))) { $this->manageUser = $user; } else { throw new CHttpException("Selected User " . urldecode($_GET['username']) . " does not exist"); } } elseif (isset($_POST['userid'])) { // check access for edit assignments $this->checkAccess('RbacAssignmentEditor', true); if (in_array($_POST['userid'], $this->protectedUsers)) { $this->messageErrors[] = "Sorry, User is protected by Controller"; $this->actionIndex(); } $username = $_POST['username']; $userid = (int) $_POST['userid']; if (!($user = User::model()->findByAttributes(array("{$colUserid}" => $userid)))) { throw new CHttpException("Managed User {$username} does not exist"); } // add selected assignments if (isset($_POST['addAssignments'])) { // fill bizRule with deny-always code if selected from user $bizRule = isset($_POST['secureMode']) ? 'return false;' : ''; foreach ($_POST['addAssignments'] as $itemname) { // add default code to bizRule if selected if (isset($_POST['addData'])) { $item = AuthItem::model()->findByAttributes(array('name' => $itemname)); $bizRule .= $item->data; } // add assignment $assignment = new AuthAssignment(); $assignment->attributes = array('userid' => $userid, 'itemname' => $itemname, 'bizrule' => $bizRule, 'data' => ''); if (!$assignment->validate()) { throw new CHttpException("New Assignment validation Error"); } $assignment->save(); $this->messageSuccess[] = "Assignment {$itemname} succesfull added."; } } // remove selected assignments if (isset($_POST['removeAssignments'])) { foreach ($_POST['removeAssignments'] as $itemname) { $assignment = AuthAssignment::model()->findByAttributes(array('userid' => $userid, 'itemname' => $itemname)); $assignment->delete(); $this->messageSuccess[] = "Assignment {$itemname} succesfull removed."; } } $this->manageUser = $user; } else { $this->actionIndex(); } $this->manageUser = $user; $this->_getSearchFields(); $displayHelper = new RBACDisplayHelper($this, 'renderItemAssign'); $displayHelper->setUser($this->manageUser); $this->doRender('manage', array('displayHelper' => $displayHelper, 'manageUser' => $this->manageUser, 'getVars' => $this->getGetVars())); Yii::app()->end(); }
/** * Checks if srbac is installed by checking if Auth items table exists. * @return boolean Whether srbac is installed or not */ public function isInstalled() { try { $tables = Yii::app()->authManager->db->schema->tableNames; $itemTableName = Yii::app()->authManager->itemTable; $itemChildTableName = Yii::app()->authManager->itemChildTable; $assignmentTableName = Yii::app()->authManager->assignmentTable; $tablePrefix = AuthItem::model()->getDbConnection()->tablePrefix; if (!is_null($tablePrefix)) { $itemTableName = preg_replace('/{{(.*?)}}/', $tablePrefix . '\\1', $itemTableName); $itemChildTableName = preg_replace('/{{(.*?)}}/', $tablePrefix . '\\1', $itemChildTableName); $assignmentTableName = preg_replace('/{{(.*?)}}/', $tablePrefix . '\\1', $assignmentTableName); } if (in_array($itemTableName, $tables) && in_array($itemChildTableName, $tables) && in_array($assignmentTableName, $tables)) { return true; } else { $tables = array_map('strtolower', $tables); if (in_array(strtolower($itemTableName), $tables) && in_array(strtolower($itemChildTableName), $tables) && in_array(strtolower($assignmentTableName), $tables)) { $this->_message = self::TABLE_NAMES_ERROR; return true; } } return false; } catch (CDbException $ex) { return false; } }
/** * Return the operations not assigned to a task by getting all the operations * and removing those assigned to the task, or all the operations if no task * is provided * @param string $name The name of the task * @param boolean $clever Use clever Assigning * @return array An array of operations(AuthItems) not assigned to the task */ public static function getTaskNotAssignedOpers($name, $clever = false) { $tasks = new CDbCriteria(); $tasks->condition = "type=" . CAuthItem::TYPE_OPERATION; if ($clever) { $p[0] = "/Viewing/"; $p[1] = "/Administrating/"; $r[0] = ""; $r[1] = ""; $cleverName = preg_replace($p, $r, $name); $len = strlen($cleverName); $tasks->addCondition("LEFT(name," . $len . ") = '" . $cleverName . "'"); } $final = array(); if ($name) { $na = AuthItem::model()->findAll($tasks); } else { return AuthItem::model()->findAll($tasks); } $as = self::getTaskAssignedOpers($name, $clever); foreach ($na as $n) { $exists = false; foreach ($as as $a) { if ($a['name'] == $n['name']) { $exists = true; } } if (!$exists) { $final[] = $n; } } return $final === null ? array() : $final; }
/** * * @desc * @param unknown_type $model * @param unknown_type $attributes * @param unknown_type $oldName */ private function _updateItem($attributes, $oldName) { if (in_array($oldName, $this->protectedItems) || in_array($attributes['name'], $this->protectedItems)) { $this->messageErrors[] = "Sorry, Item is protected by Controller"; $this->actionIndex(); } if (!($item = AuthItem::model()->findByAttributes(array('name' => $oldName)))) { $this->messageErrors[] = "Edit Error: Update Item does not exist"; $this->actionIndex(); } if ($attributes['type'] == 0 && $item->type > 0) { if (count(AuthItemChild::model()->findAllByAttributes(array('parent' => $oldName)))) { $this->messageErrors[] = "Type <i>Action</i> can't have Childs.<br/>Please eject Childs from <i>{$oldName}</i> before switch type to <i>Operation</i>"; $this->editItem = $item; $this->actionIndex(); } } if ($attributes['name'] != $oldName) { if (AuthItem::model()->findByAttributes(array('name' => $attributes['name']))) { $this->messageErrors[] = "Create Error: New Item <i>{$_POST['editItem']['name']}</i> already exists"; // return; } $item->attributes = $attributes; $item->save(); // update RBAC-Tree AuthItemChild bindings in parent $newName = $attributes['name']; $treeItems = AuthItemChild::model()->findAllByAttributes(array('parent' => $oldName)); foreach ($treeItems as $treeItem) { $treeItem->parent = $newName; $treeItem->save(); } // update RBAC-Tree AuthItemChild bindings in child $treeItems = AuthItemChild::model()->findAllByAttributes(array('child' => $oldName)); foreach ($treeItems as $treeItem) { $treeItem->child = $newName; $treeItem->save(); } // update AuthAssignment bindings in itemname $assignments = AuthAssignment::model()->findAllByAttributes(array('itemname' => $oldName)); foreach ($assignments as $assignment) { $assignment->itemname = $newName; $assignment->save(); } } else { // simple update if primary key is same $item->attributes = $attributes; $item->save(); } $this->messageSuccess[] = "Item " . (!isset($newName) ? $oldName : $newName) . " successfull updated."; }
public function getListaRoles() { return CHtml::listData(AuthItem::model()->findAll(), 'name', 'name'); }
echo CHtml::activeTextField($model, 'email', array('class' => 'validate[required,custom[email]]')); ?> <?php echo CHtml::error($model, 'email'); ?> </div> <div class="clear"></div> <hr /> <div class="grid-3-12"><?php echo CHtml::activeLabelEx($model, 'role'); ?> </div> <div class="grid-9-12"> <?php echo CHtml::activeDropDownList($model, 'role', CHtml::listData(AuthItem::model()->findAll('type=:type', array(':type' => CAuthItem::TYPE_ROLE)), 'name', 'name'), array('data-placeholder' => at('Please select one...'), 'prompt' => '', 'class' => 'chzn-select validate[required]')); ?> <?php echo CHtml::error($model, 'role'); ?> </div> <div class="clear"></div> <hr /> <div class="grid-3-12"><?php echo CHtml::activeLabelEx($model, 'new_password'); ?> </div> <div class="grid-9-12"> <?php echo CHtml::activePasswordField($model, 'new_password', array('class' => 'validate[minSize[6]]'));
/** * Edit category action */ public function actioneditcategory() { // Perms if (!Yii::app()->user->checkAccess('op_extensions_editcats')) { throw new CHttpException(403, Yii::t('error', 'Sorry, You don\'t have the required permissions to enter this section')); } if (isset($_GET['id']) && ($model = ExtensionsCats::model()->findByPk($_GET['id']))) { if (isset($_POST['ExtensionsCats'])) { $model->attributes = $_POST['ExtensionsCats']; if ($model->save()) { Yii::app()->user->setFlash('success', Yii::t('extensions', 'Category Updated.')); $this->redirect(array('index')); } } $roles = AuthItem::model()->findAll(array('order' => 'type DESC, name ASC')); $_roles = array(); if (count($roles)) { foreach ($roles as $role) { $_roles[AuthItem::model()->types[$role->type]][$role->name] = $role->name; } } // Parent list $parents = array(); $parentlist = ExtensionsCats::model()->getRootCats(); if (count($parentlist)) { foreach ($parentlist as $row) { $parents[$row->id] = $row->title; } } // Parse language selections and perms $model->language = $model->language ? explode(',', $model->language) : $model->language; $model->viewperms = $model->viewperms ? explode(',', $model->viewperms) : $model->viewperms; $model->addpostsperms = $model->addpostsperms ? explode(',', $model->addpostsperms) : $model->addpostsperms; $model->addcommentsperms = $model->addcommentsperms ? explode(',', $model->addcommentsperms) : $model->addcommentsperms; $model->addfilesperms = $model->addfilesperms ? explode(',', $model->addfilesperms) : $model->addfilesperms; $model->autoaddperms = $model->autoaddperms ? explode(',', $model->autoaddperms) : $model->autoaddperms; $this->breadcrumbs[Yii::t('extensions', 'Editing Category')] = ''; $this->pageTitle[] = Yii::t('extensions', 'Editing Category'); // Render $this->render('category_form', array('model' => $model, 'parents' => $parents, 'roles' => $_roles, 'label' => Yii::t('extensions', 'Editing Category'))); } else { Yii::app()->user->setFlash('error', Yii::t('extensions', 'Category was not found.')); $this->redirect(array('index')); } }
public function actionSaveAllowed() { if (!Helper::isAlwaysAllowedFileWritable()) { echo Helper::translate("srbac", "The always allowed file is not writable by the server") . "<br />"; echo "File : " . $this->module->getAlwaysAllowedFile(); return; } $allowed = array(); foreach ($_POST as $controller) { foreach ($controller as $action) { //Delete items $auth = AuthItem::model()->findByPk($action); if ($auth !== null) { $auth->delete(); } $allowed[] = $action; } } $handle = fopen($this->module->getAlwaysAllowedFile(), "wb"); fwrite($handle, "<?php \n return array(\n\t'" . implode("',\n\t'", $allowed) . "'\n);\n?>"); fclose($handle); $this->renderPartial("saveAllowed", array("allowed" => $allowed)); }
<?php $this->breadcrumbs = [Yii::t('RbacModule.rbac', 'Actions') => ['index'], Yii::t('RbacModule.rbac', 'Manage')]; $this->menu = [['label' => Yii::t('RbacModule.rbac', 'Roles'), 'items' => [['icon' => 'fa fa-fw fa-list-alt', 'label' => Yii::t('RbacModule.rbac', 'Manage roles'), 'url' => ['/rbac/rbacBackend/index']], ['icon' => 'fa fa-fw fa-plus-square', 'label' => Yii::t('RbacModule.rbac', 'Create role'), 'url' => ['/rbac/rbacBackend/create']]]], ['label' => Yii::t('RbacModule.rbac', 'Users'), 'items' => [['icon' => 'fa fa-fw fa-list-alt', 'label' => Yii::t('RbacModule.rbac', 'Users'), 'url' => ['/rbac/rbacBackend/userList']]]]]; ?> <h3><?php echo Yii::t('RbacModule.rbac', 'Manage items'); ?> </h3> <?php $this->widget('yupe\\widgets\\CustomGridView', ['id' => 'auth-item-grid', 'dataProvider' => $model->search(), 'filter' => $model, 'actionsButtons' => [CHtml::link(Yii::t('YupeModule.yupe', 'Add'), ['/rbac/rbacBackend/create'], ['class' => 'btn btn-success pull-right btn-sm'])], 'columns' => [['class' => 'CCheckBoxColumn'], ['name' => 'name', 'value' => 'CHtml::link($data->name, array("/rbac/rbacBackend/update", "id" => $data->name))', 'type' => 'html'], ['name' => 'description', 'class' => 'bootstrap.widgets.TbEditableColumn', 'headerHtmlOptions' => ['style' => 'width:500px'], 'editable' => ['type' => 'text', 'url' => ['/rbac/rbacBackend/inlineEdit'], 'title' => Yii::t('RbacModule.rbac', 'Enter {field}', ['{field}' => mb_strtolower($model->getAttributeLabel('description'))]), 'params' => [Yii::app()->request->csrfTokenName => Yii::app()->request->csrfToken]], 'filter' => CHtml::activeTextField($model, 'description', ['class' => 'form-control'])], ['name' => 'type', 'filter' => CHtml::activeDropDownList($model, 'type', AuthItem::model()->getTypeList(), ['class' => 'form-control', 'empty' => '']), 'value' => '$data->getType()', 'class' => 'bootstrap.widgets.TbEditableColumn', 'editable' => ['url' => $this->createUrl('/rbac/rbacBackend/inlineEdit'), 'mode' => 'popup', 'type' => 'select', 'title' => Yii::t('RbacModule.rbac', 'Select {field}', ['{field}' => mb_strtolower($model->getAttributeLabel('type'))]), 'source' => AuthItem::model()->getTypeList(), 'params' => [Yii::app()->request->csrfTokenName => Yii::app()->request->csrfToken]], 'type' => 'raw'], ['class' => 'yupe\\widgets\\CustomButtonColumn']]]);
/** * adding auth item child relationships */ public function actionAddItemChild() { // Check Access checkAccessThrowException('op_permission_add_item_child'); $model = new AuthItemChild(); $roles = AuthItem::model()->findAll(array('order' => 'type DESC, name ASC')); $_roles = array(); if (count($roles)) { foreach ($roles as $role) { $_roles[AuthItem::model()->types[$role->type]][$role->name] = $role->description . ' (' . $role->name . ')'; } } // Did we choose a parent already? if (isset($_GET['parent']) && $_GET['parent'] != '') { $model->parent = $_GET['parent']; } if (isset($_POST['AuthItemChild'])) { if (isset($_POST['AuthItemChild']['child']) && count($_POST['AuthItemChild']['child'])) { // We need to delete all child items selected up until now $existsalready = AuthItemChild::model()->findAll('parent=:parent', array(':parent' => $model->parent)); if (count($existsalready)) { foreach ($existsalready as $existitem) { Yii::app()->authManager->removeItemChild($existitem->parent, $existitem->child); } } $added = 0; foreach ($_POST['AuthItemChild']['child'] as $childItem) { $model->child = $childItem; if ($model->validate()) { $added++; } } // Get model parent $authItem = AuthItem::model()->find('name=:name', array(':name' => $model->parent)); fok(at('{number} Child item(s) Added.', array('{number}' => $added))); // Log Message alog(at("Added {number} child items for {name}", array('{number}' => $added, '{name}' => $model->parent))); if ($authItem) { $this->redirect(array('view', 'id' => $authItem->id, '#' => 'tabs-2')); } else { $this->redirect(array('index')); } } } // Selected values $selected = AuthItemChild::model()->findAll('parent=:parent', array(':parent' => $model->parent)); $_selected = array(); if (count($selected)) { foreach ($selected as $select) { $_selected[] = $select->child; } } $model->child = $_selected; // Add Breadcrumb $this->addBreadCrumb(at('Adding Child Permissions')); $this->title[] = at('Adding Child Permissions'); $this->render('child_form', array('model' => $model, 'roles' => $_roles)); }
protected function getItem($name = null) { if (isset($name)) { $this->_model = AuthItem::model()->find('name=:name', array(':name' => $name)); } elseif ($name = Yii::app()->getRequest()->getParam('name')) { $this->_model = AuthItem::model()->find('name=:name', array(':name' => $name)); } if ($this->_model === null) { throw new CHttpException(404, 'The requested page does not exist.'); } return $this->_model; }
<?php $roles = AuthItem::model()->findAllByAttributes(array('type' => CAuthItem::TYPE_ROLE)); return array('activeForm' => array('id' => 'user-form', 'enableAjaxValidation' => true, 'clientOptions' => array('validateOnSubmit' => true)), 'elements' => array('email' => array('type' => 'text'), 'name' => array('type' => 'text'), 'birthdate' => array('type' => 'date'), 'gender' => array('type' => 'dropdownlist', 'items' => User::$gender_options), 'about_self' => array('type' => 'textarea'), 'photo' => array('type' => 'file'), 'status' => array('type' => 'dropdownlist', 'items' => User::$status_options), 'role' => array('type' => 'dropdownlist', 'items' => CHtml::listData($roles, 'name', 'description')), 'password' => array('type' => 'password'), 'password_c' => array('type' => 'password')), 'buttons' => array('submit' => array('type' => 'submit', 'value' => 'сохранить')));
public function safeDown() { AuthItem::model()->deleteByPk(AuthItem::ROLE_ADMIN); }