MigratingPasswordEncoder.php 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\Security\Core\Encoder;
  11. /**
  12. * Hashes passwords using the best available encoder.
  13. * Validates them using a chain of encoders.
  14. *
  15. * /!\ Don't put a PlaintextPasswordEncoder in the list as that'd mean a leaked hash
  16. * could be used to authenticate successfully without knowing the cleartext password.
  17. *
  18. * @author Nicolas Grekas <p@tchwork.com>
  19. */
  20. final class MigratingPasswordEncoder extends BasePasswordEncoder implements SelfSaltingEncoderInterface
  21. {
  22. private $bestEncoder;
  23. private $extraEncoders;
  24. public function __construct(PasswordEncoderInterface $bestEncoder, PasswordEncoderInterface ...$extraEncoders)
  25. {
  26. $this->bestEncoder = $bestEncoder;
  27. $this->extraEncoders = $extraEncoders;
  28. }
  29. /**
  30. * {@inheritdoc}
  31. */
  32. public function encodePassword(string $raw, ?string $salt): string
  33. {
  34. return $this->bestEncoder->encodePassword($raw, $salt);
  35. }
  36. /**
  37. * {@inheritdoc}
  38. */
  39. public function isPasswordValid(string $encoded, string $raw, ?string $salt): bool
  40. {
  41. if ($this->bestEncoder->isPasswordValid($encoded, $raw, $salt)) {
  42. return true;
  43. }
  44. if (!$this->bestEncoder->needsRehash($encoded)) {
  45. return false;
  46. }
  47. foreach ($this->extraEncoders as $encoder) {
  48. if ($encoder->isPasswordValid($encoded, $raw, $salt)) {
  49. return true;
  50. }
  51. }
  52. return false;
  53. }
  54. /**
  55. * {@inheritdoc}
  56. */
  57. public function needsRehash(string $encoded): bool
  58. {
  59. return $this->bestEncoder->needsRehash($encoded);
  60. }
  61. }