G
G
GONJY MONJY2020-06-23 01:21:59
Yii
GONJY MONJY, 2020-06-23 01:21:59

How to deny login to a user with a specific role in Yii2?

Hello! I did a user role check to deny login to a user whose mail is not verified. But the code doesn't work a little. the following error is thrown:
Object of class app\modules\userAuth\models\User could not be converted to string.

This code here is the role check method:

public function checkUserRole(){

        $user = User::findOne(['username' => $this->username]);
        $role = Yii::$app->authManager->getRolesByUser($user);

        if($role === "user"){
            return false;
        }
        if($role === "active"){
            return true;
        }
    }


This code here is the actionLogin in the controller:
public function actionLogin(){

        $model = new LoginForm();
        
        if(!Yii::$app->user->isGuest){
            return $this->goHome();
        }

        if($model->load(Yii::$app->request->post()) && $model->login()){
            if($model->checkUserRole() === true){
                return $this->goHome();
            } else{
                Yii::$app->user->logout();
                Yii::$app->getSession()->setFlash('error','Please, confirm your E-mail!');  
                return $this->goHome();
            }
        }

        $model->password = '';
        
        return $this->render('login', compact('model'));

    }


If anyone has come across this, please help me to solve my problem. Although it would be nice to point out my mistake, due to which the code does not work correctly.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Maxim, 2020-06-23
@GONJY_MONJY

It is not very clear why actionLogin()you use such a complex construction in the method, which, in this case, does not make much sense. In your example, you can use the function:

Yii::$app->getAuthManager()->checkAccess(32, 'admin')

This function will allow you to check access for other users. It is good practice to use errors as exceptions with a 403 error and the message:
public function actionLogin()
{
    $model = new LoginForm();
    $model->password = ''; // перенести в метод rules формы, как default

    if($model->load(Yii::$app->request->post()) && $model->login()){
        $user = User::findOne(['username' => $this->username]);
        if(Yii::$app->getAuthManager()->checkAccess($user->getId(), 'admin')){
            throw new ForbiddenHttpException('Ошибка доступа');
        }

        return $this->goHome();
    }

    return $this->render('login', [
        'model' => $model
    ]);
}

If you need to use validation for the current user, this can be easily moved into behaviors:
public function behaviors()
{
    return [
        'access' => [
            'class' => AccessControl::class,
            'rules' => [
                [
                    'actions' => ['create', 'update'],
                    'allow' => true,
                    'matchCallback' => function ($rule, $action) {
                        /** @var User $identity */
                        $identity = Yii::$app->user->getIdentity();
                        return $identity->isAdmin(); // или другая проверка
                    }
                ],
            ],
        ],
    ];
}

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

The option value of allowthe selected rule specifies whether to authorize the user or not. If none of the rules match, then the user is considered NOT authorized, and the ACF filter stops further execution of the action. By default, when the user does not have access to the current action, ACF does the following:
  • If the user is a guest, yii\web\User::loginRequired() is called which redirects the browser to the login page.
  • If the user is authorized, a yii\web\ForbiddenHttpException is thrown .

More complex rules can be placed in your filters AccessControl
Links to documentation on the topic:
  1. yii\web\User
  2. yii\rbac\ManagerInterface
  3. yii\rbac\CheckAccessInterface

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question