The database connection is specified by [[db]]. And the database schema
should be as described in "framework/rbac/*.sql". You may change the names of
the three tables used to store the authorization data by setting [[itemTable]],
[[itemChildTable]] and [[assignmentTable]].
/** * This is to be called only once at the initialization * by commenting out the behaviors first. */ public function actionAdmin() { $r = new DbManager(); $r->init(); $test = $r->createRole('admin'); $r->add($test); $r->assign($test, Yii::$app->user->id); }
/** * Saves item. * * @return bool */ public function save() { if ($this->validate() == false) { return false; } if ($isNewItem = $this->item === null) { $this->item = $this->createItem($this->name); } else { $oldName = $this->item->name; } $this->item->name = $this->name; $this->item->description = $this->description; if (!empty($this->rule)) { $rule = \Yii::createObject($this->rule); if (null === $this->manager->getRule($rule->name)) { $this->manager->add($rule); } $this->item->ruleName = $rule->name; } else { $this->item->ruleName = null; } $createdFlashMessage = ''; $updatedFlashMessage = ''; if ($this->item->type = Item::TYPE_PERMISSION) { $createdFlashMessage = Yii::t('rbac', 'Permission has been created'); $updatedFlashMessage = Yii::t('rbac', 'Permission has been updated'); } else { if ($this->item->type = Item::TYPE_ROLE) { $createdFlashMessage = Yii::t('rbac', 'Role has been updated'); $updatedFlashMessage = Yii::t('rbac', 'Role has been updated'); } } if ($isNewItem) { \Yii::$app->session->setFlash('success', $createdFlashMessage); $this->manager->add($this->item); } else { \Yii::$app->session->setFlash('success', $updatedFlashMessage); $this->manager->update($oldName, $this->item); } $this->manager->removeChildren($this->item); if (is_array($this->children)) { foreach ($this->children as $name) { if ($this->item->type = Item::TYPE_PERMISSION) { $child = $this->manager->getPermission($name); } else { if ($this->item->type = Item::TYPE_ROLE) { $child = $this->manager->getRole($name); } } if ($this->manager->hasChild($this->item, $child) == false) { $this->manager->addChild($this->item, $child); } } } return true; }
/** * when user login in backend , it should be 'Administrator' or ,'Merchant' */ public static function beforeLogin() { Event::on(\yii\web\User::className(), \yii\web\User::EVENT_BEFORE_LOGIN, function ($event) { $user = $event->identity; $auth = new DbManager(); $auth->init(); $role = $auth->getRolesByUser($user->id); $event->isValid = in_array(current($role)->name, ['Administrator', 'Merchant']); }); }
public function afterDelete() { $rbac = new DbManager(); $rbac->init(); $role = $rbac->createRole($this->name); $role->description = $this->title; $rbac->remove($role); $rbac->removeChildren($role); return parent::afterDelete(); }
/** * load permissions for selected * @return array */ public function loadPermissions() { $auth = new DbManager(); $auth->init(); $children = $auth->getChildren($this->role_name); $dbPermissions = $this->serializePermissions($children); $selectedValue = []; foreach ($dbPermissions as $key => $value) { $selectedValue[$key] = array_keys($value); } return $selectedValue; }
/** * @param string $id * * @return string */ public function actionView($id) { $role = $this->findModel($id); $authManager = new DbManager(); $allRoles = Role::find()->asArray()->andWhere('name != :current_name', [':current_name' => $id])->all(); $permissions = Permission::find()->andWhere(Yii::$app->getModule(\Yii::$app->user->moduleAliasName)->auth_item_table . '.name != :commonPermissionName', [':commonPermissionName' => Yii::$app->getModule(\Yii::$app->user->moduleAliasName)->commonPermissionName])->joinWith('group')->all(); $permissionsByGroup = []; foreach ($permissions as $permission) { $permissionsByGroup[@$permission->group->name][] = $permission; } $childRoles = $authManager->getChildren($role->name); $currentRoutesAndPermissions = AuthHelper::separateRoutesAndPermissions($authManager->getPermissionsByRole($role->name)); $currentPermissions = $currentRoutesAndPermissions->permissions; return $this->renderIsAjax('view', compact('role', 'allRoles', 'childRoles', 'currentPermissions', 'permissionsByGroup')); }
public function afterSave($insert, $changedAttributes) { parent::afterSave($insert, $changedAttributes); if (!\Yii::$app instanceof ConsoleApplication) { if ($this->scenario == 'update' || $this->scenario == 'create') { $auth = new DbManager(); $auth->init(); $name = $this->role ? $this->role : self::ROLE_DEFAULT; $role = $auth->getRole($name); if (!$insert) { $auth->revokeAll($this->id); } $auth->assign($role, $this->id); } } }
public function init() { parent::init(); if (\Yii::$app->user->isGuest) { return; } }
/** * @inheritdoc */ protected function getChildrenList() { if ($this->_childrenList === null) { $this->_childrenList = parent::getChildrenList(); } return $this->_childrenList; }
public function init() { parent::init(); if (isset(Yii::$app->user)) { $this->assignRole(); } }
/** * Helper for adding children to role or permission * * @param string $parentName * @param array|string $childrenNames * @param bool $throwException * * @throws \Exception */ public static function addChildren($parentName, $childrenNames, $throwException = false) { $parent = (object) ['name' => $parentName]; $childrenNames = (array) $childrenNames; $dbManager = new DbManager(); foreach ($childrenNames as $childName) { $child = (object) ['name' => $childName]; try { $dbManager->addChild($parent, $child); } catch (\Exception $e) { if ($throwException) { throw $e; } } } AuthHelper::invalidatePermissions(); }
public function init() { parent::init(); //вешаем на событие удаления пользователя удаление всех его назначений в acl Event::on(User::class, User::EVENT_USER_DELETE, function (UserEvent $event) { return $this->revokeAll($event->user->id); }); }
/** * Get role by its name. * @param string $name * @return Role * @throws InvalidArgumentException when role not found. */ protected function getRole($name) { $role = $this->_auth->getRole($name); if (!$role) { throw new InvalidArgumentException('Role "' . $name . '" not found.'); } return $role; }
/** * Remove admin role for user * after that set member role for user * @param $id: user id from user table * @return redirect to admin/index page */ public function actionRemoverole($id) { $r = new DbManager(); $r->init(); if ($id > 0) { // remove admin role for this user $admin = $r->getRole('admin'); $r->revoke($admin, $id); // get member role to add to this user $member = $r->getRole('member'); $r->assign($member, $id); // update user table $this->updateUser($id, BUser::getAuthName('ROLE_MEMBER')); Yii::$app->getSession()->setFlash('user.success', Yii::t('user', 'User has been updated')); } else { Yii::$app->getSession()->setFlash('user.success', Yii::t('error', 'Sorry there is something wrong!')); } return $this->redirect(['index']); }
public function actionInit() { $auth = new DbManager(); $auth->init(); $auth->removeAll(); $groupRule = new GroupRule(); $auth->add($groupRule); $user = $auth->createRole('user'); $user->description = 'User'; $user->ruleName = $groupRule->name; $auth->add($user); $auth->add($auth->createPermission('admin')); }
private function getPermission($permissionName) { $this->outputItem("Searching for", $permissionName, "Role in database"); $permission = $this->_authManager->getRole($permissionName); if (isset($permission)) { $this->stdout('OK', Console::FG_GREEN); } else { $this->stdout('FAILED', Console::FG_RED, Console::BOLD); } return $permission; }
/** * This method is invoked right before an action is to be executed (after all possible filters.) * It checks the existence of the authManager components. * @param \yii\base\Action $action the action to be executed. * @return boolean whether the action should continue to be executed. */ public function beforeAction($action) { try { if (parent::beforeAction($action)) { $this->authManager = Instance::ensure($this->authManager, DbManager::className()); return true; } } catch (Exception $e) { $this->stderr("ERROR: " . $e->getMessage() . "\n"); } return false; }
/** * @inheritdoc */ public function checkAccess($userId, $permissionName, $params = []) { if (!isset($this->_users[$userId])) { $this->_users[$userId] = User::findOne($userId); } $user = $this->_users[$userId]; if ($user instanceof User && $user->is_super_admin) { return true; } else { return parent::checkAccess($userId, $permissionName, $params); } }
private function setDefault() { $userPermission = $this->createPermission('editUser', 'Изменение пользователей системы'); $rolePermission = $this->createPermission('editRole', 'Изменение ролей пользователей'); $adminRole = $this->createRole(Yii::$app->params['admin.role'], 'Администратор'); $this->authManager->addChild($adminRole, $userPermission); $this->authManager->addChild($adminRole, $rolePermission); $admin = User::findOne(['username' => Yii::$app->params['admin.name']]); if (is_null($admin)) { $admin = $this->createAdminUser(); } $this->authManager->assign($adminRole, $admin->getPrimaryKey()); }
public function savePermissions() { $auth = new DbManager(); $auth->init(); $actions = $this->getActions(); if (strpos($this->controllerClass, '\\') === false) { \Yii::$app->session->addFlash('error', \Yii::t('auth', 'wrong data ')); } else { foreach ($actions as $action) { if (!$auth->getPermission($this->controllerClass . '_' . $action)) { $permission = $auth->createPermission($this->controllerClass . '_' . $action); if (!$auth->add($permission)) { \Yii::$app->session->addFlash('error', \Yii::t('auth', $action . ' action add failed')); } else { \Yii::$app->session->addFlash('success', \Yii::t('auth', 'add ' . $action . ' action success!')); } } else { \Yii::$app->session->addFlash('error', \Yii::t('auth', $action . ' action has already exist')); } } } }
/** * Find role by name and throws NotFoundHttpException if it not exists. * * @param string $id * @return Role * @throws NotFoundHttpException */ protected function findRole($id) { $role = is_string($id) ? $this->authManager->getRole($id) : null; if (!$role instanceof Role) { throw new NotFoundHttpException(); } else { if ($role->name == 'admin') { // can't remove or update admin role throw new ForbiddenHttpException(Yii::t('user', "You can't update or delete administrative role")); } } return $role; }
/** * @inheritdoc */ public function getAssignments($userId) { if (empty($userId)) { return parent::getAssignments($userId); } $cacheKey = 'Assignments:' . $userId; $cached = $this->getCache($cacheKey); if (empty($cached)) { $cached = parent::getAssignments($userId); $this->setCache($cacheKey, $cached); } return $cached; }
public function beforeAction($action) { // 判断是否登录 $isLogin = AdminBaseInfo::isLogin(); if (!$isLogin) { return $this->redirect(['login/login']); } $session = Yii::$app->getSession(); $Jurisdiction = Yii::$app->controller->id . '/' . Yii::$app->controller->action->id; $dbManager = new DbManager(); $id = $session[AdminBaseInfo::SESSION_KEY_ADMIN]['id']; if (Yii::$app->authManager->getRolesByUser($id)['admin']->name == 'admin') { parent::beforeAction($action); return true; } if ($dbManager->checkAccess($id, $Jurisdiction)) { parent::beforeAction($action); return true; } else { return $this->redirect(['login/no-authority']); } parent::beforeAction($action); return true; }
public function init() { if (is_string($this->db)) { $this->db = Yii::$app->get($this->db); } if (!$this->assignmentTable) { $this->assignmentTable = $this->db->tablePrefix . 'auth_assignment'; } if (!$this->itemTable) { $this->itemTable = $this->db->tablePrefix . 'auth_item'; } if (!$this->itemChildTable) { $this->itemChildTable = $this->db->tablePrefix . 'auth_item_child'; } parent::init(); }
private function addItem($item) { $exitCode = 0; //Save the model try { $this->_authManager->add($item); $this->stdout("OK", Console::FG_GREEN); } catch (\Exception $e) { $this->stdout("FAILED", Console::FG_RED); $this->stderr("\nGenerated Message: "); //Todo: Optional full error message display $this->stderr(strtok($e->getMessage(), "\n"), Console::BG_BLUE); $exitCode = 1; } $this->stdout("\n"); return $exitCode; }
public function checkAccess($userId, $permissionName, $params = []) { if (count($params) > 0) { return parent::checkAccess($userId, $permissionName, $params); } $cacheKey = $this->cachePrefix . 'userAccessCheck:' . $userId . ':' . $permissionName; /* Due to yii2 cache system, where we receive 'false' from cache component we have to store array in cache to ensure that 'false' doesn't mean that access is restricted */ $check = $this->getCache()->get($cacheKey); if (!is_array($check)) { $check = [parent::checkAccess($userId, $permissionName, $params)]; $this->getCache()->set($cacheKey, $check, $this->lifetime); } return $check[0]; }
/** * @inheritdoc */ public function init() { parent::init(); //if (!Yii::$app->user->isGuest) { //我们假设用户的角色是存储在身份 // $this->assign(Yii::$app->user->identity->id, Yii::$app->user->identity->role); // } // $user = Yii::$app->getUser(); // if (!$user->isGuest) { // $identity = $user->getIdentity(); // if (!$this->getAssignment($identity->role, $identity->getId())) { // $role = new Role([ // 'name' => $identity->role // ]); // $this->revokeAll($identity->getId()); // $this->assign($role, $identity->getId()); // } // } }
public function getPermissionsTree($userId = 0) { if ($userId) { $pms = parent::getPermissionsByUser($userId); } else { $pms = parent::getPermissions(); } $menu = $this->getMenu(); $tree = []; foreach ($menu as $m => $sms) { if (!array_key_exists($m, $pms)) { continue; } $_ = ['name' => $pms[$m]->description, 'subMenus' => []]; foreach ($sms as $sm) { if (!array_key_exists($sm, $pms)) { continue; } $_['subMenus'][$sm] = $pms[$sm]->description; } $tree[$m] = $_; } return $tree; }
/** * @inheritdoc */ public function removeChildren($parent) { $result = parent::removeChildren($parent); if ($this->_children !== null) { unset($this->_children[$parent->name]); } $this->invalidate(self::PART_CHILDREN); return $result; }
public function actionInit() { if (!$this->confirm("Are you sure? It will re-create permissions tree.")) { return self::EXIT_CODE_NORMAL; } //$auth = Yii::$app->authManager; // Підключення через Базу даних $auth = new DbManager(); $auth->init(); $auth->removeAll(); // Роль студент $student = $auth->createRole('student'); $student->description = 'Student'; $auth->add($student); // Роль працедавець $employer = $auth->createRole('employer'); $employer->description = 'Employer'; $auth->add($employer); // Роль модератор $moderator = $auth->createRole('moderator'); $moderator->description = 'Moderator'; $auth->add($moderator); $auth->addChild($moderator, $student); $auth->addChild($moderator, $employer); // Роль адміністратор $admin = $auth->createRole('admin'); $admin->description = 'Administrator'; $auth->add($admin); $auth->addChild($admin, $moderator); }