Prevent multiple login CakePHP3

724 Views Asked by At

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?

2

There are 2 best solutions below

3
Marc Bien Go On BEST ANSWER

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.

2
Thennarasan On

AuthComponent::identify()

You need to manually call $this->Auth->identify() to identify the user using credentials provided in request. Then use $this->Auth->setUser() to log the user in, i.e., save user info to session. When authenticating users, attached authentication objects are checked in the order they are attached. Once one of the objects can identify the user, no other objects are checked. A sample login function for working with a login form could look like:

public function login()
{
if ($this->request->is('post')) {
    $user = $this->Auth->identify();
    if ($user) {
        $this->Auth->setUser($user);
        return $this->redirect($this->Auth->redirectUrl());
    } else {
        $this->Flash->error(__('Username or password is incorrect'), [
            'key' => 'auth'
        ]);
    }
}
}

The above code will attempt to first identify a user by using the POST data. If successful we set the user info to the session so that it persists across requests and then redirect to either the last page they were visiting or a URL specified in the loginRedirect config. If the login is unsuccessful, a flash message is set.

Refer this Authentication Session