我尝试用DbManager制作RBAC。我读了一些指南并做到了:
在config中添加了authManager
:
'components' => [
//...
'authManager' => [
'class' => 'yii\rbac\DbManager',
'defaultRoles' => [
'user',
'moderator',
'admin',
'superadmin'
],
],
//...
]
在我的数据库中导入\vendor\yiisoft\yii2\rbac\migrations\schema-mysql.sql
;
编写GroupRule类:
namespace app\components\rbac;
use Yii;
use yii\rbac\Rule;
/**
* User group rule class.
*/
class GroupRule extends Rule
{
/**
* @inheritdoc
*/
public $name = 'group';
/**
* @inheritdoc
*/
public function execute($user, $item, $params)
{
if (!Yii::$app->user->isGuest) {
$role = Yii::$app->user->identity->role;
if ($item->name === 'superadmin') {
return $role === $item->name;
} elseif ($item->name === 'admin') {
return $role === $item->name || $role === 'superadmin';
} elseif ($item->name === 'moderator ') {
return $role === $item->name || $role === 'superadmin' || $role === 'admin';
} elseif ($item->name === 'user') {
return $role === $item->name || $role === 'superadmin' || $role === 'admin' || $role === 'moderator';
}
}
return false;
}
}
和rbac控制器:
namespace app\commands;
use Yii;
use yii\console\Controller;
use app\components\rbac\GroupRule;
use yii\rbac\DbManager;
/**
* RBAC console controller.
*/
class RbacController extends Controller
{
/**
* Initial RBAC action
* @param integer $id Superadmin ID
*/
public function actionInit($id = null)
{
$auth = new DbManager;
$auth->init();
$auth->removeAll(); //удаляем старые данные
// Rules
$groupRule = new GroupRule();
$auth->add($groupRule);
// Roles
$user = $auth->createRole('user');
$user->description = 'User';
$user->ruleName = $groupRule->name;
$auth->add($user);
$moderator = $auth->createRole(' moderator ');
$moderator ->description = 'Moderator ';
$moderator ->ruleName = $groupRule->name;
$auth->add($moderator);
$auth->addChild($moderator, $user);
$admin = $auth->createRole('admin');
$admin->description = 'Admin';
$admin->ruleName = $groupRule->name;
$auth->add($admin);
$auth->addChild($admin, $moderator);
$superadmin = $auth->createRole('superadmin');
$superadmin->description = 'Superadmin';
$superadmin->ruleName = $groupRule->name;
$auth->add($superadmin);
$auth->addChild($superadmin, $admin);
// Superadmin assignments
if ($id !== null) {
$auth->assign($superadmin, $id);
}
}
}
在控制台中输入yii rbac/init 1
。
所以,现在为id = 1的用户分配superadmin角色
我有auth_item
表和我的角色,但是type
列每行有值= 1!我认为这是不正常的。我做错了什么?另一个问题 - 我应该对role
表的user
列的item_name
列和auth_assignment
表的{{1}}列做什么?如何在创建新用户时分配角色?
答案 0 :(得分:1)
您可以使用assign
的{{1}}功能为用户分配角色。一般语法是:
authManager
e.g。
Yii::$app->authManager->assign(Yii::$app->authManager->getRole('user_role_here'), 'user_id_here');