Search code examples
phpyii2rbac

RBAC Yii2 doesn't work with default roles


I'm following the Definitive Guide to Yii 2.0. In my application I have two roles: the admin, who can do everything and the viewer, who can do some actions that unregistered users can't do. I'm trying to use default roles functionality of Yii 2 RBAC, but it seems doesn't work. The user table in my database has a column named "role": for admin it's value set to 1 and for viewers = 2.

What I did:

/app/rbac/UserGroupRule.php

namespace app\rbac;

use Yii;
use yii\rbac\Rule;

class UserGroupRule extends Rule {
    public $name = 'userGroup';

    public function execute($user, $item, $params) {
        if (!Yii::$app->user->isGuest) {
            $group = Yii::$app->user->identity->role;
            if ($item->name === 'admin') {
                return $group == 1;
            } elseif ($item->name === 'viewer') {
                return $group == 1 || $group == 2;
            }
        }
        return false;
    }
}

$auth = Yii::$app->authManager;

$rule = new \app\rbac\UserGroupRule;
$auth->add($rule);

$author = $auth->createRole('viewer');
$author->ruleName = $rule->name;
$auth->add($viewer);

$admin = $auth->createRole('admin');
$admin->ruleName = $rule->name;
$auth->add($admin);
$auth->addChild($admin, $viewer);

in my controller:

public function behaviors() {
    return [
        'access' => [
            'class' => AccessControl::className(),
            'only' => ['admin'],
            'rules' => [
                [
                    'allow' => true,
                    'actions' => ['admin'],
                    'roles' => ['admin'],
                ],
            ],
        ],
    ];
}

When I try to access "admin" action, it says Forbidden #403, even when I'm an admin. How to make it work?


Solution

  • The user table in my database has a column named "role": for admin it's value set to 1 and for viewers = 2

    That's not how it works unfortunately. The rights/roles a user has are (by default) done via the auth_assignment-table. Just add an entry in it:

    INSERT INTO `auth_assignment` VALUES ("admin", <user-id>, NOW());
    

    (be sure to change the user ID into whatever user you want to make admin.

    That should solve your issue.

    Edit (as I misread some of your question):

    As per this link you can indeed define default roles, but you have to make sure to also reconfigure your authManager-component in the configuration file to include the default roles:

    'components' => [
        'authManager' => [
            // ...
            'defaultRoles' => ['admin', 'viewer'],
        ],
    ],
    

    This list of roles indicate the permissions that always should be checked for every user, no matter if they have an entry in the auth_assignment-table or not.