vendor/symfony/security-http/EventListener/PasswordMigratingListener.php line 35

Open in your IDE?
  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\Http\EventListener;
  11. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  12. use Symfony\Component\Security\Core\Encoder\EncoderFactoryInterface;
  13. use Symfony\Component\Security\Http\Authenticator\Passport\Badge\PasswordUpgradeBadge;
  14. use Symfony\Component\Security\Http\Authenticator\Passport\UserPassportInterface;
  15. use Symfony\Component\Security\Http\Event\LoginSuccessEvent;
  16. /**
  17.  * @author Wouter de Jong <wouter@wouterj.nl>
  18.  *
  19.  * @final
  20.  * @experimental in 5.1
  21.  */
  22. class PasswordMigratingListener implements EventSubscriberInterface
  23. {
  24.     private $encoderFactory;
  25.     public function __construct(EncoderFactoryInterface $encoderFactory)
  26.     {
  27.         $this->encoderFactory $encoderFactory;
  28.     }
  29.     public function onLoginSuccess(LoginSuccessEvent $event): void
  30.     {
  31.         $passport $event->getPassport();
  32.         if (!$passport instanceof UserPassportInterface || !$passport->hasBadge(PasswordUpgradeBadge::class)) {
  33.             return;
  34.         }
  35.         /** @var PasswordUpgradeBadge $badge */
  36.         $badge $passport->getBadge(PasswordUpgradeBadge::class);
  37.         $plaintextPassword $badge->getAndErasePlaintextPassword();
  38.         if ('' === $plaintextPassword) {
  39.             return;
  40.         }
  41.         $user $passport->getUser();
  42.         $passwordEncoder $this->encoderFactory->getEncoder($user);
  43.         if (!$passwordEncoder->needsRehash($user->getPassword())) {
  44.             return;
  45.         }
  46.         $badge->getPasswordUpgrader()->upgradePassword($user$passwordEncoder->encodePassword($plaintextPassword$user->getSalt()));
  47.     }
  48.     public static function getSubscribedEvents(): array
  49.     {
  50.         return [LoginSuccessEvent::class => 'onLoginSuccess'];
  51.     }
  52. }