在CakePHP的Auth组件中使用用户名而不是电子邮件

时间:2011-08-06 07:44:18

标签: cakephp cakephp-1.3 cakephp-1.2

使用CakePHP的Auth组件,如何允许用户使用“用户名”或“电子邮件”字段作为用户名,并使用“密码”字段作为密码进行身份验证?

2 个答案:

答案 0 :(得分:4)

“使用(用户名和电子邮件)作为用户名”是什么意思?

编辑:好的,您希望Auth查看数据库中的用户名和电子邮件字段,以与用户输入的“用户名”进行比较?然后这样做:

function beforeFilter() {
  parent::beforeFilter();
  $this->Auth->fields = array('username' => 'username', 'password' => 'pass');
  $this->Auth->autoRedirect = false;
}
function login(){
  if ($this->Auth->user()) {
     $this->redirect($this->Auth->redirect());
  } else if (!empty($this->data)) {
     $this->Auth->fields = array('username' => 'email', 'password' => 'pass');
     $this->data['User']['email'] = $this->data['User']['username'];
     if($this->Auth->login($this->data))$this->redirect($this->Auth->redirect());
  }
}

答案 1 :(得分:3)

要执行此操作,您必须跳过Auths autoredirect并自行管理。这是users_controller中的登录操作:

public function login() {
    if(!empty($this->data)) { // Submitted form

        // Try to login with Email
        if(!$this->Auth->user() // if user wasn't logged in with username + pass
            && !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)) {
                // They logged in, so kill the flash error message
                $this->Session->delete('Message.auth');
            } else {
                $this->Session->setFlash($this->Auth->loginError, $this->Auth->flashElement, array(), 'auth');
            }
        }

        if($this->Auth->user()) {
            // Post login logic here
            $this->redirect($this->Auth->redirect());
        }

    } else {
        if($this->Auth->user()) {
            $this->Session->setFlash(__d('users', 'You are already registered and logged in!', true));
            //$this->redirect('/');
            $this->redirect($this->Auth->redirect());
        }
    }

这是直接从我的应用程序复制的,因此可能需要对您进行一些调整。不要忘记在AppController中设置$this->Auth->autoRedirect = false;:beforeFilter();

你必须记住,Auth会自动检查用户名和密码,所以这个动作就是从中获取的。 Session::remove()调用是删除用户名/密码检查失败时自动离开的Auth错误消息和电子邮件登录成功(否则您会收到成功登录的错误消息)。