Search code examples
phpyii2rbac

Yii2 RBAC DbManager error Call to a member function getRole() on null


I've set up the database etc by having implemented SQL code to set up the tables and the rbac/init script to fill out the roles / permissions.

I have an assign() at user creation but I keep receiving this error on the getRole():

yii\base\ErrorException Call to a member function getRole() on null

   public function addUser()
{
    if($this->validate()) {
        $user = new User();
        $auth_key = Yii::$app->getSecurity()->generateRandomString(32);
        $this->password = Yii::$app->getSecurity()->generatePasswordHash($this->password);

        $user->email = $this->email;
        $user->password = $this->password;
        $user->active = $this->active;
        $user->firstname = $this->firstname;
        $user->lastname = $this->lastname;
        // $user->nickname = $this->nickname;
        $user->datecreated = time();
        $user->auth_key = $auth_key;
        $user->save(false);

        $auth = Yii::$app->authManager;
        $authorRole = $auth->getRole($this->role);
        $auth->assign($authorRole, $user->getId());

        return $user;
    }else{
        return false;
    }
}

the $role variable is passed through $_POST along with the other user attributes.

Please help. Thanks.


Solution

  • You've gone the wrong way about it.

    The issue here seems to be that Yii::$app->authManager is not set when it should be. This probably means that your main.php configuration file does not contain the correct information. It should contain the following component:

    return [
        // ...
        'components' => [
            'authManager' => [
                'class' => 'yii\rbac\DbManager',
            ],
            // ...
        ],
    ];
    

    (http://www.yiiframework.com/doc-2.0/guide-security-authorization.html#configuring-rbac-manager)

    In the example from the link above PhpManager is used but in your case you will want to use yii\rbac\DbManager

    Doing it this way means that you will only have one loaded manager and will also unlock all action filtering options.