src/EventListener/AuthorizationRequestResolverListener.php line 23

Open in your IDE?
  1. <?php
  2. namespace App\EventListener;
  3. use Psr\Log\LoggerInterface;
  4. use League\Bundle\OAuth2ServerBundle\Event\AuthorizationRequestResolveEvent;
  5. use Symfony\Component\HttpFoundation\RequestStack;
  6. use Symfony\Component\HttpFoundation\RedirectResponse;
  7. use Symfony\Component\HttpFoundation\Session\SessionInterface;
  8. use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
  9. use Symfony\Component\Routing\RouterInterface;
  10. use App\Entity\User;
  11. class AuthorizationRequestResolverListener {
  12.     private $symfonyUserKey 'symfony_username';
  13.     private LoggerInterface $logger;
  14.     private RequestStack $requestStack;
  15.     private RouterInterface $router;
  16.     private SessionInterface $session;
  17.     private TokenStorageInterface $tokenStorage;
  18.     public function __construct(RequestStack $requestStackRouterInterface $router,
  19.             LoggerInterface $loggerTokenStorageInterface $tokenStorage) {
  20.         $this->logger $logger;
  21.         $this->requestStack $requestStack;
  22.         $this->router $router;
  23.         $this->session $this->requestStack->getSession();
  24.         $this->tokenStorage $tokenStorage;
  25.     }
  26.     public function resolve(AuthorizationRequestResolveEvent $event) {
  27.         $token $this->tokenStorage->getToken();
  28.         if (empty($token)) {
  29.             $this->redirectLogin($event);
  30.             return;
  31.         }
  32.         $user $token->getUser();
  33.         if (empty($user)) {
  34.             $this->redirectLogin($event);
  35.             return;
  36.         }
  37.         $this->resolveAuthorization($event$user);
  38.     }
  39.     private function resolveAuthorization(AuthorizationRequestResolveEvent $eventUser $user) {
  40.         /* set data for further processing in league oauth2 server */
  41.         $event->resolveAuthorization(true);
  42.         $event->setUser($user);
  43.         /* remove session value */
  44.         $this->session->remove($this->symfonyUserKey);
  45.     }
  46.     private function redirectLogin(AuthorizationRequestResolveEvent $event) {
  47.         $request $this->requestStack->getCurrentRequest();
  48.         $parameters $request->query->all();
  49.         $location $this->router->generate('oauth2_login'$parameters);
  50.         $redirectResponse = new RedirectResponse($location);
  51.         $event->setResponse($redirectResponse);
  52.     }
  53. }