Backend login authorization with rbac

I am setting up a backend admin panel and trying to figure out a simple way to limit login authorization to admins with rbac.

I’m trying to do something like this:




$user = $model->user;

if (isset($user) && Yii::$app->user->can('adminPanel') && $model->login()) {

    return $this->goHome();



But I can’t call


Yii::$app->user->can('adminPanel')

as the user is not yet logged in. I realize I could assign roles in the user table at signup, but that is redundant with the auth_assignment table. Is there a simple way to check the user role without adding an additional column to the user table?

Use access control filter?




            'access' => [

                'class' => AccessControl::className(),

                'rules' => [

                    [

                        'allow' => true,

                        'roles' => ['adminPanel'],

                    ],

                ],

            ],



But I want to prevent a guest from logging into the admin panel if they don’t have the admin role. The filter only applies after login, right? I don’t want users with “User” role to be able to login via the admin panel at all.

Here’s what I have right now:




'access' => [

    'class' => AccessControl::className(),

    'rules' => [

        [

            'actions' => ['login', 'error'],

            'allow' => true,

        ],

        [

            'actions' => ['logout', 'index'],

            'allow' => true,

            'roles' => ['adminPanel'],

        ],

    ],

],



As it stands, users are able to login, just not redirect to index.

Ah ok, I see what you mean now.

How about logging the user in, checking the role, and logging them out right away if they’re not admin?

Yes, that would be an option. I was wondering if there might be a cleaner way, like accessing the roles somehow through the auth manager before or during login. Maybe there isn’t a way to do that.