Well, since one of my most popular all-time blog posts is Login system with CakePHP in under 10 minutes I think it’s time that I update it to version 2.x (currently 2.2 at the time of writing). The original post was probably written for version 1.2 or 1.1 and there have been several changes made, especially with breaking changes to the AuthenicateComponent.
The beautiful part is the changes are extremely limited. In fact, only the UsersController requires a few minor changes.
[code]
CREATE TABLE IF NOT EXISTS `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`first_name` varchar(150) NOT NULL,
`last_name` varchar(150) NOT NULL,
`email` varchar(150) NOT NULL,
`username` varchar(20) NOT NULL,
`password` varchar(100) NOT NULL,
`created` datetime NOT NULL,
`modified` datetime NOT NULL,
PRIMARY KEY (`id`),
KEY `email` (`email`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
[/code]
Once the users table is created in your database, a model is required as well. Create a new file called UserModel.php inside of your app/Model directory:
[code]
<?php
class UserModel extends AppModel {
}
[/code]
Next a controller is required to display and execute the login process. Create a new file called UsersController.php inside of your app/Controller directory:
[code]
<?php
App::uses(‘AppController’, ‘Controller’);
class UsersController extends AppController {
public $name = ‘Users’;
public $uses = array(‘User’);
// Pass settings in $components array
public $components = array(
‘Auth’ => array(
‘loginAction’ => array(
‘controller’ => ‘users’,
‘action’ => ‘login’,
),
‘authError’ => ‘Did you really think you are allowed to see that?’,
‘authenticate’ => array(‘Form’)
)
);
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’);
}
}
}
public function logout() {
return $this->redirect($this->Auth->logout());
}
}
[/code]
And finally a view is required to display the login form. Create a new file called login.ctp and place it inside of your app/View/Users folder:
[code]
<?php
echo $this->Session->flash(‘auth’);
echo $this->Form->create(‘User’);
echo $this->Form->input(‘username’);
echo $this->Form->input(‘password’);
echo $this->Form->end(‘Login’);
?>
[/code]
That’s it! 90% of this code is completely the same as the original CakePHP login post, makes it nice and easy to stay on top of the new updates!