PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, January 13, 2022

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

 January 13, 2022     cakephp, cakephp-3.0     No comments   

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
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

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

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing