Been trying to figure this out for plenty of hours, but without success.
$this->request->data['Login'] array contains the right username and hash which matches the entry in the database. $this->Auth->login(); is always returning false for some reason.
The Login table has a column called UserID and Password, Password is hashed using MD5 and a salt which is stored in the table Login as well.
I tried adding a beforeSave function in the Login model which hashed the password, but this didn't seem to work either?
/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');
?>