使用电子邮件而不是用户名进行Cakephp 2.0身份验证

6

在我的看法中,我有:

<?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(); ?>

在我的AppController中:
public $components = array(
        'Session',
        'Auth'
    );

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

在我的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'));
            }
        }
    }

但是登录无法工作,我错过了什么吗?
谢谢。
2个回答

15

我认为问题是:

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

这就是在CakePHP 1.3中指定自定义登录字段的方法。然而,CakePHP 2.0要求您在public $components = array(...);中指定这些字段。在1.3 API中,Auth有一个$fields属性,但在2.0 API中,$fields属性已不再存在。因此,您必须执行以下操作:

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

更多信息可以在这里找到:http://book.cakephp.org/2.0/en/core-libraries/components/authentication.html#configuring-authentication-handlers

请告诉我它的工作原理!


0

我的问题得到了最终解决。谢谢。

我在userModel方面遇到了问题,然后我写了这个:

'Auth' => array(
         'userModel' => 'Member'
      )

用这个代替:

'Auth' => array(
    'authenticate' => array(
        'Form' => array(
            'userModel' => 'Member'
        )
    )
)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接