我正在使用yii2來實現rbac。但是,當我嘗試獲得我以前創建的角色時,我得到一個空變量:$authorRole = $auth->getRole('admin');
yii2 rbac authmanager getRoles()return empty
規則類,其中我把實際的規則邏輯。
警予/控制檯/控制器/ UserGroupRule.php
namespace app\rbac;
use Yii;
use yii\rbac\Rule;
/**
* Checks if user group matches
*/
class UserGroupRule extends Rule
{
public $name = 'userGroup';
public function execute($user, $item, $params)
{
if (!Yii::$app->user->isGuest) {
$group = Yii::$app->user->identity->group;
if ($item->name === 'admin') {
return $group == 1;
} elseif ($item->name === 'author') {
return $group == 1 || $group == 2;
}
}
return false;
}
}
現在定義的角色..
yii/console/controller/RbacController.php
namespace console\controllers;
use Yii;
use yii\console\Controller;
class RbacController extends Controller
{
public function actionInit()
{
$auth = Yii::$app->authManager;
$rule = new \app\rbac\UserGroupRule;
$auth->add($rule);
$admin = $auth->createRole('admin');
$admin->ruleName = $rule->name;
$auth->add($admin);
}
}
這也是我能夠運行./yii RBAC /初始化後,生成規則文件:
- conso LE/RBAC/items.php
- 控制檯/ RBAC/rules.php
這主要是相同的文檔
YII /黎民/配置/ main.php
'authManager' => [
'class' => 'yii\rbac\PhpManager',
'defaultRoles' => ['admin', 'author'], // your define roles
],
但
種前端\型號\ SignupForm ::註冊()
我得到一個空的結果,當我試圖讓admin角色:
public function signup()
{
if ($this->validate()) {
$user = new User();
$user->username = $this->username;
$user->email = $this->email;
$user->setPassword($this->password);
$user->generateAuthKey();
$user->save(false);
$auth = Yii::$app->authManager;
$authorRole = $auth->getRole('admin');
$auth->assign($authorRole, $user->getId());
return $user;
}
return null;
}
這裏是$權威性的價值:
yii\rbac\PhpManager#1
(
[itemFile] => '/advanced/frontend/rbac/items.php'
[assignmentFile] => '/advanced/frontend/rbac/assignments.php'
[ruleFile] => '/advanced/frontend/rbac/rules.php'
[*:items] => []
[*:children] => []
[*:assignments] => []
[*:rules] => []
[defaultRoles] => [
0 => 'admin'
1 => 'author'
2 => 'admin'
3 => 'author'
]
[yii\base\Component:_events] => []
[yii\base\Component:_behaviors] => null
)