#functionality #authentication #cakephp #php

Auto login in CakePHP 3.x

Table Of Content


  1. Step 1.
  2. Step 2.
  3. Step 3.
  4. Step 4.
  5. Step 5.

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.

Most Viewed Posts


Must Read


January 28, 2022

#AppImage #linux

How to Add AppImage Application to Menu in Ubuntu (Linux)

AppImages are the most easiest to run compared.The challenging task is to make the AppImage accessible globally through he system like an installed application (in the menu)

Reading time: less than a minute
How to Add Laravel Pint to VS Code Formatter
June 24, 2022

#code-quality #vscode #laravel-pint #laravel

How to Add Laravel Pint to VS Code Formatter

I have been using the unsatisfactory formatters from a long time. All of them have one thing but lack other. Laravel Pint is one who has it all, combining it with vscode is like proving you laravel project a super power.

Reading time: 2 minutes
March 24, 2021

#express js #node #node js #sequelize #mysql

How to create model association in Sequelize - express JS / Node JS

In the very initial days of my work in Node JS if faced this issue. Though Sequelize provide a great ORM for MySQL but the association within the models is a bit tricky.

Reading time: 2 minutes
December 14, 2021

#database #javascript #sequelize #npx

Sequelize CLI Commands

list of Sequelize CLI commands which comes handy, while working on a project.

Reading time: 1 minute
How to create a progressive web app (PWA) in laravel 5.* and above
July 07, 2019

#functionality #pwa #javascript #laravel

How to create a progressive web app (PWA) in laravel 5.* and above

The progressive web app is the new trend as well as the need for the present time. I hope before getting in the “HOW” part you know what is exactly a PWA

Reading time: 4 minutes
How to create a progressive web app (PWA) in laravel 5.* and above
July 07, 2019

#functionality #pwa #javascript #laravel

How to create a progressive web app (PWA) in laravel 5.* and above

The progressive web app is the new trend as well as the need for the present time. I hope before getting in the “HOW” part you know what is exactly a PWA

Reading time: 4 minutes
September 06, 2019

#cli #authentication #laravel

PHP artisan make:auth in laravel 6.0

As you may have known by now that laravel 6.0 has been out. Though it's expected to have a lot of changes in the major release but in 6.0 there are not that many changes.

Reading time: less than a minute
November 02, 2020

#blog #php #laravel

How to get started with laravel wink for creating a blog

There are a number of options available for purpose of blog creation but if you are a developer non of them are as satisfying as laravel wink.

Reading time: 1 minute
May 15, 2019

#package #cakephp

Cristeena Documentation

Hello there, this is the official explanation documentation for project cristeen. In here we will discuss all the aspects for cristeen and how it can be used at her best for the development of the web application

Reading time: 1 minute
December 20, 2018

#functionality #log #cakephp #php

How to make log daily in CakePHP 3.x

As you may know according to the default configuration of CakePHP the debug and error log is generated in the same file. But this can be changed in a few simple steps

Reading time: less than a minute
mohammed-samgan-khan

Hi, I am Samgan, I know the adds are bit annoying but i hope you understand. Talking about me, I excel at solving complex problems involving logic and step by step breakdown of the problem. Besides, to develop complex algorithms, I specialize in problem framing, systems design, and product development strategy. Sometimes I also enjoy public speaking.