SnapShooter Backups Server, Database, Application and Laravel Backups - Get fully protected with SnapShooter

3 simple steps to migrate Auth component to CakePHP 2.x

If you have recently migrated your CakePHP application from 1.x version to 2.x version, you might have noticed that there is a lot of changes required. In this simple tutorial, we talk about how to migrate Auth component from 1.x to 2.x, hope you will find it useful.

Introduction

Auth component is rewritten in CakePHP 2.x from ground. It has greatly improvement. Meanwhile a lot of changes need to be done in the way of using it. In this tutorial, we cover the migration guide in a very simple and generic perspective. You are strongly recommended to read the official cookbook before doing migration.

Reallocation of AppController.php

Normally Auth component is included in the application level, which is the AppController class. Before CakePHP 2.x. AppController.php is located at the directory of "app/app_controller.php". However in CakePHP 2.x, the directory is changed to "app/Controller/AppController.php". So please pay particular attention to the directory's change of the AppController.php file. Otherwise, you may end up finding that Auth component does not restrict user's access, and it does not give any error message either.

Different way of setting Auth component variables

In CakePHP 2.x, Auth component is introduced with three types of authentication handlers. So the way of setting its variables is changed, now you need to set the variables using its authentication handler as the array key. Basically if you have set variables for Auth component, you will have to rewrite it again. For more information about its variables, take a look at the cookbook.

No more auto login() magic function

If you were enjoying the ease of login() magic function, which basically does all the underline process of logging an user into your system. Too bad for you, because in CakePHP 2.x, you will have to manually log user in using login() function, and redirect user to his home page. This change is due to the confusion of login() function. So now in your UsersController.php login() function, you will have to manually do the login and redirection as below:

class UsersController extends AppController {  
    public function login() {      
        if ($this->request->is('post')) {
            if ($this->Auth->login()) {
                return $this->redirect($this->Auth->redirect());
            } else {
                $this->Session->setFlash(__('Username or password is incorrect'), 'default', array(), 'auth');
            }
        }
    }
}

The end

Hopefully this simple tutorial helped you with your development. If you like our post, please follow us on Twitter and help spread the word. We need your support to continue. If you have questions or find our mistakes in above tutorial, do leave a comment below to let us know.