October 09, 2014

10:21 am
In this article, we are going to discuss about How to create a simple AuthComponent in CakePHP 2.x. To make restricted access level site in cakephp we need to implement AuthComponent in cakephp. To apply AuthComponent in cakephp 2.x is similar like to apply AuthComponent in Cakephp 1.x. I think you know cakephp.

Here I described the Authcomponent implementation system for Cakephp 2.x

Step 1 : 

Create a users table like bellow

CREATE TABLE `users` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(255) NOT NULL,
  `password` varchar(255) DEFAULT NULL,
  `email` varchar(255) DEFAULT NULL,
  `firstname` varchar(255) NOT NULL,
  `lastname` varchar(255) DEFAULT NULL,
  `address` text,
  `mobile` varchar(255) DEFAULT NULL,
  `status` tinyint(1) DEFAULT '0',
  PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=5 DEFAULT CHARSET=utf8

Step 2 :

Create respective UserController, UserModel and view files.

Step 3:

For User Password hashing you need to add the SimplePasswordHasher component in your model table:

// app/Model/User.php

App::uses('AppModel', 'Model');
App::uses('SimplePasswordHasher', 'Controller/Component/Auth');

class User extends AppModel {

// ...

public function beforeSave($options = array()) {
    if (isset($this->data[$this->alias]['password'])) {
        $passwordHasher = new SimplePasswordHasher();
        $this->data[$this->alias]['password'] = $passwordHasher->hash(
            $this->data[$this->alias]['password']
        );
    }
    return true;
}

Step 4:

Open your AppController and write the bellow code

// app/Controller/AppController.php
class AppController extends Controller {

    public $components = array(
        'Session',
        'Auth' => array(
            'loginRedirect' => array(
                'controller' => 'members',
                'action' => 'index'
            ),
            'logoutRedirect' => array(
                'controller' => 'pages',
                'action' => 'display',
                'home'
            ),
            'authorize' => array('Controller')
        )
    );
    public function isAuthorized() {
        $userDetails =  AuthComponent::user();
        if($userDetails['group_id'] == 1) return true;
        if(!empty($this->permissions[$this->action]))
        {
          if($this->permissions[$this->action] == '*') return true;
             
          if(in_array($userDetails['group_id'], $this->permissions[$this->action]))
          {
          return true;
          }
        }else{
        $this->Session->setFlash(__('You are not authorize to access that location.'));
        return false;
         
        }
         
    }
}

Step 5:

Go to your user controller and add the following methods:

// app/Controller/UsersController.php
public function beforeFilter() {
    parent::beforeFilter();
    // Allow all users to register and logout.
    $this->Auth->allow('add', 'logout');
}
public function login() {
    if ($this->request->is('post')) {
        $this->User->set($this->request->data);
            if ($this->Auth->login()) {
                return $this->redirect($this->Auth->redirect());
            }else  
            { 
            $this->Session->setFlash('Data Validation Failure', 'default', array('class' => 'cake-error'));
            }
    }

    public function logout() {
        return $this->redirect($this->Auth->logout());
    }
   
Step 6:

Create login.ctp file with bellow code:  

//app/View/Users/login.ctp

<div class="users form">
<?php echo $this->Session->flash('auth'); ?>
<?php echo $this->Form->create('User'); ?>
    <fieldset>
        <legend>
            <?php echo __('Please enter your username and password'); ?>
        </legend>
        <?php echo $this->Form->input('username');
        echo $this->Form->input('password');
    ?>
    </fieldset>
<?php echo $this->Form->end(__('Login')); ?>
</div>

All done now you can check the AuthComponent action by accessing your application:

0 comments:

Post a Comment