Auth… Finally!
August 6th, 2008Finally, after several attempts, I have Auth working. Now I’ll attempt to explain in a simple manner, like most of the sources I found. I will also attempt to include all caveats, unlike any of the sources I found.
app/config/core.php
Place a salt value in Security.salt. I suggest using the sha1 value on my password generator page.
You may want to increase Session.timeout beyond the default 2 minutes.
app/controller/users_controller.php
uses('sanitize');
class UsersController extends AppController {
public $name = 'Users';
public $components = array('Auth');
function beforeFilter() {
Security::setHash('sha1');
}
// The AuthComponent provides the needed functionality or login, so you can leave this function blank.
function login() {
print_r($this->Auth->data);
print_r($this->Auth->password('password'))
// set users.last_login
if ((isset($_SESSION['Auth']['User']['id'])) && (is_numeric($_SESSION['Auth']['User']['id']))) {
$sql = "UPDATE users SET last_login=NOW() WHERE id=" . Sanitize::escape($_SESSION['Auth']['User']['id']);
$result = $this->User->query($sql);
}
}
function logout() {
$this->redirect($this->Auth->logout());
}
}
Make sure you add Auth to the components array of any controller you plan to have any authentication on:
public $components = array('Auth');
Also you can specify which controller methods do not need authentication like this:
function beforeFilter() {
$this->Auth->allow('index', 'results', 'animal', 'spotlight', 'breed');
}
app/model/
No model file is needed, but you need to create a database table with id, username, and password fields. Any other fields will be paced in the Auth object (inside session), like this:
[Auth] => Array
(
[User] => Array
(
[id] => 53
[first_name] => Aaron
[last_name] => Thies
[email] => athies@gmail.com
[username] => athies
[last_login] => 0000-00-00 00:00:00
)
)
You can find out what to set the password value in the users db table by using $this->Auth->password(’password’). This caused me a lot of aggravation as I was just using SHA1(’password’).
You can tweak Auth using the various Auth methods outlined here: http://book.cakephp.org/view/172/authentication. These methods can be placed inside controller::beforeFilter().
app/views/users/login.ctp
if ($session->check('Message.auth')) $session->flash('auth');
if ($session->check('Message.flash')) {
$session->flash();
}
if ($session->check('Message.auth')) {
$session->flash('auth');
}
echo $form->create('User', array('action' => 'login'));
echo $form->input('username');
echo $form->input('password');
echo $form->end('Login');
A Little Something More
During the course of getting Auth to work I learned this helpful hint.
If you ever produced this error, “Database table users for model User was not found.”, you can fix this by deleting everything in this folder: /app/tmp/cache/models










