我希望 auth 组件允许用户登录输入用户名或电子邮件。在我的用户表中,两个字段 - userName 和 userEmail 都是唯一的。在注册时,密码生成如下:
sha1($用户名.$密码);
问题是用户无法使用电子邮件登录。
应用控制器
var $components = array('Auth');
public function beforeFilter(){
if(isset($this->params['prefix']) && $this->params['prefix'] == 'webadmin') {
$this->Auth->userModel = 'Admin';
$this->Auth->logoutRedirect = $this->Auth->loginAction = array('prefix' => 'webadmin', 'controller' => 'login', 'action' => 'index');
$this->Auth->loginError = 'Invalid Username/Password Combination!';
$this->Auth->authError = 'Please login to proceed further!';
$this->Auth->flashElement = "auth.front.message";
$this->Auth->loginRedirect = array('prefix'=>'webadmin', 'controller'=>'dashboard', 'action'=>'index');
}
else{
$this->layout="front";
//$this->Auth->autoRedirect = false;
// $this->Auth->logoutRedirect = $this->Auth->loginAction = array('controller' => 'users', 'action' => 'login');
// $this->Auth->loginRedirect = array('controller'=>'blogs', 'action'=>'index');
$this->Auth->fields = array(
'username' => 'userName',
'password' => 'password'
);
$this->Auth->userScope = array('User.status'=>1);
$this->Auth->loginError = "The username/email and password you entered doesn't match our records.";
$this->Auth->authError = 'Please login to view this page!';
$this->Auth->flashElement = "auth.front.message";
$this->Auth->loginRedirect = array('controller'=>'profiles', 'action'=>'index');
}
用户控制器:登录功能如下:
if(!empty($this->data))
{
// Try to login with Email
if (!empty($this->Auth->data)) {
// save username entered in the login form
$username = $this->Auth->data['User']['userName'];
// find a user by e-mail
$find_by_email = $this->User->find('first', array(
'conditions' => array('userEmail' => $this->Auth->data['User']['userName']),
'fields' => 'userName'));
// found
if (!empty($find_by_email))
{
$this->Auth->data['User']['userName'] = $find_by_email['User']['userName'];
$this->data['User']['password']=$this->Auth->data['User']['password'];
if (!$this->Auth->login($this->data)) {
// login failed
// bring back the username entered in the login form
$this->Auth->data['User']['username'] = $username;
} else {
$this->Session->delete('Message.auth');
// redirect
if ($this->Auth->autoRedirect) {
$this->redirect($this->Auth->redirect(), null, true);
}
}
}
}
}
Auth.php:(我在使用 cakephp 会话自动登录 SMF 论坛时,对密码的生成方式进行了一些更改。)
function login($data = null) {
$data['User.password'] = sha1(strtolower($data['User.userName']) . $_POST['data']['User']['password']);
$this->__setDefaults();
$this->_loggedIn = false;
if (empty($data)) {
$data = $this->data;
}
if ($user = $this->identify($data)) {
$this->Session->write($this->sessionKey, $user);
$this->_loggedIn = true;
}
return $this->_loggedIn;
}
我从这个链接获得了帮助,但是我没有在 auth.php 中的 $data['User.userName'] 中获得用户名,我在这里收到了电子邮件,所以密码错误并导致登录失败。
请帮忙。