CakePHP: User Authetication
Posted: August 14th, 2009 | Author: Kornelije Sajler | Filed under: CakePHP, Learnaholism, The Clash of MVC Frameworks | Tags: CackePHP, MVC, MVC Frameworks, MySQL, PHP, XAMPP | 9 Comments »It is time for some coding. The first MVC Framework is CakePHP, because the final application for my firm will be in PHP. I will not write about installing and configuring CakePHP and I think that readers have notion of MVC Frameworks and how they work.
System requirements for CakePHP:
- PHP 4.3.2+ (PHP 5 recommended)
- Apache Web Server with mod_rewrite enabled (I recommend installing XAMPP)
- Supported Database – MySQL in my case
CakePHP Folder Structure
Before begin there is need for explanation of CakePHP structure. When you download cake and extract it you should get this folder structure:
- app – the folder where our application code shall reside.
- cake – core CakePHP files, where magic resides.
- vendors – where to place third-party PHP libraries you need to use with your CakePHP applications.
The app directory is only relevant to this application and it has this structure:
- config – database connection details, bootstrapping, core configuration files should be stored here.
- controllers – contains your application’s controllers and their components.
- locale – stores string files for internationalization.
- models – contains your application’s models, behaviors, and datasources.
- plugins – contains plugin packages.
- tests – unit test for the application.
- tmp – this is where CakePHP stores temporary data.
- vendors – any third-party classes or libraries should be placed here.
- views – presentational files are placed here: elements, error pages, helpers, layouts, and view files.
- webroot - in a production setup, this folder should serve as the document root for your application. Folders here also serve as holding places for CSS stylesheets, images, and JavaScript files.
So, when I post source for this application it’ll be only app directory!
But, before we begin, you should create a MySQL database in my case “cake” and create the users table with this script:
CREATE TABLE `users` ( `id` int(11) NOT NULL AUTO_INCREMENT, `username` varchar(8), `password` varchar(64), PRIMARY KEY (`id`) ) ENGINE=InnoDB;
We also need to tell CakePHP where to find database. In app/config there is a file database.php.default which should be renamed in to database.php and add database information, in my case:
<?php
class DATABASE_CONFIG
{
var $default = array(
'driver' => 'mysql',
'persistent' => false,
'host' => 'localhost',
'login' => 'root',
'password' => 'lida',
'database' => 'cake',
'prefix' => '',
);
}
?>
Note: Here is only default configuration for database, test configuration is not important for now!
Authentication
CakePHP in its Core Components has a Authentication – AuthComponent is used for creating authentication easily and quickly. The components in cake are added to the list of components in your controller. Since we want to use authentication component for all of our controllers we shall create AppController as our global controller for application:
<?php
class AppController extends Controller
{
var $components = array('Auth');
}
?>
Note: The AppController is not added to the app/controller directory where controllers reside, instead it is in root of app directory.
User Model
Since user as entity is for its self, model is very simple. It consists of $name attribute, set to the controller name. This is only important for PHP 4, even though I use PHP 5, we shall declare the $name attribute only.
Users Controller
The user controller is where our actions reside. We have this actions for user:
- index – only redirects to a login action/page.
- register - serves only for registration and to put some users to test login. Totally insecure and will not be a part of application. Password will be given to our users, and there will be no registration available!
- login – authenticate the user and if Username/Password input is valid, redirects user to the main page.
- logout – logout the user from application.
Because we add AuthComponent to AppController, then authentication is for all application. In user controller we add this snippet of code:
function beforeFilter()
{
$this->Auth->allow('register');
}
The Before Filter is added to allow registration of users, and this is only for test!
Login
function login()
{
if(isset($this->data['User']))
{
if($this->Auth->login($this->data['User']))
{
$this->redirect('/');
}
$this->flash("Username/Password is incorrect");
}
}
Logout
function logout()
{
$this->Auth->logout();
/* $this->flash('You are now logged out.'); */
$this->redirect('login');
}
This code is very straight forward and it explain itself.
User Views – Presentation
First and foremost the views are inside the app/views/{NameOfController} folder in our case the folder is users. The extension for CakePHP view (presentation) files is .ctp and they are with name of controller actions. Since index and logout actions have no reason to have presentation files we have only presentation for register and login actions. But first we have to include some presentational helpers to ease our working with HTML and Forms. Helpers are included within each controller. To use presentational helpers for user views we have to add this line of code to our UserController:
var $helpers = array('Html', 'Form');</pre>
<h3>Register.ctp</h3>
<pre class="brush:php"><?php
echo $form->create('User', array('action' => 'register'));
echo $form->input('username');
echo $form->input('password');
echo $form->input('password_confirm', array('type' => 'password'));
echo $form->submit('Register');
echo $form->end();
?></pre>
<h3>Login.ctp</h3>
<pre class="brush:php"><?php
$session->flash('auth');
echo $form->create('User', array('action' => 'login'));
echo $form->inputs(array(
'legend' => __('Login', true),
'username',
'password'
));
echo $form->end('Login');
?>
Both of views uses entirely helpers, which are also very self-explanatory.
We only have to test our login and logout and for that we need to have main page. Since we don’t want to create Home Controller and Index action we can add in our app/views/pages, a page home.ctp, which will be our home page when we call our domain. And all we have to do is put the logout link:
<?php
echo $html->link('Logout', array('controller' => 'users', 'action'=>'logout'));
?>
I think that would be all for User Authentication, and bear in mind to remove this insecure registration. It is only for testing and easily adding users to database. Next, we shall start to add strong entities like Clients and Voucher Types. Since then if you have any question please, ask or go to the manual of CakePHP for more informations.
Source code for this post: app.zip




Recent Comments: