Yii2 roles and users

237 views Asked by At

Can I statically define roles in authManager (in defaultRoles array in config) and assign them to users so behavior rules define access to actions?
As i have certain roles, I don't want to use auth_assignment and auth_item and ...
Assuming I create column in user table for role and every user has one role and roles are define in config file.

In fact I want to build access rules like 'admin' for users who are admin (Where yii says '@' for authenticated user and '?' for guest).

1

There are 1 answers

0
Mehrdad On

First create your roles somewhere like params then behaviors function can manage authentication easily

public function behaviors()
{
    return [
        'access' => [
            'class'  => AccessControl::className(),
            'except' => [''],//or only
            'rules'  => [
                [
                    'allow'         => true,
                    'actions'       => ['deletepic', 'regenerate'],
                    'matchCallback' => function ($rule, $action) {
                        return (myAuth(['root','admin']));
                    }
                ],
            ],
        ],
    ];
}

myAuth() will check current user role and return true if they role match requested action.