FallbackPasswordHasher.php 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. <?php
  2. App::uses('AbstractPasswordHasher', 'Controller/Component/Auth');
  3. App::uses('PasswordHasherFactory', 'Tools.Controller/Component/Auth');
  4. /**
  5. * A backport of the 3.x FallbackPasswordHasher class.
  6. *
  7. * @author Mark Scherer
  8. * @license http://opensource.org/licenses/mit-license.php MIT
  9. */
  10. class FallbackPasswordHasher extends AbstractPasswordHasher {
  11. /**
  12. * Default config for this object.
  13. *
  14. * @var array
  15. */
  16. protected $_defaultConfig = ['hashers' => []];
  17. /**
  18. * Holds the list of password hasher objects that will be used
  19. *
  20. * @var array
  21. */
  22. protected $_hashers = [];
  23. /**
  24. * Constructor
  25. *
  26. * @param array $config configuration options for this object. Requires the
  27. * `hashers` key to be present in the array with a list of other hashers to be
  28. * used
  29. */
  30. public function __construct(array $config = []) {
  31. $config += $this->_defaultConfig;
  32. parent::__construct($config);
  33. foreach ($this->_config['hashers'] as $key => $hasher) {
  34. if (!is_string($hasher)) {
  35. $hasher += ['className' => $key, ];
  36. }
  37. $this->_hashers[] = PasswordHasherFactory::build($hasher);
  38. }
  39. }
  40. /**
  41. * Generates password hash.
  42. *
  43. * Uses the first password hasher in the list to generate the hash
  44. *
  45. * @param string $password Plain text password to hash.
  46. * @return string Password hash
  47. */
  48. public function hash($password) {
  49. return $this->_hashers[0]->hash($password);
  50. }
  51. /**
  52. * Verifies that the provided password corresponds to its hashed version
  53. *
  54. * This will iterate over all configured hashers until one of them returns
  55. * true.
  56. *
  57. * @param string $password Plain text password to hash.
  58. * @param string $hashedPassword Existing hashed password.
  59. * @return bool True if hashes match else false.
  60. */
  61. public function check($password, $hashedPassword) {
  62. foreach ($this->_hashers as $hasher) {
  63. if ($hasher->check($password, $hashedPassword)) {
  64. return true;
  65. }
  66. }
  67. return false;
  68. }
  69. /**
  70. * Returns true if the password need to be rehashed, with the first hasher present
  71. * in the list of hashers
  72. *
  73. * @param string $password The password to verify
  74. * @return bool
  75. */
  76. public function needsRehash($password) {
  77. return $this->_hashers[0]->needsRehash($password);
  78. }
  79. }