一直試圖弄清楚這個好幾個小時,但沒有成功。
$ 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