Skip to content

Instantly share code, notes, and snippets.

@redoPop
Created October 5, 2011 00:22
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save redoPop/1263248 to your computer and use it in GitHub Desktop.
Save redoPop/1263248 to your computer and use it in GitHub Desktop.
CakePHP 2.0 Authentication object for use with better hash methods (bcrypt, etc.)
<?php
App::uses('FormAuthenticate', 'Controller/Component/Auth');
class HashFormAuthenticate extends FormAuthenticate {
/**
* Find a user record given a username and unhashed password.
*
* @param string $username The username/identifier.
* @param string $password The unhashed password.
* @return Mixed Either false on failure, or an array of user data.
*/
protected function _findUser($username, $password) {
$userModel = $this->settings['userModel'];
list($plugin, $model) = pluginSplit($userModel);
$fields = $this->settings['fields'];
$conditions = array($model . '.' . $fields['username'] => $username);
if (!empty($this->settings['scope'])) {
$conditions = array_merge($conditions, $this->settings['scope']);
}
$result = ClassRegistry::init($userModel)->find('first', array(
'conditions' => $conditions,
'recursive' => 0,
));
// If no matching user record was found, return false
if (empty($result) || empty($result[$model])) {
return false;
}
// If the user's password hash doesn't match the results, return false
if (!$this->checkPassword($password, $result[$model][$fields['password']])) {
return false;
}
// Remove the password from the model data before returning the user
unset($result[$model][$fields['password']]);
return $result[$model];
}
/**
* Check a password against a hash.
*
* You can use any hash method you like. I'm using P5K -- my own library
* that incorporates PBKDF2 hashes.
*
* Returns true if the password matches the hash, false otherwise.
*
* @param string $password The unhashed password.
* @param string $hash The hash to check against.
*/
public function checkPassword($password, $hash) {
// (phpass/bcrypt check goes here!)
// Check the password against a PBKDF2 value
// https://github.com/jdbartlett/P5K
if (substr($hash, 0, 6) == '$p5k2$') {
App::uses('P5K', 'Lib');
return P5K::check($password, $hash);
}
// Check the password against CakePHP's built in hash method
return Security::hash($password, null, true) == $hash;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment