Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cakephp 2.0 Authentication using email instead of username

In my view I have:

<?php
echo $this->Form->create('User', array("controller" => "Users", "action" => "login", "method" => "post"));
echo $this->Form->input('User.email', array("label" => false));
echo $this->Form->input('User.password', array("label" => false, 'class' => 'password-input'));
echo $this->Form->end(); ?>

In my AppController:

public $components = array(
        'Session',
        'Auth'
    );

    function beforeFilter(){
        $this->Auth->fields = array(
            'username' => 'email',
            'password' => 'password'
        );
    }

In my UsersController:

function beforeFilter(){
        $this->Auth->allow('sign_up', 'login', 'logout', 'forgot_password');
        return parent::beforeFilter();
    }
public function login() {
        if ($this->Auth->login()) {
            $this->Session->setFlash(__('Successfully logged in'), 'default', array('class' => 'success'));
            $this->redirect($this->Auth->redirect());
        } else {
            if (!empty($this->request->data)) {
                $this->Session->setFlash(__('Username or password is incorrect'), 'default', array('class' => 'notice'));
            }
        }
    }

But the login is not working, what am I missing?

Thanks.

like image 310
content01 Avatar asked Apr 20 '12 14:04

content01


1 Answers

I believe the problem is:

function beforeFilter(){
    $this->Auth->fields = array(
        'username' => 'email',
        'password' => 'password'
    );
}

That was how custom login fields were specified in CakePHP 1.3. CakePHP 2.0 instead requires you to specify these fields in the public $components = array(...);. The 1.3 API shows that Auth has a $fields property, but the 2.0 API shows that there is no longer a $fields property. So you must:

public $components = array(
    'Session',
    'Auth' => array(
        'authenticate' => array(
            'Form' => array(
                'fields' => array('username' => 'email')
            )
        )
    )
);

More information can be found at: http://book.cakephp.org/2.0/en/core-libraries/components/authentication.html#configuring-authentication-handlers

Please tell me how it works out!

like image 119
penguin egg Avatar answered Nov 06 '22 03:11

penguin egg