一直试图弄清楚这个好几个小时,但没有成功。
$ this-> request-> data ['Login']数组包含与数据库中的条目匹配的正确用户名和散列。 $这 - > Auth->登录();由于某种原因总是返回错误。
登录表有一个名为UserID和Password的列,使用MD5对密码进行哈希处理,并将盐存储在表Login中。
我试图在散列密码的登录模型中添加一个beforeSave函数,但是这似乎不起作用?
/app/Controller/AppController.php
<?php
App::uses('Controller', 'Controller');
class AppController extends Controller {
public $helpers = array('App', 'Html', 'Form', 'Session');
public $components = array(
'Session',
'Auth' => array(
'loginAction' => array('controller' => 'login', 'action' => 'authenticate'),
'loginRedirect' => array('controller' => 'account', 'action' => 'index'),
'logoutRedirect' => array('controller' => 'home', 'action' => 'index'),
'authenticate' => array('Form' => array('userModel' => 'Login', 'fields' => array('username' => 'UserID', 'password' => 'Password'))))
);
// Execute on every page load.
public function beforeFilter(){
$this->Auth->allow('index', 'view');
}
}
/app/Controller/LoginController.php
<?php
class loginController extends AppController{
public $uses = array('Login');
public function index(){
$this->render('/login');
}
public function authenticate(){
if($this->request->is('post')){
$this->request->data['Login']['password'] = $this->hashPassword($this->data['Login']);
if($this->Auth->login()){
return $this->redirect($this->Auth->redirect());
}
$this->Session->setFlash('Invalid username or password.');
return $this->redirect('/login');
}
}
private function hashPassword($login){
// Get the salt of the user.
$salt = $this->Login->find('first', array(
'fields' => array(
'Salt'),
'conditions' => array(
'Login.UserID' => $login['username'])));
return md5(md5($login['password']) . $salt['Login']['Salt']);
}
}
/app/Model/Login.php
<?php
class Login extends AppModel{
public $useTable = 'Login';
public $validate = array(
'username' => array(
'required' => array(
'rule' => array('notEmpty'),
'message' => 'Please fill in all of the fields.'
)
),
'password' => array(
'required' => array(
'rule' => array('notEmpty'),
'message' => 'Please fill in all of the fields.'
)
));
}
/app/View/login.ctp
<?php
echo $this->Session->flash('flash', array('element' => 'fail'));
echo $this->Form->create('Login', array('url' => '/login/authenticate'));
echo $this->Form->input('username', array('label' => false, 'div' => false, 'autocomplete' => 'off'));
echo $this->Form->input('password', array('label' => false, 'div' => false));
echo $this->Form->end('Login');
?>
谢谢你的回复,但它不回答我的问题。如果我不应该手动哈希我的密码,我该如何正确地做到这一点? – user1961685 2014-09-05 17:15:48
删除手动散列密码的任何/每一行,然后阅读指示它只显示散列它的位置在beforeSave()中的位置。 – Dave 2014-09-05 17:23:14