Thursday, January 13, 2022

[FIXED] common method to check status before all controllers in CakePHP

Issue

I have an application in cakephp where a logged in user must have a status of active otherwise it should redirect to a controller where user must have submit his application.

Actually i want to implement on all the controllers whenever a user tried to access any controller action it should check the status automatically and if status is not active it should redirect to the user application. How can i implement it in the Appcontroller.

My Appcontroller contents are :

public function initialize()
    {
        parent::initialize();

        $this->loadComponent('RequestHandler', [
            'enableBeforeRedirect' => false,
        ]);
        $this->loadComponent('Flash');
        $this->loadComponent('Auth', [
            'authError' => 'You have been logged out due to period of inactivity.',
            'loginAction' => [
                'controller' => 'Users',
                'action' => 'login'
            ],
            'loginRedirect' => [
                'controller' => 'Users',
                'action' => 'dashboard'
            ],
            'logoutRedirect' => [
                'controller' => 'Users',
                'action' => 'logout'
            ],
        ]);

Solution

You can use beforeFilter Method in your AppController to perform such a check. Suppose the name of your Controller where you want to Redirect is YourController, then your method should look like.

    public function beforeFilter( $event ) {

        if ($this->Auth->user()) { //If User is logged in.
            if ( $this->request->controller != 'YourController' ) { //If Request Controller is other than YourController
                $status  = $this->Auth->user('status'); //Get the Status
                if( $status != 'active' ) { //If Status is not active
                    //Redirect Here
                    return $this->redirect(
                        ['controller' => 'YourController', 'action' => 'index'];
                    );                  
                }   
            }
        }
    }



Answered By - ascsoftw

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.