Tags

, , ,


I found some new thing in cakephp 2.x.  I just tried to show here how quickly we can setup Auth Component in to our project.

First we need to setup configuration

// app/Controller/AppController.php
var $components = array(
        "Auth" => array(
            'loginRedirect' => array('controller' => 'dashboard', 'action' => 'index'), // After success where page goes to 
            'logoutRedirect' => array('controller' => 'users', 'action' => 'login') // This is login page 
        ),
        "Session");
function beforeFilter(){
.....
         $this->Auth->authenticate = array( 
                                        AuthComponent::ALL => array('userModel' => 'User', 'scope' => array("User.status" => 1)),
                                        'Form');


}

Logic check controller.

//app/Controller/UsersController.php
    function login() 
    {
        if($this->request->is('post')){
        {
              if($this->Auth->login()){
                  $this->loginUser = AuthComponent::user();  // Here $this->loginUser is defined so we can get the user values here. 
                  return $this->redirect($this->Auth->redirect());
              }else{
                  $this->Session->setFlash('Username or password is incorrect', 'default', array(), 'auth');
              }
          }   
        
        }
    }

Login view here, this is login form

    echo $this->Session->flash('auth'); // This will show the authentication error message
    echo $this->Form->create('User', array("controller" => "users", "action" => "login", "method" => "post"));

    echo $this->Form->input('User.username', array("label" => "Username:"));
    echo $this->Form->input('User.password', array("label" => "Password: "));
    echo $this->Form->end('Login');

When we create a user we need to setup the hash password field


If we need hash password, we need to do the follwoing 

//app/Model/User.php

function beforeSave(){
    if (isset($this->data[$this->alias]['password'])) {
            $this->data[$this->alias]['password'] = AuthComponent::password($this->data[$this->alias]['password']);
    }
}

I can add user normally and its work.

I just show here the basic login use which is used for quick setup.

Happy login 😀

If you want to go more advanced uses of component go to Docs

Advertisements