Pages

Sunday, January 27, 2013

Cakephp Auth Component 2.0

Cakephp Auth Component 2.0

Define Auth component to controller as follows

public  $comonents=array(
'Auth'=>array(
                           'loginRedirect' =>array('controller'=>'users','action'=>'index'),
                           'logoutRedirect'=>array('controller'=>'users','action'=>'index'),
                            'authError'=>'Access Denied',
                            'authorize'=>array('Controller'),
                            'loginError'=>'Invalid credentials, please try again.',
                            'allow'=>('index','view');
                       ) ,
'Session'
);

//check for authorization
public function isAuthorized($user)
{
          return true;
}

Now in users controller define the login action

public function login()
{
       if($this->Auth->login())
       {
           $this->redirect($this->Auth->redirect());
       }
     else
    {
       $this->Session->setFlash('Authentication Failed')
   }
}

public function logout()
{
     $this->redirect($this->Auth->logout());
}

create form in login view to provide interface to user for username and password and AuthComponent will automatically validate login.

Make sure fields in the database match cake's cretriea i.e "usename" for User Name and "password" for Password and "Users" table.

register new user 
create a new add method in a controller create a view for the same and then in user model just before save hash the password as follows

$this->data['user']['password']=AuthComponent::password($this->data['User']['Password']);

To check for login status
$this->Auth->loggedIn();
To get current info of loggedin user
 $this->Auth->User;
To Display auth error message
$this->Session->flash('auth');

1 comment:

  1. We need to create a database table users first

    CREATE TABLE users (
    id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    username VARCHAR(50),
    password VARCHAR(50),
    role VARCHAR(20),
    created DATETIME DEFAULT NULL,
    modified DATETIME DEFAULT NULL
    );

    ReplyDelete