Skip to content

Commit db17ece

Browse files
committed
Implementing a FallbackPassword hasher to assist people in migrating
users to a stronger password algorithm
1 parent cf52733 commit db17ece

File tree

1 file changed

+84
-0
lines changed

1 file changed

+84
-0
lines changed
Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
<?php
2+
/**
3+
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
4+
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
5+
*
6+
* Licensed under The MIT License
7+
* For full copyright and license information, please see the LICENSE.txt
8+
* Redistributions of files must retain the above copyright notice.
9+
*
10+
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
11+
* @link http://cakephp.org CakePHP(tm) Project
12+
* @since 3.0
13+
* @license http://www.opensource.org/licenses/mit-license.php MIT License
14+
*/
15+
namespace Cake\Controller\Component\Auth;
16+
17+
use Cake\Controller\Component\Auth\AbstractPasswordHasher;
18+
19+
/**
20+
* A password hasher that can use multiple different hashes where only
21+
* one is the preferred one. This is useful when trying to migrate an
22+
* existing database of users from one password type to another.
23+
*
24+
*/
25+
class FallbackPasswordHasher extends AbstractPasswordHasher {
26+
27+
/**
28+
* Default config for this object.
29+
*
30+
* @var array
31+
*/
32+
protected $_defaultConfig = [
33+
'hashers' => ['Simple', 'Weak']
34+
];
35+
36+
/**
37+
* Holds the list of password hasher objects that will be used
38+
*
39+
* @var array
40+
*/
41+
protected $_hashers = [];
42+
43+
/**
44+
* Constructor
45+
*
46+
*/
47+
protected function __construct() {
48+
foreach ($this->_config['hashers'] as $hasher) {
49+
$this->_hashers = PasswordHasherFactory::build($hasher);
50+
}
51+
}
52+
53+
/**
54+
* Generates password hash.
55+
*
56+
* Uses the first password hasher in the list to generate the hash
57+
*
58+
* @param string $password Plain text password to hash.
59+
* @return string Password hash
60+
*/
61+
public function hash($password) {
62+
return $this->_hashers[0]->hash($password);
63+
}
64+
65+
/**
66+
* Verifies that the provided password corresponds to its hashed version
67+
*
68+
* This will iterate over all configured hashers until one of them return
69+
* true.
70+
*
71+
* @param string $password Plain text password to hash.
72+
* @param string $hashedPassword Existing hashed password.
73+
* @return bool True if hashes match else false.
74+
*/
75+
public function check($password, $hashedPassword) {
76+
foreach ($this->_hashers as $hasher) {
77+
if ($hasher->check($password, $hashedPassword)) {
78+
return true;
79+
}
80+
}
81+
return false;
82+
}
83+
84+
}

0 commit comments

Comments
 (0)