CakePHP User Auth

I am pretty new to cakephp, I have been using it for a about a month now, mostly with the 1.1 release. Upgraded to 1.2 on this one application. It went okay, it was a simple application. The toughest part was validation and login. For those who have struggled through this as well, getting user logged in and the new validation in 1.2. Here is the source of what I did.

app/models/user.php

class User extends AppModel {

var $name = 'User';
var $useTable = 'users';
var $validate = array(
'username' => array(
VALID_NOT_EMPTY,
'alphanumeric' => array(
'rule' => 'alphanumeric',
'message' => 'Username may only consist of letter and numbers'),
'length' => array(
'rule' => array('between', 6, 20),
'message' => 'Username must be between 6 and 20 characters in length'),
'unique' => array(
'rule' => 'checkUniqueUser',
'message' => 'Username already taken'),

),
'password' => array(
VALID_NOT_EMPTY,
'length' => array(
'rule' => array('minLength', 6),
'message' => 'Password must be at least 6 characters in length'),
),
'email' => array(
'email' => array(
'rule' => 'email',
'message' => 'Invalid Email',
),
'unique' => array(
'rule' => 'checkUniqueEmail',
'message' => 'Email already in use',
),
),
);

//The Associations below have been created with all possible keys, those that are not needed can be removed
var $hasMany = array(
'Comment' => array('className' => 'Comment',
'foreignKey' => 'user_id',
'dependent' => false,
'conditions' => '',
'fields' => '',
'order' => '',
'limit' => '',
'offset' => '',
'exclusive' => '',
'finderQuery' => '',
'counterQuery' => ''
)
);

function checkUniqueUser($data) {
return $this->isUnique(array('username' => $this->data['User']['username']));
}

function checkUniqueEmail($data) {
return $this->isUnique(array(’email’ => $this->data['User']['email']));
}

// The basic login stuff
function validateLogin($data)
{
$user = $this->find(array(’username’ => $data['username'], ‘password’ => md5($data['password'])), array(’id’, ‘username’));
if(empty($user) == false)
return $user['User'];
return false;
}

}
?>

app/controllers/users_controller.php

class UsersController extends AppController {

var $name = 'Users';

// This is to know
function login()
{
if(empty($this->data) == false)
{
if(($user = $this->User->validateLogin($this->data['User'])) == true)
{
$this->Session->write(’User’, $user);
$this->Session->setFlash(’You\’ve successfully logged in.’);
$this->redirect(’/');
exit();
}
else
{
$this->Session->setFlash(’Sorry, the information you\’ve entered is incorrect.’);
exit();
}
}
}

function logout()
{
$this->Session->destroy(’User’);
$this->Session->setFlash(’You\’ve successfully logged out.’);
$this->redirect(’/');
}

function view($id = null) {
if (!$id) {
$this->Session->setFlash(__(’Invalid User.’, true));
$this->redirect(array(’action’=>’index’));
}
$this->set(’user’, $this->User->read(null, $id));
}

function add() {
if (!empty($this->data)) {
$this->User->create();
if ($this->User->save($this->data)) {
$this->Session->setFlash(__(’The User has been saved’, true));
$this->redirect(array(’action’=>’index’));
} else {
$this->Session->setFlash(__(’The User could not be saved. Please, try again.’, true));
}
}
}

}
?>

app/app_controller.php

class AppController extends Controller {

var $helpers = array('Html', 'Form', 'Javascript', 'Ajax');

function checkSession()
{
// If the session info hasn't been set...
if (!$this->Session->check('User'))
{
$this->Session->setFlash('The URL you\'ve followed requires you login.');
$this->redirect('/users/login');
}
}
}

?>
And then just call $this->checkSession() in your controllers to force a login

hutchic
March 16th, 2008 11:12 pm

I know I’m paranoid but I allways NULL out sensitive information before creating a session ie:

$user['password'] = NULL;
$this->Session->write(’User’, $user);

but that’s just my personal preference. I’d also suggest a way to set a redirect in the login functionality. In checksession if there is no user session and the action requested wasn’t the login /logout action or any others that would infinite loop set a session variable called redirect. Then on login use that variable for $this->redirect …. also proper tabbing would make this more readable ;)

March 17th, 2008 5:21 am

Sorry for the no tabs. Just had a little problem with the wordpress editor. I am working on a better login redirect, to redirect to the page that they were trying to go to.

I don’t think it infinite loops (the code is in use), I only call checkSession on pages where login is required.

andru
March 31st, 2008 5:57 am

Also for your validation, you could just make one method to check the uniqueness of a field, and pass the field name in as a parameter ;)

March 31st, 2008 7:23 am

thanks audru, that is a good idea.

Manish Sanger
September 24th, 2008 8:48 am

Hi
tried this method using request handler, but it loads the login page in a updating div.
Please help.
Thanks in advance.

September 24th, 2008 9:26 am

If you are using cake 1.2RC2, the manual is the only way to go. It’s the only good way to do auth.

http://manual.cakephp.org/view/172/Authentication

*Name
*Mail
Website
Comment