In previous post I discuss the basic and general usage of cakephp authentication. In this post I am going to code and explain how to write a simple sign up application. This article will not only cover authentication but also models, forms and view etc.
So lets get started.
First of all create a table named “user” by executing the following sql query.
CREATE TABLE 'user' (
'id' int(11) NOT NULL auto_increment,
‘username’ varchar(30) NOT NULL,
‘password’ varchar(30) NOT NULL,
‘email’ varchar(255) NOT NULL,
‘created’ datetime NOT NULL,
‘modified’ datetime NOT NULL,
PRIMARY KEY (‘id’)
)
Now create a model in app/models with name user.php and write following code in that model.
<?
class User extends AppModel
{
var $name=’User’;
var $useTable=’user’;
var $validate=array(
‘username’ => array(
‘notempty’ => array(
‘rule’ => array(‘minLength’,1),
‘required’ => true,
‘allowEmpty’ => false,
‘message’ => ‘Enter Username’
),
‘checkUnique’ => array(
‘rule’ => array(‘checkUnique’,'username’),
‘message’ => ‘Name already taken. Choose another.’
)
),
‘password’=>array(
‘notempty’ => array(
‘rule’ => array(‘minLength’,1),
‘required’ => true,
‘allowEmpty’ => false,
‘message’ => ‘Enter Password’
),
‘passwordsimilar’=>array(
‘rule’ => ‘checkPasswords’,
‘message’ => ‘Passwords must match.’
)
),
‘email’ => array(
‘rule’ => ‘email’,
‘required’ => true,
‘allowEmpty’ => false,
‘message’ => ‘Enter valid email’
),
);
function checkUnique($data,$fieldName){
$valid = false;
if(isset($fieldName)&&($this->hasField($fieldName))){
$valid = $this->isUnique(array($fieldName=>$data));
}
return $valid;
}
function checkPasswords($data) {
if($data['password'] == $this->data['User']['password2hashed'])
return true;
return false;
}
}
Explanation:
First we extend our model form cakePhp AppModel class. By doing so, we inherit all the method of that class.
Next we define name of the model and the table (database table) used by this model class. We then define our validate array that is crucial for validating submitting data against the database table. This will insure that the data will not be inserted until and unless valid.
You can put as many table fields as you want and cake will do the rest for you.
You can clearly see in this array that we are defining validation rules for some of the table fields. The first one is the username. We will not insert data in the database until user enter a valid and unique name. if user enter empty username through form. He will be notified with error message. Similarly if he enter a name which already exist in the table another error message will be display saying that “username already taken choose another one”. Although cake provide us validation rules for “allowEmpty” and “required” to ensure that user don’t left fields empty, however to check uniqueness we will need to define our own rule. The lines
'checkUnique' => array(
‘rule’ => array(‘checkUnique’,'username’),
‘message’ => ‘Name already taken. Choose another.’
)
in our validate array call our custom defined method
function checkUnique($data,$fieldName){
}
$valid = false;
if(isset($fieldName)&&($this->hasField($fieldName))){
$valid = $this->isUnique(array($fieldName=>$data));
return $valid;
}
in this function we check if the $fieldName is passed and is in the User table. If yes then we check its uniqueness by calling a mehod isUnique() provided by cakePhp and passing it the field data. If the name is not already taken, isUnique() method will return true, false otherwise. And at the end of the function we return this value.
Next we define validation rules for password field. Make sure that it is not empty and matched to the “confirm password”. Here again we define our own function for ensuring that both password match. The function
function checkPasswords($data) {
if($data['password'] == $this->data['User']['password2hashed'])
return true;
return false;
}
check that both password match. If not it will return false, data will not be inserted in the database table and user will be notified with “password must match” error.
Next we define validation rule for email field and make sure that user enter a valid email address.
That’s it we have now defined our own model and will go forward to create our controller and call this model on appropriate action.
So lets define our own controller.
In app/controllers create users_controller.php and write following code
<?php
class UsersController extends AppController {
var $name = ‘Users’;
var $uses=array(‘User’);
var $components = array(‘Auth’);
function beforeFilter(){
$this->Auth->allow(’signup’);
}
function signup(){
if (!empty($this->data)) {
if(isset($this->data['User']['password2']))
$this->data['User']['password2hashed'] =$this->Auth->password($this->data['User']['password2']);
$this->User->create();
if ($this->User->save($this->data)) {
$this->Session->setFlash(‘Congratulations! You have signed up!’);
$this->redirect(array(‘controller’ => ‘questions’,'action’=>’home’));
} else {
$this->Session->setFlash(‘There was an error signing up. Please, try again.’);
$this->data = null;
}
}
}
}
Explanation:
We first extend our controller form AppController, define its name, model and components its uses.
Next we define beforFilter() method and allow singup action to be executed whether or not user is authentic.
The action “signup” is important. We are putting most of our code in this action.
First we check if the form is posted by checking the data as $this->data. If it is not empty we then check that the passowrd2 is set. If it is true then we create hashed password with the statement
$this-> Auth->password($this->data['User']['password2']);
and assign it to the $this->data['User']['password2hashed'];
this is important to save hashed password.
Next we call $this->User->create() to load the model and prepare it for the next action.
We then call save action of the model as
$this->User->save($this->data) by passing it the data posted. This function return true if data is successfully inserted in the database table.
If it return true we set flash message and redirect to the home page of the question controller otherwise we set error message to flash helper and set posted data to null.
We have now defined our model and controller, now its time to write our view code.
Create views/users/signup.ctp and write the following code in it.
<?php if($form->isFieldError('User.username')) e($form->error('User.username', null, array('class' => 'message'))); ?>
<?php if($form->isFieldError(‘User.password’)) e($form->error(‘User.password’, null, array(‘class’ => ‘message’))); ?>
<?php if($form->isFieldError(‘User.email’)) e($form->error(‘User.email’, null, array(‘class’ => ‘message’))); ?>
<h2>Sign Up</h2>
<?php e($form->create(‘User’, array(‘action’ => ’signup’)));?>
<fieldset>
<label for=”UserUsername” class=”usernamelabel”><span>
Your Name</span></label>
<?php e($form->text(‘username’, array(‘class’=> ‘fullwidth’))); ?>
<label for=”UserEmail” class=”emaillabel”><span>Your Email
</span></label>
<?php e($form->text(‘email’, array(‘class’=> ‘fullwidth’))); ?>
<label for=”UserPassword” class=”passwordlabel”><span>
Password</span></label>
<?php e($form->password(‘password’, array(‘class’=> ‘fullwidth’))); ?>
<label for=”UserPasswordRepeat” class=”passwordrepeatlabel”>
<span>Re Password</span></label>
<?php e($form->password(‘password2′, array(‘class’=> ‘fullwidth’))); ?>
<?php e($form->submit(‘Sign Up’, array(‘div’ => false,
‘class’ => ’submitbutton’))); ?>
</fieldset>
<?php e($form->end()); ?>
The code seem a bit complex, however it is very simple if you break it.
In the first three line we check for the error in case of submitting un valid form. If any of the error occur we display it.
Next we create our our form and set its action.
That’s it we have now create a simple sign up application. If you point to
http://localhost/cake/users/signup/
you will see a simple sign up form. You can fill it and it will do everything for you.
Any question feel free to ask.