<?php
namespace App\EventListener;
use Psr\Log\LoggerInterface;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Routing\RouterInterface;
use League\Bundle\OAuth2ServerBundle\Event\AuthorizationRequestResolveEvent;
use App\Entity\User;
class AuthorizationRequestResolverListener {
private $symfonyUserKey = 'symfony_username';
private LoggerInterface $logger;
private RequestStack $requestStack;
private RouterInterface $router;
private SessionInterface $session;
private TokenStorageInterface $tokenStorage;
public function __construct(RequestStack $requestStack, RouterInterface $router,
LoggerInterface $logger, TokenStorageInterface $tokenStorage) {
$this->logger = $logger;
$this->requestStack = $requestStack;
$this->router = $router;
$this->session = $this->requestStack->getSession();
$this->tokenStorage = $tokenStorage;
}
public function resolve(AuthorizationRequestResolveEvent $event) {
$token = $this->tokenStorage->getToken();
if (empty($token)) {
$this->redirectLogin($event);
return;
}
$user = $token->getUser();
if (empty($user)) {
$this->redirectLogin($event);
return;
}
$this->resolveAuthorization($event, $user);
}
private function resolveAuthorization(AuthorizationRequestResolveEvent $event, User $user) {
/* set data for further processing in league oauth2 server */
$event->resolveAuthorization(true);
$event->setUser($user);
/* remove session value */
$this->session->remove($this->symfonyUserKey);
}
private function redirectLogin(AuthorizationRequestResolveEvent $event) {
$request = $this->requestStack->getCurrentRequest();
$parameters = $request->query->all();
$location = $this->router->generate('oauth2_login', $parameters);
$redirectResponse = new RedirectResponse($location);
$event->setResponse($redirectResponse);
}
}