2011-11-02 132 views
3

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

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

这些都是想什么,我知道:

  1. 这本书并不表示这是否是正常的,但我想了解如何忽略此错误消息,因为它没有意义。 THIS LINE在哪里(在评论中)接受用户?该行后面显示错误消息。

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

下面是什么,我认为相关的代码。请让我知道你是否需要更多。

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

回答

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

你并不需要为setFlash如果authError您在登录观看Flash(“权威性”)(如食谱),你不需要呼叫重定向。

+0

你是说最后的else语句是不必要的(setFlash(...))?你能解释一下你的回答吗?在登录视图中更多地使用flash('auth')?顺便说一句,如果我想引导用户访问除登录页面之外的页面,重定向似乎是必要的。没有它,我登录,但我仍然在登录页面(无法告诉我成功登录,没有尝试导航到其他受限制的页面)。 – musicliftsme

+0

请参阅http://book.cakephp.org/view/1250/Authentication它根据Auth中的设置自动重定向(否则,为什么您认为您可以将login()保留为默认设置?) –

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

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

相关问题