magic is happening
Read Time2 Minutes, 52 Seconds

Although the authentication component of CakePHP 3 has made the life of a developer much easier but still there are some functionalities that are still needed to be done manually. One of them is login automatically if the users have checked for ‘remember me’.

To be frank auto login also known as cookie-based login is not that big deal. The real idea behind that is to make browser remember that user from a particular site has visited and if he comes back please don’t ask him/her to log in again.

By so far you must have understood that we are going to use cookies to implement the logic. So, without wasting any time lets get started

Step 1.

Add cookie component to the system. You may have noticed the best place to add a component is in the appController.php initialize action as the request handler and flash are also included there.

You can add the following line to add the cookie component.

$this->loadComponent('Cookie');

Step 2.

Now since we have cookies support with us, we can proceed further.

Now we have to make a remember me checkbox on the login page so that we can check if the user is willing to be remembered by the browser.

You can do it easily by just adding an input with type=”checkbox”. For this article name of the checkbox is “remember”

<input class="form-control" type="checkbox" name="remember"> Remember Me

Step 3.

Now we are all set for the main functionality.

Now if the user’s checks “remember me” we are going to add a secret hash in the cookies and the same hash will be assigned to the login user for future identification. To do that we only need 1 thing a “secret hash”. This can be done with the help “Security” utility.

Add the following line to appController.php

use Cake\Utility\Security;

Now create a function in app controller which will return a secret and unique hash.

function _hashGenerator()
{
        return Security::hash(rand());
}

Congratulations! We have hash now.

Step 4.

Things from here are simple from here. Below is the pseudo code for the same.

  • Check if the remember is checked
  • if checked then set a variable remember and unset the check form the request as it will create a problem in the auth identify.
  • Once the user is identified and remember is set then set the auto login. (function is mentioned below).
  • In setting autoLogin
    • generate a hash
    • assign same hash to login user
    • set the same hash in cookies.

The function to implement the above pseudo code is mentioned below (to be written in usersController.php)

if ($user = $this->Auth->identify()) {
    if ($remember) {
                    $this->_setAutoLogin($user['id']);
         }
...
function _setAutoLogin($id=null)
{
        $hash = $this->_hashGenerator();
        $this->Cookie->config([
            'expires' => '+30 days',
            'httpOnly' => true
        ]);
        $this->Cookie->write('connects', $hash);
        $user = $this->Users->get($id);
        $user->hash = $hash;
        if ($this->Users->save($user)) {
            return true;
        } else {
            return false;
        }
}

Step 5.

All set we are done now. All we have to do is add the below line at the start of the login function in usersController.php.

$this->_autoLogin();

and add the below function to usersController.php

function _autoLogin()
{
        if ($this->Cookie->read('connects')) {
            $user = $this->Users->findByHash($this->Cookie->read('connects'))->first()->toArray();
            $this->_setAutoLogin($user['id']);
            $this->Auth->setUser($user);

            return $this->redirect(['controller' => 'pages', 'action' => 'home']);
        } else {
            return false;
        }
}

See, it was that simple. If you any query or suggestion regarding the issue feel free to comment.

0 0

About Post Author

samgan

samgan excel at solving complex problems involving logic and step by step breakdown of the problem. In addition, to develop complex algorithms, he specialize in problem framing, systems design, and product development strategy. Sometimes he also enjoy public speaking.
0 %
Happy
0 %
Sad
0 %
Excited
0 %
Angry
0 %
Surprise

2 thoughts on “Auto login in CakePHP 3.x

  1. Good Article, Really informative.
    I really appreciate the efforts you are putting back in the society.
    keep doing the good work.

Leave a Reply

Your email address will not be published. Required fields are marked *

Close
Social profiles