【发布时间】:2011-10-21 09:13:37
【问题描述】:
使用 CakePHP 的 Auth 组件,我如何允许用户通过使用他们的“用户名”或“电子邮件”字段作为用户名以及“通过”字段作为他们的密码来进行身份验证?
【问题讨论】:
标签: cakephp cakephp-1.3 cakephp-1.2
使用 CakePHP 的 Auth 组件,我如何允许用户通过使用他们的“用户名”或“电子邮件”字段作为用户名以及“通过”字段作为他们的密码来进行身份验证?
【问题讨论】:
标签: cakephp cakephp-1.3 cakephp-1.2
“使用(用户名和电子邮件)都作为用户名”是什么意思?
编辑:好的,所以您希望 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()); } }
【讨论】:
为此,您必须跳过 Auths 自动重定向并自行管理。这是您的 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:beforeFilter(); 中设置 $this->Auth->autoRedirect = false;;
您必须记住,身份验证会自动检查用户名和密码,因此此操作只是从中获取。 Session::remove() 调用是在用户名/密码检查失败并且邮件登录成功时自动删除 Auth 错误消息(否则您会收到登录成功的错误消息)。
【讨论】: