[Cakephp] Authentication

Deskripsi
How to implement Authentication (login) using Cakephp Framework 2.X

Required 
1. Understand Form , Model , Controller , Routes

How To
1. Create table in your database and give it name "user", create 3 field : user_id, username , password.
2. Create Model , give it name "testModel.php"

<?php
class testModel extends AppModel
{
    var $useDBConfig = 'default';
    var $name = 'testModel '; //must same with file name
    var $primaryKey = 'id_user'; // primary key table
    var $useTable = 'user'; // same as table name in database
 
    public $validate = array(
        'username' => array(
            'required' => array(
                'rule' => array('notEmpty'),
                'message' => 'A username is required'
            )
        ),
        'password' => array(
            'required' => array(
                'rule' => array('notEmpty'),
                'message' => 'A password is required'
            )
        ));
}
?>

3. open file in path app/controller/AppController.php
   add code like this :


class AppController extends Controller { //you can find this line in the bottom  

/* Executing All Controller*/
var $uses = array('userlogin');
/* ----- */

public $components = array(
       'Session',
       'Auth' => array(
       'loginAction' => array('controller' => 'autentikasi','action' => 'login'),
       'authenticate' => array(
       'Form' => array(
       'userModel' => 'userlogin',
       'fields' => array('username' => 'username/email',
                          'password' => 'password' )
                       )
                       ),
       'Form','Basic',
       'loginRedirect' => array('controller' => 'Main',
       'action' => 'index'
        ),
       'logoutRedirect' => array(
       'controller' => 'autentikasi',
       'action' => 'login'
       ),
       'authorize' => array('Controller'), // <- activate isAuthorize()
       )
       );

  

 public function beforeFilter(){
        $this->layout = false;
        $this->Auth->deny('*');
        // don't forget to allow the action you'll be execute , if not it always forever loop to login page.
        $this->Auth->allow('login','not_supported');
 }

  

    public function isAuthorized($user) {

        // jika berhasil login , dapatkan data user

        if (isset($user['userlogin']['username']))

        {

            $dataUser = $this->userlogin->find('all', array('fields'=>array('userlogin.username','userlogin.role'),

                                                            'limit' => 10,

                                                            'conditions' => array('userlogin.username' => $user['userlogin']['username'],

                                                                                  'userlogin.password' => $user['userlogin']['password']

                                                                                   ),

                                                            'order'=>array('userlogin.username' => 'ASC')));

                if(!empty($dataUser))

                { 

                    $this->Session->write('login',true);

                    $this->Session->write('username',$dataUser[0]['userlogin']['username']);

                    $this->Session->write('role',$dataUser[0]['userlogin']['role']);

                    return true;

                }

                else

                {

                    $this->redirect($this->Auth->logout()); //force logout if false username and password

                    return false; //return false auth->login

                }

        }

        else

        {

            echo "Session failure please relogin !";

            return false;

        }

    }

}





4. open or create file in path app/controller/testAuthController.php
<?php

class testAuthController extends AppController {
var $uses = array('testModel ');

    public function index() {
                if ($this->request->is('post')) {
                    if ($this->Auth->login($this->request->data))
                   {
                     return $this->redirect($this->Auth->redirect());
                   }
                   else
                  {
                    $this->Session->setFlash(__('Invalid username or password, try again'));
                  }
               }
    }

    public function logout() {
    return $this->redirect($this->Auth->logout()); // this is calling logout redirect for button logout
    }
 
}

5. Now create form login for index action
<?php echo $this->Session->flash('auth'); ?>
<?php echo $this->Form->create('testModel',array('url'=>array('controller'=>'testAuth','action'=>'index'))); ?>
                        <fieldset>
                            <legend>
                            <?php echo __('Please enter your username and password'); ?>
                            </legend>
                            <?php echo $this->Form->input('username'); // this data passing to username auth
                                  echo $this->Form->input('password'); // this data passing to password auth
                            ?>
                        </fieldset>
                        <?php echo $this->Form->end(__('Login'));
?>

6. Create routes for pretty url, open file in app/config/routes
add line :
 Router::connect('/', array('controller' => 'testAuth', 'action' => 'index', 'home'));
Router::connect('/login/*', array('controller' => 'testAuth', 'action' => 'index'));

Note :
1. if user not login , all page cannot be access and always redirect to login page.
2. if success login , all user can access ALL PAGE , to handle this authorization each user, you can use SESSION :)
3. if user logout , automaticly redirect to login page.

Work Greats , Happy Learning...

Note:
- Edited : fix code authentication



Post a Comment

Harap gunakan bahasa yang baik dan sopan, terima kasih