Answer the question
In order to leave comments, you need to log in
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;
}
}
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'));
}
Answer the question
In order to leave comments, you need to log in
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')
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
]);
}
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']
],
],
],
];
}
allow
the 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:AccessControl
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question