In case you haven't read the previous post, I'll walk through the entire process. Firstly we need a database table to store the users:
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;
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:
<?php
class UserModel extends AppModel {
}
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:
<?php
App::uses('AppController', 'Controller');
class UsersController extends AppController {
public $name = 'Users';
public $uses = array('User');
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());
}
}
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:
<?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');
?>
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!
Published on Sep 18, 2012
Tags: CakePHP Tutorial
| AuthComponent
| PHP