2015-08-03 65 views
1

我想在我的項目中使用Yii2高級應用程序版本在phpmanager中配置rbac。但是\ Yii :: $ app-> user-> can沒有返回預期的結果。在YII2中的RBAC:user-> can()在PHPManager中

我寫的RbacController和成功地執行yii rbac/init

即更新公共/組件/ items.php如圖

<?php 
return [ 
    'user' => [ 'type' => 1, 'children' => [ 'createX', ], ], 
    'createX' => [ 'type' => 2, 'description' => 'create a X',], 
    'admin' => [ 'type' => 1, 'children' => [ 'updateX', ], ], 
    'updateX => [ 'type' => 2, 'description' => 'update a X', ], 
]; 

在SignupForm ::註冊,我添加它:

$auth = Yii::$app->authManager; 
$roleObj = $auth->getRole('user'); // this role is defined by the RBAC Controller's init action 
$auth->assign($roleObj, $user->getId()); 

assignments.php

return [ 2 => [ 'user', ], ]; 

我認爲2對應於用戶ID。

rules.php

return []; 

公共/ main.php

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

當我該角色的權限,它打印:

陣列([createX] => YII \ RBAC \ Permission Object([type] => 2 [name] => createX [description] =>創建一個X [ruleName] => [data] => [createdAt] => 1438601819 [updatedAt] => 1438601819))

所以我期待的是用戶沒有更新權限,但在方法XController ::更新

echo \Yii::$app->user->can('updateX'); 
// returns 1, just the same than \Yii::$app->user->can('createX') returning 

請一些幫助

回答

0

第一項文件應該是:

<?php 
return [ 
     'user' => [ 'type' => 1, 'children' => [ 'createX', ], ], 
     'createX' => [ 'type' => 2, 'description' => [ 'create a X', ], ], 
     'admin' => [ 'type' => 1, 'children' => [ 'updateX', ], ], 
     'updateX' => [ 'type' => 2, 'description' => ['update a X', ], ], 
]; 

您可以使用var_dump驗證代碼是否正確:

var_dump(\Yii::$app->authManager);