Put a restriction on access to the action controller, prescribed the following rule:

 [ 'allow' => true, 'actions' => ['login' , 'registration'], 'roles' => ['?'], ], 

Everything works correctly, but how can you make it so that when a rule is not executed (that is, a logged in user goes through the hook), a non-standard warning of the type is thrown :

Error: yii \ web \ ForbiddenHttpException:

and showed a definite page?

  • Catch him. Try catch - Naumov
  • @Naumov, in every action? - Maybe_V
  • I'm not good at yui but I think the controller has something like the type of accessibility method - Naumov

1 answer 1

Use the AccessControl.denyCallback property if the handler is the same for all rules:

 'access' => [ 'class' => AccessControl::className(), 'rules' => [ [ 'actions' => ['login' , 'registration'], 'allow' => true, 'roles' => ['?'] ] ], 'denyCallback' => function($rule, $action) { Yii::$app->session->setFlash('info', 'Вам сюда нельзя!'); return $action->controller->redirect('/site/index'); }, ] 

or AccessRule.denyCallback , if you need a specific handler for a specific rule:

 'access' => [ 'class' => AccessControl::className(), 'rules' => [ [ 'actions' => ['login' , 'registration'], 'allow' => true, 'roles' => ['?'], 'denyCallback' => function($rule, $action) { Yii::$app->session->setFlash('info', 'Вам сюда нельзя!'); return $action->controller->redirect('/site/index'); }, ] ], ] 
  • Thanks for the answer) this solution suits me)! But the second example for some reason does not work! throws away that without him) - Maybe_V
  • one
    Thanks, I already figured out what was wrong! works when 'allow' => false! And you can still tell how you can handle the error in the controller action! That in each action not to catch try-catch! For example, when invoking each action, check some parameters? - Maybe_V