I am trying to implement RBAC in my project by following the tutorial* on the Yii website. However I am confused when trying to implement the permissions by group.
For this example I have added a group
field into the user table and have defined two groups, user (2)
and admin (1)
.
I then created a console command which looks like this:
class RbacController extends Controller
{
public function actionInit()
{
$auth = \Yii::$app->authManager;
$rule = new \appbac\UserGroupRule;
$auth->add($rule);
$search = $auth->createPermission('search');
$search->description = 'Search';
$search->ruleName = $rule->name;
$auth->add($search);
$user = $auth->createRole('user');
$user->ruleName = $rule->name;
$auth->add($user);
$admin = $auth->createRole('admin');
$admin->ruleName = $rule->name;
$auth->add($admin);
$auth->addChild($admin, $user);
}
}
And I have this file: rbac/UserGroupRule.php
class UserGroupRule extends Rule
{
public $name = 'userGroup';
public function execute($user, $item, $params)
{
// return true; // force return to true for test
if(!Yii::$app->user->isGuest) {
$group = Yii::$app->user->identity->group;
if($item->name === 'search') {
return $group == 1;
}
return false;
}
}
I'm trying to test the permission with if(\Yii::$app->user->can('search'))
.
Firstly, I wonder why the console command is required here as I can't see where it's being used.
The $item parameter in the execute method has the value of
search
, but the tutorial shows that it expects this value to be role type.Regardless of what I return in the execute method, it seems to return false.
Can anyone answer these questions?