Menus

Saturday, 1 August 2015

Yii2 global filter/behavior to force user to authenticate first



you can add global behavior to your config:

add the following code below 'components' => [...]

(Example  to add path - backend\config\main.php)

Globally set redirect to login for guest users in every controller


 'as beforeRequest' => [
    'class' => 'yii\filters\AccessControl',
    'rules' => [
        [
            'actions' => ['login', 'error'],
            'allow' => true,
        ],
        [

            'allow' => true,
            'roles' => ['@'],
        ],
    ],
],



Redirect to login for guest users in every controller


   if(Yii::app()->user->isGuest){
     //not logged user
    }else{
     //loggedin user
    }


Examples

public function beforeAction()
{
       if (Yii::app()->user->isGuest)
            $this->redirect(Yii::app()->createUrl('user/login'));

       //something code right here if user valided
}



        {
                
       if (Yii::app()->user->isGuest)
        $this->redirect(Yii::app()->createUrl('site/login'));
        else
        $this->render('index');
        }




Yii2 concept-configurations

2 comments:

  1. Nice and good article. It is very useful for me to learn and understand easily. Thanks for sharing your valuable information and time. Please keep updatingAzure Online Training Bangalore

    ReplyDelete