src/Subscriber/AdminAuthenticationSubscriber.php line 45

Open in your IDE?
  1. <?php
  2. namespace App\Subscriber;
  3. use App\Entity\Local\AdminUser;
  4. use Oz\ApiNvl\Model\User;
  5. use Doctrine\ORM\EntityManagerInterface;
  6. use League\OAuth2\Client\Provider\Exception\IdentityProviderException;
  7. use League\OAuth2\Client\Provider\GenericProvider;
  8. use LogicException;
  9. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  10. use Symfony\Component\Security\Http\Event\InteractiveLoginEvent;
  11. use Symfony\Component\Security\Http\SecurityEvents;
  12. class AdminAuthenticationSubscriber implements EventSubscriberInterface
  13. {
  14.     /**
  15.      * @var EntityManagerInterface
  16.      */
  17.     private $em;
  18.     /**
  19.      * @param EntityManagerInterface $em
  20.      */
  21.     public function __construct(EntityManagerInterface $em)
  22.     {
  23.         $this->em $em;
  24.     }
  25.     /**
  26.      * @return array[]
  27.      */
  28.     public static function getSubscribedEvents(): array
  29.     {
  30.         return [
  31.             SecurityEvents::INTERACTIVE_LOGIN => ['interactiveLogin'15],
  32.         ];
  33.     }
  34.     /**
  35.      * @param InteractiveLoginEvent $interactiveLoginEvent
  36.      *
  37.      */
  38.     public function interactiveLogin(InteractiveLoginEvent $interactiveLoginEvent): void
  39.     {
  40.         /** @var User $user */
  41.         $user $interactiveLoginEvent->getAuthenticationToken()->getUser();
  42.         if (!$user instanceof AdminUser) {
  43.             return;
  44.         }
  45.         $this->updateAdminUser($user);
  46.     }
  47.     /**
  48.      * @param AdminUser $user
  49.      *
  50.      * @return void
  51.      */
  52.     private function updateAdminUser(AdminUser $user)
  53.     {
  54.         $params = [
  55.             'clientId'                => $_ENV['ADMIN_TOKEN_CLIENT_ID'],
  56.             'clientSecret'            => $_ENV['ADMIN_TOKEN_CLIENT_SECRET'],
  57.             'urlAuthorize'            => $_ENV['URL_MON_COMPTE'] . '/provider/connect/authorize',
  58.             'urlAccessToken'          => $_ENV['URL_MON_COMPTE'] . '/provider/connect/token',
  59.             'urlResourceOwnerDetails' => $_ENV['URL_MON_COMPTE'] . '/provider/connect/resource',
  60.         ];
  61.         $provider = new GenericProvider($params);
  62.         try {
  63.             $accessToken $provider->getAccessToken('client_credentials', [
  64.                 'scope' => 'api.dynamic.admin.full',
  65.             ]);
  66.         }
  67.         catch (IdentityProviderException $e) {
  68.             throw new LogicException($e->getMessage());
  69.         }
  70.         $user->setOauthToken($accessToken);
  71.         $this->em->persist($user);
  72.         $this->em->flush();
  73.     }
  74. }