YII2中的RBAC:PHPManager中的user-> can()

时间:2015-08-03 13:03:29

标签: php yii2 rbac

我正在尝试使用Yii2高级应用程序版本在我的项目中使用phpmanager配置rbac。但是\ Yii :: $ app-> user->可以不返回预期的。

我编写了RbacController并成功执行yii rbac/init

更新了common / components / 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 :: signup中,我添加了它:

$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] =&gt; yii \ rbac \ Permission Object([type] =&gt; 2 [name] =&gt; createX [description] =&gt;创建X [ruleName] =&gt; [数据] =&gt; [createdAt] =&gt; 1438601819 [updatedAt] =&gt; 1438601819))

所以我希望用户没有更新权限,但在方法XController :: update

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

请一些帮助

1 个答案:

答案 0 :(得分: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);