CakePhp authentication example

One nice thing in cakePhp is that it has written nearly all the code for you. You will need to write very little code while developing your application.
Example is its scaffold functionality. I’ll cover it later on.
Another very good example is Authentication.
If you want that specific controller’s actions should only be executed after user authentication, you will need to just write a single line of code in that controller. Consider you have a controller like
<?php
class PostsController extends AppController
{
var $name = "Posts";
function view(){
}
}

And you want that only authentic user can access its view action, write
class PostsController extends AppController
{
var $name = "Posts";
var $components=array('Auth');
function view(){
}
}

 
That’s it. You can clearly see that we have only added single line of code var $component = array(‘Auth’). It tell cakePhp to allow access to any of the “postsController” action when user is authentic.
 Now if you are not authentic and write
http://localhost/cake/posts/view
it will redirect you to User’s controller=>login action.
Before accessing any of the action of the posts controller you will need to be an authentic user.
However may not want this functionality in all controllers. Web application always contains pages that can be accessed by anybody. To achieve this functionality you will need to add another function to your controller. E.g
 
class PostsController extends AppController
{
var $name = "Posts";
var $components=array('Auth');
function beforFilter(){
$this->Auth->allow('view');
}
function view(){
}
}

 we added single function beforeFilter() and single line of code $this->Auth->allow(‘view’);
beforeFilter() is an important function called cakePhp controller callback. I’ve discuss this in my previous post. It is called and executed before action executing any action within controller in which it is defined. So when you write
http://localhost/cake/posts/view
cakePhp will first call beforeFilter() and execute it and then call “view” action.
In this function we have told cakePhp that allow access to the “view” action. In this case user will be granted access regardless of authentication.
Posted in CakePhp