Search code examples
cakephp-3.0multiple-login

Prevent multiple login CakePHP3


I have finished the CakePHP3 Blog tutorial. Now I want to prevent users from multiple login on same computer. I mean, after having logged in, the user has to log out in order to access the log in action again. How can I do that?


Solution

  • Had the exact same issue here's how I fixed it. In your AppController, add this to your initialize function:

    $this->loadComponent('Auth', [
            'authenticate' => [
                'Form' => [
                    'fields' => [
                        'username' => 'username',
                        'password' => 'password'
                    ]
                ]
            ],
            'loginAction' => [
                'controller' => 'Users',
                'action' => 'login'
            ],
        ]);
    

    This basically forces the user to log-in before anything else.

    And in the controller that handles the login I added this:

    if($this->Auth->user()){
            $this->Flash->error(__('You are already logged in!'));
            return $this->redirect(['controller' => 'index']);
        }
    

    This checks if there is already a user logged in and, if so, is redirected to the home page.