yii2 deny user login on backend

14,070

Solution 1

Solved - Note: The solution is not exactly RBAC but ACF.

After searching and consulting, I found the solution at This yii2 viki.

I was unclear of RBAC behavior, in that I thought it won't let a role perform specific task before some action(login, submit etc).

Actually, RBAC will let you do whatever you try, and afterwards checks for permission and block if not permitted.

Example

There is some yard sale in a house and you are free to roam around it's front yard. The house gate/entrance doesn't have any guard at front and its not locked. You try to sneak into the house and as soon you get into the house there is some security guard inside who abruptly stops you to identify yourself, he scan your information in the house security system(permissions in DB) and doesn't find your right to be in the house. He forces you out. This guard is RBAC

I needed a guard at the front gate, who won't let anybody in unless they are allowed to. And that would be ACF.

So, now I needed a way to tell the back-end system that a specific role cannot perform a specific action beforehand (i.e. deny non-admin login at back-end), this is not possible with RBAC so, for that we could use 'matchCallback' using ACF.

Backend Rules:

        'rules' => [
            [
                'actions' => ['login'],
                'allow' => true,
            ],
            [
                'actions' => ['logout', 'index'],
                'allow' => true,
                'roles' => ['@'],
                'matchCallback' => function ($rule, $action) {
                    return Yii::$app->user->identity->isAdmin;
                }
            ],
         ]

The matchCallback on True allows the actions to be performed and on False denies the action. isAdmin is a getter function that needs to be defined in User model.

namespace /common/models/User;

const ROLE_ADMIN = 20;
public function getIsAdmin()
{
    return $this->role == self::ROLE_ADMIN;
}

I have posted the complete working code of model in This yii2 viki's comments.

Solution 2

You both first login user and then checking his role, there is no need for that. Your LoginForm model has getUser() method, find it after calling load() and validate(), and check role with authManager. Smth like this:

    /** @var LoginForm $model */
    $model = Yii::createObject('loginForm');

    if ($model->load(Yii::$app->request->post()) && $model->validate()) {
        /** @var User $user */
        $user = $model->getUser();
        if (!empty($user) && Yii::$app->authManager->checkAccess($user->getId(), 'admin')) {
            // Don't validate twice
            $model->login(false);
            return $this->goBack();
        } else {
            $model->addError('email', 'This user is not authorized for administration');
        }
    }
    return $this->render('login.twig', [
        'model' => $model,
    ]);

You also don't want to validate() LoginForm twice, so add $runValidation param to the login() method.

public function login($runValidation = true)
{
    if ($runValidation) {
Share:
14,070

Related videos on Youtube

Abdul Rehman
Author by

Abdul Rehman

Web Developer since 2012. Latest technologies, the way it's shaping and helping the future of mankind fascinates me. This gives me inspiration to code.

Updated on June 04, 2022

Comments

  • Abdul Rehman
    Abdul Rehman almost 2 years

    I have yii2 advance template with RBAC migration applied. I was trying to learn RBAC and followed the Docs 2.0.

    I have logged in using database, but the front-end and back-end both get logged in with any account. I have made 2 RBAC roles (admin, user), but can't understand or find how to

    restrict back-end to login non-admin user-role.

    The following is the code for roles. and database entries:

    namespace console\controllers;
    
    use Yii;
    use yii\console\Controller;
    
    class RbacController extends Controller
    {
        public function actionInit()
        {
            $auth = Yii::$app->authManager;
    
            // add "admin" role
            $admin = $auth->createRole('admin');
            $auth->add($admin);
    
            // add "user" role
            $user = $auth->createRole('user');
            $auth->add($user);
    
            $auth->assign($admin, 1);
        }
    }
    

    User Table:

    admin   [email protected]     20  10  1421197319  1421197319
    user    [email protected]      10  10  1421198124  1421198124
    

    Current rules:

    'rules' => [
        [
            'actions' => ['login', 'error'],
            'allow' => true,
        ],
        [
            'actions' => ['logout', 'index'],
            'allow' => true,
            'roles' => ['@'],
        ],
    
  • Abdul Rehman
    Abdul Rehman over 9 years
    Thanks 4 reply. This does not work. There are already behaviors in controller of backend. how can i make a rule so that anyone is allowed to access login but only admin is allowed to be logged in and access index page. There are only 2 pages index and login in backend. If i do action=>[login, index, error] roles=>[admin]. It will not even view the login page, bcoz current user is guest. and according to the rule an admin role is required. i have tried it. and the problem is as i explained.
  • TomaszKane
    TomaszKane over 9 years
    Ensure that you have RBAC tables in you DSN and your user "admin" have assigned role "admin". Example how to set access to actions is here: yiiframework.com/doc-2.0/guide-security-authorization.html
  • iltaf khalid
    iltaf khalid about 9 years
    I had a problem where I wanted to allow public access to index page in Yii2 backend and your code gave me that clue :) [ 'actions' => ['index'], 'allow' => true, 'roles' => ['?'], ], Thanks buddy
  • Abdul Rehman
    Abdul Rehman about 9 years
    your solution works but there is some fundamental problem. U r 1st loging a user which is not supposed to be logged in the 1st place. U r doing extra work. I already new this workaround. try my solution. Its better