Yii 2 redirecting to Login if Guest visit the website

前端 未结 3 1671
不知归路
不知归路 2021-01-21 19:31

I need some advice how to make redirecting to login if someone does not login into the website and he is only Guest

3条回答
  •  一向
    一向 (楼主)
    2021-01-21 20:03

    There are two options:

    1. You can use the AccessControl as mentioned by @Maksym Semenykhin
    2. You can use the option below especially when you would like the logged user to be returned to this page after login.

      public function beforeAction($action){
      if (parent::beforeAction($action)){
          if (Yii::$app->user->isGuest){
              Yii::$app->user->loginUrl = ['/auth/default/index', 'return' => \Yii::$app->request->url];
              return $this->redirect(Yii::$app->user->loginUrl)->send();
          }
      }}
      

      You can also create a custom 'Controller' class which inherits \yii\web\Controller then have all controllers that need authorization inherit your custom controller.

    On the login function, replace the redirect part with the following code:

        $return_url = empty(Yii::$app->request->get('return'))? \yii\helpers\Url::to(['/admin/default/index']) :Yii::$app->request->get('return');
        return $this->redirect($return_url);
    

提交回复
热议问题