How to Apply Auth Component in CakePHP

Auth Component :-

Auth Component allow authentication on our web app. it prevent user to access personal page which required to login into site. Auth basically filter page according to access / prevent policy.
Let start with how to implement Auth Component :-
First : i am using table following table and use CakePHP 2.x Version.
    CREATE TABLE `test`.`users` (
    `id` INT( 5 ) NOT NULL AUTO_INCREMENT ,
    `username` VARCHAR( 40 ) NOT NULL ,
    `password` VARCHAR( 40 ) NOT NULL ,
    `status` ENUM( 't', 'f' ) NOT NULL DEFAULT 't',
    `created` DATETIME NULL ,
    `modified` DATETIME NULL ,
    PRIMARY KEY ( `id` )
    ) ENGINE = InnoDB;

Configuring Components in CakePHP
Step 1:
Auth component is already put inside CakePHP library. so we need to just add into our controller.
Include Auth Component into your controller.
    class YourController extends AppController
    {
    public  $components = array('Auth');
    .......
    }
it could be better to add Auth Component into AppController because it apply to whole web application
    class AppController extends Controller
    {
    
    public  $components = array('Auth');
    .......
    
    }
Step 2:
if you have some other field rather then `username` and `password` then create configure aur settings in beforeFilter() of Controller otherwise skep it.
    function beforeFilter()
    {
        $this->Auth->fields = array(
            'username' => 'YOUR USERNAME FIELD NAME',
            'password' => 'YOUR PASSWORD FIELD NAME'
        );
    }
Step3: 
Setting up login redirect and logout redirect action.
    function beforeFilter()
    {
     $this->Auth->loginRedirect = array('controller' => 'Users', 'action' => 'myaccount');
     $this->Auth->logoutRedirect = array('controller' => 'index', 'action' => 'index');
    }
after above steps your Auth Component is ready to use. now you have to login user using your own logic and add user details into Auth Session.
here i am using my own sample code:-
    public function login()
    {
        if(!empty($this->request->data))
        {
            $username = $this->request->data['User']['username'];
            $password = md5($this->request->data['User']['password']);
            // Fetch User Details from database
            $user = $this->User->find('first',array(          
               'conditions'=> array(
                       'User.username'=>$username,'User.password'=>$password
                            )
              ));
            if(!empty($user))
            {
                $this->Auth->login($user);
                //Redirect To other page
            }
        }
    }
If you have any problem place your comment or follow these link
Authentication
Setting-Auth-Component-Variables
login

Comments

Popular Posts