Alejandro
Alejandro

Reputation: 866

Rbac error check permission Yii2

In my source code, I have this code for check if a user have permissions. For this I'm using RBAC. In my controller, I have this:

public function behaviors()
{
    $behaviors['access'] = [
         'class' => AccessControl::className(),
         'rules' => [
            [
                'allow' => true,
                'roles' => ['@'],
                'matchCallback' => function ($rule, $action) {

                    $module      = Yii::$app->controller->module->id; 
                    $action      = Yii::$app->controller->action->id;
                    $controller  = Yii::$app->controller->id;
                    $route       = "$module/$controller/$action";
                    $post = Yii::$app->request->post();
                    if (\Yii::$app->user->can($route)) {
                        return true;
                    } else {
                        Yii::$app->session->setFlash('error', 'Your user does not have access to this module.');
                        return $this->redirect('dashboard');
                    }
                }
            ],
        ],
    ];         
    return $behaviors;

}

My issue is when I use the function

if (\Yii::$app->user->can($route)) { ....

Yii displays the following error:

PHP Warning – yii\base\ErrorException
in_array() expects parameter 2 to be array, string given ....
........
 in /lxcshared/yii-develop/sacyii.git/vendor/yiisoft/yii2/rbac/DbManager.php at line 196
........
    if (isset($assignments[$itemName]) || in_array($itemName, $this->defaultRoles)) {
        return true;
    }

I follow this guideline Role Based Access Control (RBAC) but I don't know what why I have this issue.

Upvotes: 1

Views: 781

Answers (1)

Misbahul D Munir
Misbahul D Munir

Reputation: 29

Check your config authManager->defaultRoles. It must be array.

'authManager' => [
    ...
    'defaultRoles' => [...]
]

Upvotes: 2

Related Questions