vendor/friendsofsymfony/oauth-server-bundle/Controller/AuthorizeController.php line 149

Open in your IDE?
  1. <?php
  2. declare(strict_types=1);
  3. /*
  4.  * This file is part of the FOSOAuthServerBundle package.
  5.  *
  6.  * (c) FriendsOfSymfony <http://friendsofsymfony.github.com/>
  7.  *
  8.  * For the full copyright and license information, please view the LICENSE
  9.  * file that was distributed with this source code.
  10.  */
  11. namespace FOS\OAuthServerBundle\Controller;
  12. use FOS\OAuthServerBundle\Event\OAuthEvent;
  13. use FOS\OAuthServerBundle\Form\Handler\AuthorizeFormHandler;
  14. use FOS\OAuthServerBundle\Model\ClientInterface;
  15. use FOS\OAuthServerBundle\Model\ClientManagerInterface;
  16. use OAuth2\OAuth2;
  17. use OAuth2\OAuth2ServerException;
  18. use Symfony\Bundle\FrameworkBundle\Templating\EngineInterface;
  19. use Symfony\Component\EventDispatcher\EventDispatcherInterface;
  20. use Symfony\Component\Form\Form;
  21. use Symfony\Component\HttpFoundation\Request;
  22. use Symfony\Component\HttpFoundation\RequestStack;
  23. use Symfony\Component\HttpFoundation\Response;
  24. use Symfony\Component\HttpFoundation\Session\SessionInterface;
  25. use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
  26. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  27. use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
  28. use Symfony\Component\Security\Core\Exception\AccessDeniedException;
  29. use Symfony\Component\Security\Core\User\UserInterface;
  30. /**
  31.  * Controller handling basic authorization.
  32.  *
  33.  * @author Chris Jones <leeked@gmail.com>
  34.  */
  35. class AuthorizeController
  36. {
  37.     /**
  38.      * @var ClientInterface
  39.      */
  40.     private $client;
  41.     /**
  42.      * @var SessionInterface
  43.      */
  44.     private $session;
  45.     /**
  46.      * @var Form
  47.      */
  48.     private $authorizeForm;
  49.     /**
  50.      * @var AuthorizeFormHandler
  51.      */
  52.     private $authorizeFormHandler;
  53.     /**
  54.      * @var OAuth2
  55.      */
  56.     private $oAuth2Server;
  57.     /**
  58.      * @var EngineInterface
  59.      */
  60.     private $templating;
  61.     /**
  62.      * @var RequestStack
  63.      */
  64.     private $requestStack;
  65.     /**
  66.      * @var TokenStorageInterface
  67.      */
  68.     private $tokenStorage;
  69.     /**
  70.      * @var UrlGeneratorInterface
  71.      */
  72.     private $router;
  73.     /**
  74.      * @var ClientManagerInterface
  75.      */
  76.     private $clientManager;
  77.     /**
  78.      * @var string
  79.      */
  80.     private $templateEngineType;
  81.     /**
  82.      * @var EventDispatcherInterface
  83.      */
  84.     private $eventDispatcher;
  85.     /**
  86.      * This controller had been made as a service due to support symfony 4 where all* services are private by default.
  87.      * Thus, this is considered a bad practice to fetch services directly from container.
  88.      *
  89.      * @todo This controller could be refactored to not rely on so many dependencies
  90.      *
  91.      * @param RequestStack             $requestStack
  92.      * @param Form                     $authorizeForm
  93.      * @param AuthorizeFormHandler     $authorizeFormHandler
  94.      * @param OAuth2                   $oAuth2Server
  95.      * @param EngineInterface          $templating
  96.      * @param TokenStorageInterface    $tokenStorage
  97.      * @param UrlGeneratorInterface    $router
  98.      * @param ClientManagerInterface   $clientManager
  99.      * @param EventDispatcherInterface $eventDispatcher
  100.      * @param SessionInterface         $session
  101.      * @param string                   $templateEngineType
  102.      */
  103.     public function __construct(
  104.         RequestStack $requestStack,
  105.         Form $authorizeForm,
  106.         AuthorizeFormHandler $authorizeFormHandler,
  107.         OAuth2 $oAuth2Server,
  108.         EngineInterface $templating,
  109.         TokenStorageInterface $tokenStorage,
  110.         UrlGeneratorInterface $router,
  111.         ClientManagerInterface $clientManager,
  112.         EventDispatcherInterface $eventDispatcher,
  113.         SessionInterface $session null,
  114.         $templateEngineType 'twig'
  115.     ) {
  116.         $this->requestStack $requestStack;
  117.         $this->session $session;
  118.         $this->authorizeForm $authorizeForm;
  119.         $this->authorizeFormHandler $authorizeFormHandler;
  120.         $this->oAuth2Server $oAuth2Server;
  121.         $this->templating $templating;
  122.         $this->tokenStorage $tokenStorage;
  123.         $this->router $router;
  124.         $this->clientManager $clientManager;
  125.         $this->templateEngineType $templateEngineType;
  126.         $this->eventDispatcher $eventDispatcher;
  127.     }
  128.     /**
  129.      * Authorize.
  130.      */
  131.     public function authorizeAction(Request $request)
  132.     {
  133.         $user $this->tokenStorage->getToken()->getUser();
  134.         if (!$user instanceof UserInterface) {
  135.             throw new AccessDeniedException('This user does not have access to this section.');
  136.         }
  137.         if ($this->session && true === $this->session->get('_fos_oauth_server.ensure_logout')) {
  138.             $this->session->invalidate(600);
  139.             $this->session->set('_fos_oauth_server.ensure_logout'true);
  140.         }
  141.         $form $this->authorizeForm;
  142.         $formHandler $this->authorizeFormHandler;
  143.         /** @var OAuthEvent $event */
  144.         $event $this->eventDispatcher->dispatch(
  145.             OAuthEvent::PRE_AUTHORIZATION_PROCESS,
  146.             new OAuthEvent($user$this->getClient())
  147.         );
  148.         if ($event->isAuthorizedClient()) {
  149.             $scope $request->get('scope'null);
  150.             return $this->oAuth2Server->finishClientAuthorization(true$user$request$scope);
  151.         }
  152.         if (true === $formHandler->process()) {
  153.             return $this->processSuccess($user$formHandler$request);
  154.         }
  155.         $data = [
  156.             'form' => $form->createView(),
  157.             'client' => $this->getClient(),
  158.         ];
  159.         return $this->renderAuthorize($data$this->templating$this->templateEngineType);
  160.     }
  161.     /**
  162.      * @param UserInterface        $user
  163.      * @param AuthorizeFormHandler $formHandler
  164.      * @param Request              $request
  165.      *
  166.      * @return Response
  167.      */
  168.     protected function processSuccess(UserInterface $userAuthorizeFormHandler $formHandlerRequest $request)
  169.     {
  170.         if ($this->session && true === $this->session->get('_fos_oauth_server.ensure_logout')) {
  171.             $this->tokenStorage->setToken(null);
  172.             $this->session->invalidate();
  173.         }
  174.         $this->eventDispatcher->dispatch(
  175.             OAuthEvent::POST_AUTHORIZATION_PROCESS,
  176.             new OAuthEvent($user$this->getClient(), $formHandler->isAccepted())
  177.         );
  178.         $formName $this->authorizeForm->getName();
  179.         if (!$request->query->all() && $request->request->has($formName)) {
  180.             $request->query->add($request->request->get($formName));
  181.         }
  182.         try {
  183.             return $this->oAuth2Server
  184.                 ->finishClientAuthorization($formHandler->isAccepted(), $user$request$formHandler->getScope())
  185.             ;
  186.         } catch (OAuth2ServerException $e) {
  187.             return $e->getHttpResponse();
  188.         }
  189.     }
  190.     /**
  191.      * Generate the redirection url when the authorize is completed.
  192.      *
  193.      * @param UserInterface $user
  194.      *
  195.      * @return string
  196.      */
  197.     protected function getRedirectionUrl(UserInterface $user)
  198.     {
  199.         return $this->router->generate('fos_oauth_server_profile_show');
  200.     }
  201.     /**
  202.      * @return ClientInterface
  203.      */
  204.     protected function getClient()
  205.     {
  206.         if (null !== $this->client) {
  207.             return $this->client;
  208.         }
  209.         if (null === $request $this->getCurrentRequest()) {
  210.             throw new NotFoundHttpException('Client not found.');
  211.         }
  212.         if (null === $clientId $request->get('client_id')) {
  213.             $formData $request->get($this->authorizeForm->getName(), []);
  214.             $clientId = isset($formData['client_id']) ? $formData['client_id'] : null;
  215.         }
  216.         $this->client $this->clientManager->findClientByPublicId($clientId);
  217.         if (null === $this->client) {
  218.             throw new NotFoundHttpException('Client not found.');
  219.         }
  220.         return $this->client;
  221.     }
  222.     /**
  223.      * @throws \RuntimeException
  224.      */
  225.     protected function renderAuthorize(array $dataEngineInterface $enginestring $engineType): Response
  226.     {
  227.         return $engine->renderResponse(
  228.             '@FOSOAuthServer/Authorize/authorize.html.'.$engineType,
  229.             $data
  230.         );
  231.     }
  232.     /**
  233.      * @return null|Request
  234.      */
  235.     private function getCurrentRequest()
  236.     {
  237.         $request $this->requestStack->getCurrentRequest();
  238.         if (null === $request) {
  239.             throw new \RuntimeException('No current request.');
  240.         }
  241.         return $request;
  242.     }
  243. }