2016-07-01 65 views
0

我正在使用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 
) 

回答

2

這可能是因爲您在「console/rbac/items.php和 console/rbac/rules.php」中生成了rbac,但您的rbac PhpManager正在使用高級/前端

你可以移動這個文件或設置正確的路徑

'authManager' => [ 
    'class' => 'yii\rbac\PhpManager', 
    'itemFile' => '@common/rbac/items.php', 
    'assignmentFile' => '@common/rbac/assignments.php', 
    'ruleFile' => '@common/rbac/rules.php', 
    'defaultRoles' => ['admin', 'author'], // your define roles 
], 

的「@common」是yii2別名這裏列出的所有可用的別名:http://www.yiiframework.com/wiki/667/yii-2-list-of-path-aliases-available-with-default-basic-and-advanced-app/

這應該可以幫助,讓我知道是否會有仍然是一個問題