powered by Slim Framework
enhanced by Nesbot.com

CakePHP: Login System using the Authentication Component

Published on Aug 25, 2011 by Jamie Munro

When you need to ensure that a user is both registered and logged in to view a specific action in your controller, CakePHP provides an Authentication component to help manage the process.



Assumptions



  • You have an existing CakePHP project created

  • You have an existing database created (it can be updated)

  • Your application is configured to connect to your database

  • You have some basic database knowledge (to create new tables)


To create a login system, your website must have a table that will contain a list of active users typically a users table. Once the table is created, the ability to add users is needed. To avoid any unnecessary work, I always like to scaffold my models, controllers, and views.

If you are not familiar with scaffolding in CakePHP, check out this article on scaffolding with CakePHP. If you are already familiar with scaffolding, let's move ahead.

Taken from the above mentioned scaffolding article, is a basic users table that contains a field for both the username and password fields:


CREATE TABLE `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`first_name` varchar(150) NOT NULL,
`last_name` varchar(150) NOT NULL,
`email` varchar(150) NOT NULL,
`username` varchar(20) NOT NULL,
`password` varchar(100) NOT NULL,
`created` datetime NOT NULL,
`modified` datetime NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB


With the table created, scaffold your User model, UsersController, and your views that will allow new users to register.

When the above files have been created, the UsersController requires some new functions as well as components to be included. Also, a beforeFilter function is added to tell the Authentication component what views can be accessed without logging in.


<?php
class UsersController extends AppController {
var $name = 'Users';
var $components = array('Auth');

function beforeFilter() {
parent::beforeFilter();
$this->Auth->allow('add','login');
}

// The index, add, edit, view, and delete functions
// have been removed for simplicities sake, be sure
// to leave this included in your UsersController
// 

function login() {}

function logout() {
$this->redirect($this->Auth->logout());
}
}


The above example contains an abridged UsersController with several new functions: beforeFilter, login and logout. No code is required in the login function because the Authentication component performs all of the logic to validate a login request. The logout function performs a redirect to the default page specified after logging out (defined further below) as well as calls the logout function from the Authentication component to ensure the session is cleared properly. The beforeFilter function only allows the add and login functions; all other functions in this controller will redirect the user to the login page if they are not already logged in.

In this example, the allow function is added directly in the UsersController. I typically place this in one of two spots: AppController or each individual controller. Since this example only contains one controller, the latter will be used. I also find this provides a bit more control since the actions allowed are controller specific and not globally defined.

To display the login form, a new view must be created. This view should be called login.ctp and placed within your views/users directory:


<p>If you have already registered, use the login form below  OR  you can <?php echo $this->Html->link('Register Now', array('action'=>'add', 'controller'=>'users'));?>.</p>
<?php
echo $this->Session->flash('auth');
echo $this->Form->create('User');
echo $this->Form->input('username');
echo $this->Form->input('password');
echo $this->Form->end('Login');
?>


At this point, the login system will be fully functional using the default options for the Authentication component. If you wish to learn more about setting different options for things like the loginAction, fields used for login, userModel, and more review the CakePHP book on Setting Auth Component Variables.

Summary


The Authentication component contains a lot of properties that can be customized to suit your needs. For example, if you have a different model other than the User model it can be changed. Same with the fields used for login, e.g. use email and password instead. Finally, the allow function with the Authentication component is what defines the actions that can be accessed without logging in. If you wish to globally define the actions, create or update your AppController and place it in the beforeFilter; otherwise, place it in each individual controller as done above.

Tags: PHP | cakephp

<- MVC3: Login System with the AuthorizeAttribute  Home CSS3: Custom Fonts using @font-face -> 
blog comments powered by Disqus