CakePHP:允许使用用户名或电子邮件登录

时间:2011-11-02 00:11:59

标签: php cakephp

我正在实施一个逻辑,您可以使用您的用户名或电子邮件地址登录CakePHP。我在一本名为CakePHP 1.3:应用程序开发手册(第1章:允许使用用户名或电子邮件登录)的书中进行了示例。本书解释说,当Auth组件无法使用提供的信息登录用户时,它会返回到login()操作,并可以查找可能使用login()操作中的逻辑登录用户的其他信息。 / p>

代码/逻辑正在运行。但是,当我使用我的电子邮件地址登录时,它仍会显示loginError消息,其中显示“指定的帐户无效”。下面是“欢迎”,这是我登录成功时显示的消息。

这些是我想知道的:

  1. 本书并未说明这是否正常,但我想学习如何省略此错误消息,因为它没有意义。该线路(评论中)在哪里吸引用户?该行后面会显示错误消息。

  2. ..并且可能显示“您已登录使用电子邮件登录”。这是次要的。

  3. 以下是我认为的相关代码。如果您需要更多信息,请与我们联系。

    class AppController extends Controller {
    public $components = array(
        'Auth' => array(
            'authorize' => 'controller',
            'loginRedirect' => array(
                'admin' => false,
                'controller' => 'users',
                'action' => 'dashboard'
            ),
            'loginError' => 'Invalid account specified',
            'authError' => 'You don\'t have the right permission'
        ),
        'Session'
    );
    }
    
    
    class UsersController extends AppController {
    public function login() {
        if (
            !empty($this->data) &&
            !empty($this->Auth->data['User']['username']) &&
            !empty($this->Auth->data['User']['password'])
        ) {
            $user = $this->User->find('first', array(
                'conditions' => array(
                    'User.email' => $this->Auth->data['User']['username'],
                    'User.password' => $this->Auth->data['User']['password']
                ),
                'recursive' => -1
            ));
    
            if (!empty($user) && $this->Auth->login($user)) {   // $this->Auth->login() true if logs in
                if ($this->Auth->autoRedirect) {    // I think autoRedirect is TRUE by default
    
                    $this->redirect($this->Auth->redirect()); // <<THIS LINE>>
                }
            } else {
                $this->Session->setFlash($this->Auth->loginError, $this->Auth->flashElement, array(), 'auth');
            }           
        }
    }
    

2 个答案:

答案 0 :(得分:1)

    if (!empty($user) && $this->Auth->login($user)) {
        $this->Session->delete('Message.auth');
    }

如果在登录视图中闪存('auth'),则不需要为authError设置setFlash(如在cookbook中),并且您不需要调用重定向。

答案 1 :(得分:0)

它与http://www.packtpub.com/cakephp-1-3-application-development-cookbook/book CakePHP 1.3应用程序开发指南中解释的代码相同 , 我认为这样会更有效

if(!empty($user) && $this->Auth->login($user)){
                if($this->Auth->autoRedirect){
                    $this->Session->delete('Message.auth'); // kills login failed message after successful login
                    $this->redirect($this->Auth->redirect());
                } else {
                    $this->Session->setFlash($this->Auth->loginError, $this->Auth->flashElement, array(), 'auth');
                }
            }

这种方式登录成功登录后将失败错误消息将被省略,重定向将保持不变。

相关问题