vendor/scheb/2fa-bundle/Security/Http/EventListener/AbstractCheckCodeListener.php line 24

Open in your IDE?
  1. <?php
  2. declare(strict_types=1);
  3. namespace Scheb\TwoFactorBundle\Security\Http\EventListener;
  4. use Scheb\TwoFactorBundle\Security\Http\Authenticator\Passport\Credentials\TwoFactorCodeCredentials;
  5. use Scheb\TwoFactorBundle\Security\TwoFactor\Provider\PreparationRecorderInterface;
  6. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  7. use Symfony\Component\Security\Core\Exception\AuthenticationException;
  8. use Symfony\Component\Security\Http\Event\CheckPassportEvent;
  9. use function assert;
  10. use function sprintf;
  11. /**
  12.  * @internal
  13.  */
  14. abstract class AbstractCheckCodeListener implements EventSubscriberInterface
  15. {
  16.     public function __construct(private PreparationRecorderInterface $preparationRecorder)
  17.     {
  18.     }
  19.     public function checkPassport(CheckPassportEvent $event): void
  20.     {
  21.         $passport $event->getPassport();
  22.         if (!$passport->hasBadge(TwoFactorCodeCredentials::class)) {
  23.             return;
  24.         }
  25.         $credentialsBadge $passport->getBadge(TwoFactorCodeCredentials::class);
  26.         assert($credentialsBadge instanceof TwoFactorCodeCredentials);
  27.         if ($credentialsBadge->isResolved()) {
  28.             return;
  29.         }
  30.         $credentialsBadge $passport->getBadge(TwoFactorCodeCredentials::class);
  31.         assert($credentialsBadge instanceof TwoFactorCodeCredentials);
  32.         $token $credentialsBadge->getTwoFactorToken();
  33.         $providerName $token->getCurrentTwoFactorProvider();
  34.         if (!$providerName) {
  35.             throw new AuthenticationException('There is no active two-factor provider.');
  36.         }
  37.         if (!$this->preparationRecorder->isTwoFactorProviderPrepared($token->getFirewallName(), $providerName)) {
  38.             throw new AuthenticationException(sprintf('The two-factor provider "%s" has not been prepared.'$providerName));
  39.         }
  40.         if (!$this->isValidCode($providerName$token->getUser(), $credentialsBadge->getCode())) {
  41.             return;
  42.         }
  43.         $token->setTwoFactorProviderComplete($providerName);
  44.         $credentialsBadge->markResolved();
  45.     }
  46.     abstract protected function isValidCode(string $providerNameobject $userstring $code): bool;
  47. }