CakePHP: User Authetication

Posted: August 14th, 2009 | Author: | Filed under: CakePHP, Learnaholism, The Clash of MVC Frameworks | Tags: , , , , , | 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:CakePHP logo

  • 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


The Clash of MVC Frameworks!

Posted: August 6th, 2009 | Author: | Filed under: The Clash of MVC Frameworks | Tags: , , , , , , , , , , , , , | 3 Comments »

MVC Architecture

Today, I have been bumped by an wild idea to make a comparison between “most popular”  MVC frameworks. Idea is to create simple web application but it will have at least one many-to-many relationship in it . The application will be something that I got on my job to make, and because of  its OS architecture (Linux)  we decide to be a PHP application. It is fairly simple and tomorrow when I got my mind set it on more for this application I’ll make an data model.

Initially I wanted to be done with Zend Framework but we have an Debian machine for this application, and even after upgrade it had a PHP version 5.2.0 (first he had 4.4.4?!!!), but for Zend Framework prerequisite is PHP version 5.2.4+.

So, today I started coding with CakePHP, and I didn’t try to copy/paste code. I write all, and had a lots, lots and lots of errors. Uh, this PHP (for me) is so unnatural to write. Funny, I had most of errors on forgetting to add semicolon on the end (but almost never have this problem in C#), and else I had problems with OOP syntax in PHP (which I totally dislike), uh, so many errors. Probably because I’ve been coding with PHP but very rarely OOP related, most of , was as with all others so called ‘spaghetti code’. And by all means I really didn’t mean to spit and tell that PHP is bad language, because it is highly used and it can be learned very fast, and it is also very powerful especially since PHP 5, but it is missing some language elegance. And for sure CakePHP is a great MVC Framework…

Ok, enough about PHP and me, back to MVC frameworks. Idea is to make this little application in this MVC frameworks:

As you can see there will be no true Java MVC like Spring because all of this frameworks mentioned up are (for me) clones of Ruby on Rails and they are RAD frameworks or ones for quick development of web application. Driven by Convention over Configuration (CoC) paradigm which Java MVC frameworks very lacks!  But believe me I have nothing against Java frameworks, they prove themselves through years and I would really like to do something in Spring or Spring.NET! And maybe I shall one day…

If I forget some good framework, please tell it or you would rather see some other framework instead of this. Write them then, don’t be shy?