/** * Creates a new model. * If creation is successful, the browser will be redirected to the 'view' page. */ public function actionTambah() { $model = new AuthItem(); // Uncomment the following line if AJAX validation is needed // $this->performAjaxValidation($model); if (isset($_POST['AuthItem'])) { $model->attributes = $_POST['AuthItem']; if ($model->save()) { $this->redirect(array('ubah', 'id' => $model->name)); } } $this->render('tambah', array('model' => $model)); }
public function safeUp() { /* Всем администраторам назначается роль admin */ $adminRole = new AuthItem(); $adminRole->name = AuthItem::ROLE_ADMIN; $adminRole->description = Yii::t('RbacModule.rbac', 'Admin'); $adminRole->type = AuthItem::TYPE_ROLE; $adminRole->save(); $admins = User::model()->findAllByAttributes(['access_level' => User::ACCESS_LEVEL_ADMIN]); foreach ($admins as $admin) { $assign = new AuthAssignment(); $assign->itemname = $adminRole->name; $assign->userid = $admin->id; $assign->save(); } }
/** * Create permission form */ public function actionCreate($type = null) { // Check Access checkAccessThrowException('op_permission_create'); $model = new AuthItem(); if (isset($_POST['AuthItem'])) { $model->setAttributes($_POST['AuthItem']); if ($model->save()) { fok(at('Permission Created!')); // Log Message alog(at("New permission created: '{name}'.", array('{name}' => $model->name))); $this->redirect(array('index')); } } else { if ($type !== null) { $model->type = $type; } } // Add Breadcrumb $this->addBreadCrumb(at('Create Permission')); $this->title[] = at('Create Permission'); $this->render('form', array('model' => $model)); }
/** * Creates a new model. * If creation is successful, the browser will be redirected to the 'view' page. */ public function actionCreate() { $model = new AuthItem(); $operationsList = $tasksList = array(); $operations = AuthItem::model()->findAll('type = :type', array(':type' => AuthItem::TYPE_OPERATION)); foreach ($operations as $op) { $operationsList[$op->name] = $op->description . "({$op->name})"; } $tasks = AuthItem::model()->findAll('type = :type', array(':type' => AuthItem::TYPE_TASK)); foreach ($tasks as $task) { $tasksList[$task->name] = $task->description . "({$task->name})"; } if (Yii::app()->request->isPostRequest && isset($_POST['AuthItem'])) { $transaction = Yii::app()->db->beginTransaction(); try { $model->attributes = Yii::app()->request->getPost('AuthItem'); if ($model->save()) { $children = array(); if ($model->type == AuthItem::TYPE_TASK) { $children = Yii::app()->request->getPost('operations'); } elseif ($model->type == AuthItem::TYPE_ROLE) { $children = Yii::app()->request->getPost('tasks'); } // сохранить чайлдов if (!empty($children)) { foreach ($children as $name) { $child = new AuthItemChild(); $child->setAttributes(array('parent' => $model->name, 'child' => $name)); if (!$child->save()) { throw new CDbException('Ошибка при сохранении связанных объектов!'); } } } $transaction->commit(); Yii::app()->user->setFlash('success', 'Действие добавлено!'); $this->redirect(array('view', 'id' => $model->name)); } } catch (Exception $e) { Yii::app()->user->setFlash('error', $e->getMessage()); $transaction->rollback(); } } $this->render('create', array('model' => $model, 'operations' => $operationsList, 'tasks' => $tasksList)); }
/** * Autocreating of authItems */ public function actionAutoCreateItems() { $controller = str_replace("Controller", "", $_POST["controller"]); $actions = isset($_POST["actions"]) ? $_POST["actions"] : array(); $message = ""; $createTasks = isset($_POST["createTasks"]) ? $_POST["createTasks"] : 0; $tasks = isset($_POST["tasks"]) ? $_POST["tasks"] : array(""); if ($createTasks == "1") { $message = "<div style='font-weight:bold'>" . Helper::translate('srbac', 'Creating tasks') . "</div>"; foreach ($tasks as $key => $taskname) { $auth = new AuthItem(); $auth->name = $taskname; $auth->type = 1; try { if ($auth->save()) { $message .= "'" . $auth->name . "' " . Helper::translate('srbac', 'created successfully') . "<br />"; } else { $message .= "<div style='color:red;font-weight:bold'>" . Helper::translate('srbac', 'Error while creating') . ' ' . $auth->name . '<br />' . Helper::translate('srbac', 'Possible there\'s already an item with the same name') . "</div><br />"; } } catch (Exception $e) { $message .= "<div style='color:red;font-weight:bold'>" . Helper::translate('srbac', 'Error while creating') . ' ' . $auth->name . '<br />' . Helper::translate('srbac', 'Possible there\'s already an item with the same name') . "</div><br />"; } } } $message .= "<div style='font-weight:bold'>" . Helper::translate('srbac', 'Creating operations') . "</div>"; foreach ($actions as $action) { $act = explode("action", $action, 2); $a = trim($controller . (count($act) > 1 ? $act[1] : ucfirst($act[0]))); $auth = new AuthItem(); $auth->name = $a; $auth->type = 0; try { if ($auth->save()) { $message .= "'" . $auth->name . "' " . Helper::translate('srbac', 'created successfully') . "<br />"; if ($createTasks == "1") { if ($this->_isUserOperation($auth->name)) { $this->_assignChild($tasks["user"], array($auth->name)); } $this->_assignChild($tasks["admin"], array($auth->name)); } } else { $message .= "<div style='color:red;font-weight:bold'>" . Helper::translate('srbac', 'Error while creating') . ' ' . $auth->name . '<br />' . Helper::translate('srbac', 'Possible there\'s already an item with the same name') . "</div><br />"; } } catch (Exception $e) { $message .= "<div style='color:red;font-weight:bold'>" . Helper::translate('srbac', 'Error while creating') . ' ' . $auth->name . '<br />' . Helper::translate('srbac', 'Possible there\'s already an item with the same name') . "</div><br />"; } } echo $message; }
/** * Creates a new model. * If creation is successful, the browser will be redirected to the 'view' page. */ public function actionCreateAction() { $model = new AuthItem(); // Uncomment the following line if AJAX validation is needed // $this->performAjaxValidation($model); if (isset($_POST['AuthItem'])) { $model->attributes = $_POST['AuthItem']; if ($model->save()) { $this->logAudit("Action " . $model->name . " was created "); $this->redirect(array('view', 'id' => $model->name)); } } $this->render('createAction', array('model' => $model)); }
public function actionManage() { if (isset($_POST['AuthItem'])) { $items_names = array(); foreach ($_POST['AuthItem'] as $task_name => $data) { p($_POST['AuthItem']); die; if (!isset($data['description'])) { continue; } $items_names[] = $task_name; if (!isset($data['operations'])) { continue; } foreach ($data['operations'] as $name => $description) { $items_names[] = $name; } } $items_names = array_map(function ($v) { return "'{$v}'"; }, $items_names); $items_names = implode(',', $items_names); AuthItem::model()->delete("name NOT IN ({$items_names})"); foreach ($_POST['AuthItem'] as $task_name => $data) { if (!isset($data['description'])) { continue; } $task = AuthItem::model()->findByPk($task_name); if (!$task) { $task = new AuthItem(); $task->type = CAuthItem::TYPE_TASK; $task->name = $task_name; $task->description = $data['description']; } if ($task->save() && isset($data['operations'])) { foreach ($data['operations'] as $name => $description) { $operation = AuthItem::model()->findByPk($name); if (!$operation) { $operation = new AuthItem(); $operation->type = CAuthItem::TYPE_OPERATION; $operation->name = $name; $operation->description = $description; } if ($operation->save()) { $auth_item_child = AuthItemChild::model()->findByAttributes(array('parent' => $task->name, 'child' => $operation->name)); if (!$auth_item_child) { $auth_item_child = new AuthItemChild(); $auth_item_child->parent = $task->name; $auth_item_child->child = $operation->name; $auth_item_child->save(); } } } } } } $auth_items = array(); $tasks = $this->getModulesTasks(); foreach ($tasks as $task) { $auth_items[] = array('id' => $task['name'], 'name' => $task['name'], 'exists' => $task['exists'], 'description' => $task['description']); if (isset($task['operations'])) { foreach ($task['operations'] as $operation) { $operation['parent'] = $task['name']; $operation['id'] = $operation['name']; $auth_items[] = $operation; } } } $data_provider = new CArrayDataProvider($auth_items, array('pagination' => false)); $this->render('manage', array('data_provider' => $data_provider, 'tasks' => $this->getModulesTasks())); }
/** * Update an auth item. * Note: The item's type can not be changed. */ public function actionManage($item) { $item = $this->authManager->getEAuthItem($item); if (empty($item)) throw new CHttpException(404, Yii::t('RbamModule.rbam','Authorisation item not found.')); $authItem = new AuthItem('update'); // $authItem is a CFormModel $attributes = array(); foreach ($authItem->getAttributes() as $name=>$value) $authItem->$name = $item->$name; $form = $authItem->getForm(!in_array($item->name, $this->getModule()->getDefaultRoles())); if ($form->submitted($form->uniqueId)) { $response = array(); if ($authItem->save($item)) { $response['content'] = Yii::t('RbamModule.rbam','"{item}" {type} updated.', array( '{item}'=>$item->name, '{type}'=>$this->type($item->type, true) )); if ($item->name!==$_POST['AuthItem']['oldName']) $response['redirect'] = $this->createUrl($this->action->id, array('item'=>$item->name)); } else { $errors = array(); foreach ($authItem->getErrors() as $attribute=>$attributeErrors) foreach ($attributeErrors as $error) $errors[] = array( 'attribute'=>$attribute, 'label'=>$authItem->getAttributeLabel($attribute), 'error'=>$error ); $response = compact('errors'); } header('Content-type: application/json'); echo CJSON::encode($response); Yii::app()->end(); } if (Yii::app()->getUser()->checkAccess($this->getModule()->authAssignmentsManagerRole)) { $authAssignment = new AuthAssignment('upate'); // $authAssignment is a CFormModel $assignmentForm = $authAssignment->getForm(); } else $assignmentForm = null; $this->pageTitle = $this->_pageTitle($this->action->id, array( '{item}'=>$item->name, '{type}'=>$this->type($item->type, true, true) )); $this->breadcrumbs = array( 'RBAM'=>array('rbam/index'), $this->_pageTitle('index')=>array('index'), $this->pageTitle ); $this->render('form', compact('item', 'form', 'assignmentForm')); }
public function actionCreate() { $parent = $this->getItem(); $item = new AuthItem(); $item_child = new AuthItemChild(); if (isset($_POST['AuthItem'])) { $item->attributes = $_POST['AuthItem']; $item_child->attributes = $_POST['AuthItemChild']; $item_child->child = $item->name; if ($item->validate() && $item_child->validate()) { $item->save(false); $item_child->save(false); $this->redirect(array('view', 'name' => $item->name)); } } $this->render('create', array('parent' => $parent, 'item' => $item, 'item_child' => $item_child)); }
/** * * @desc */ public function actionEdit() { $this->checkAccess('RbacViewer', true); $model = new AuthItem(); if (empty($_POST)) { if (isset($_GET['item'])) { if (in_array($_GET['item'], $this->protectedItems)) { $this->messageErrors[] = "Warning! Item is protected by Controller"; } $model->attributes = $_GET; if ($model->validate()) { $name = urldecode($_GET['item']); if ($item = $model->findByAttributes(array('name' => $name))) { // display edit Item box $this->editItem = $item; $this->actionIndex(); } else { $this->messageErrors[] = "The Item you want to edit does not exist"; } } else { $this->messageErrors[] = "Unsecure Data detected. Please mail the Siteadmin if this Problem returns."; } } else { //ignore missing item and display index $this->actionIndex(); } } else { $this->checkAccess('RbacEditor', true); // filter names $_POST['editItem']['name'] = $this->filterString($_POST['editItem']['name'], $this->filterNames); $model->attributes = $_POST['editItem']; $oldName = $_POST['oldName']; if (in_array($oldName, $this->protectedItems) || in_array($_POST['editItem']['name'], $this->protectedItems)) { $this->messageErrors[] = "Sorry, Item is protected by Controller"; $this->actionIndex(); } if ($model->validate()) { if (isset($_POST['updateItem'])) { $this->_updateItem($_POST['editItem'], $oldName); } elseif (isset($_POST['createItem'])) { if (!AuthItem::model()->findByAttributes(array('name' => $_POST['editItem']['name']))) { $model->setIsNewRecord(true); $model->save(); $this->messageSuccess[] = "Item {$_POST['editItem']['name']} successfull created."; } else { $this->messageErrors[] = "Create Error: New Item <i>{$_POST['editItem']['name']}</i> already exists"; $this->editItem = $model; $this->actionIndex(); } } elseif (isset($_POST['deleteItem'])) { AuthItem::model()->deleteAllByAttributes(array('name' => $oldName)); AuthItemChild::model()->deleteAllByAttributes(array('parent' => $oldName)); AuthItemChild::model()->deleteAllByAttributes(array('child' => $oldName)); AuthAssignment::model()->deleteAllByAttributes(array('itemname' => $oldName)); $this->messageSuccess[] = "Item {$oldName} successfull deleted."; } else { // ignore not existing submit option and render page } $this->actionIndex(); } else { //use Yii error system $model->setIsNewRecord(true); $this->editItem = $model; $this->actionIndex(); } } }
public function actionImport() { $modulesList = []; $modules = []; foreach (Yii::app()->getModules() as $key => $value) { $key = strtolower($key); $module = Yii::app()->getModule($key); if ($module instanceof \yupe\components\WebModule) { $modulesList[$key] = $module->getName(); $modules[$key] = $module; } } if (Yii::app()->getRequest()->isPostRequest) { $importModules = array_intersect(Yii::app()->getRequest()->getPost('modules', []), array_keys($modules)); foreach ($importModules as $moduleName) { /* @var $module \yupe\components\WebModule */ $module = $modules[$moduleName]; $rules = $module->getAuthItems(); // 1 - получить все элементы из дерева $items = $this->getRulesList($rules); $parentsChildren = $this->getRulesParentsAndChildren($items); // обновляем foreach ($items as $item) { $model = AuthItem::model()->findByPk($item['name']); if (!$model) { $model = new AuthItem(); } $model->attributes = $item; $model->save(); } // удаляем удаленные из модуля // оставшиеся $availableItems = array_map(function ($x) { return $x['name']; }, $items); /* удаляем правила */ $criteria = new CDbCriteria(); $criteria->addCondition('name like :rule'); $criteria->params = [':rule' => ucfirst($moduleName) . '.%']; $criteria->addNotInCondition('name', $availableItems); AuthItem::model()->deleteAll($criteria); /* создаем связи */ foreach ($parentsChildren as $pair) { $model = AuthItemChild::model()->findByPk(['parent' => $pair['parent'], 'child' => $pair['child']]); if (!$model) { $model = new AuthItemChild(); $model->attributes = $pair; $model->save(); } } } Yii::app()->getUser()->setFlash(yupe\widgets\YFlashMessages::SUCCESS_MESSAGE, Yii::t('RbacModule.rbac', 'Items successfully imported!')); $this->redirect(['import']); } $this->render('import', ['modules' => $modulesList]); }
/** * 增加角色 */ public function actionRoleCreate() { $request = new Request(array('restful' => false)); if (is_object($request->params)) { $params = get_object_vars($request->params); } else { $params = $request->params; } // Uncomment the following line if AJAX validation is needed // $this->performAjaxValidation($model); $model = new AuthItem(); $model->attributes = array('name' => $params['roleName'], 'type' => CAuthItem::TYPE_ROLE, 'description' => $params['roleDescription'], 'bizrule' => $params['roleBizRule'], 'data' => $params['roleData']); $authItem = AuthItem::model()->find('name = :name', array(':name' => $params['roleName'])); if (empty($authItem)) { if ($model->save()) { $data = array('roleName' => $model->name); //添加父角色 $paerentRoleName = $params['parentRoleName']; $auth = Yii::app()->authManager; $role = $auth->addItemChild($paerentRoleName, $params['roleName']); if ($role) { $success = true; $message = '该操作添加成功'; $data = array(); } else { $success = true; $message = '该操作添加失败'; $data = array(); } } else { $success = false; $message = '添加角色失败'; $data = array(); } } else { $success = false; $message = '添加角色或权限已经存在'; $data = array(); } $res = new Response(); $res->success = $success; $res->message = $message; $res->data = $data; echo $res->to_json(); }