yii2 rbac authmanager getRoles() return empty

I’m implementing rbac using yii2. But when i try to get the roles that i previously created i get an empty variable : $authorRole = $auth->getRole(‘admin’);

The rule class, where i put the actual rule logic.

yii/console/controller/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;

    }

}

Now defining the roles…

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);


    }

}

After this i was able to run ./yii rbac/init to generate the rule files:


console/rbac/items.php

console/rbac/rules.php

This is mostly identical to the documentation


yii/commom/config/main.php

'authManager' => [

    'class' => 'yii\rbac\PhpManager',

    'defaultRoles' => ['admin', 'author'], // your define roles

],  

But in

frontend\models\SignupForm::signup()

I get an empty result when i try to get the admin role :


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;

}

here is the value of $auth :


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

)

  1. Do you have the same auth config for console / frontend?

  2. Were roles actually saved? Check files (if you use file backend) or DB (if you use database).