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

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\PostAuthorizationEvent;
  13. use FOS\OAuthServerBundle\Event\PreAuthorizationEvent;
  14. use FOS\OAuthServerBundle\Form\Handler\AuthorizeFormHandler;
  15. use FOS\OAuthServerBundle\Model\ClientInterface;
  16. use FOS\OAuthServerBundle\Model\ClientManagerInterface;
  17. use OAuth2\OAuth2;
  18. use OAuth2\OAuth2ServerException;
  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. use Twig\Environment as TwigEnvironment;
  31. /**
  32. * Controller handling basic authorization.
  33. *
  34. * @author Chris Jones <leeked@gmail.com>
  35. */
  36. class AuthorizeController
  37. {
  38. /**
  39. * @var ClientInterface
  40. */
  41. private $client;
  42. /**
  43. * @var SessionInterface
  44. */
  45. private $session;
  46. /**
  47. * @var Form
  48. */
  49. private $authorizeForm;
  50. /**
  51. * @var AuthorizeFormHandler
  52. */
  53. private $authorizeFormHandler;
  54. /**
  55. * @var OAuth2
  56. */
  57. private $oAuth2Server;
  58. /**
  59. * @var RequestStack
  60. */
  61. private $requestStack;
  62. /**
  63. * @var TokenStorageInterface
  64. */
  65. private $tokenStorage;
  66. /**
  67. * @var TwigEnvironment
  68. */
  69. private $twig;
  70. /**
  71. * @var UrlGeneratorInterface
  72. */
  73. private $router;
  74. /**
  75. * @var ClientManagerInterface
  76. */
  77. private $clientManager;
  78. /**
  79. * @var EventDispatcherInterface
  80. */
  81. private $eventDispatcher;
  82. /**
  83. * This controller had been made as a service due to support symfony 4 where all* services are private by default.
  84. * Thus, this is considered a bad practice to fetch services directly from container.
  85. *
  86. * @todo This controller could be refactored to not rely on so many dependencies
  87. *
  88. * @param SessionInterface $session
  89. */
  90. public function __construct(
  91. RequestStack $requestStack,
  92. Form $authorizeForm,
  93. AuthorizeFormHandler $authorizeFormHandler,
  94. OAuth2 $oAuth2Server,
  95. TokenStorageInterface $tokenStorage,
  96. UrlGeneratorInterface $router,
  97. ClientManagerInterface $clientManager,
  98. EventDispatcherInterface $eventDispatcher,
  99. TwigEnvironment $twig,
  100. SessionInterface $session = null
  101. ) {
  102. $this->requestStack = $requestStack;
  103. $this->session = $session;
  104. $this->authorizeForm = $authorizeForm;
  105. $this->authorizeFormHandler = $authorizeFormHandler;
  106. $this->oAuth2Server = $oAuth2Server;
  107. $this->tokenStorage = $tokenStorage;
  108. $this->router = $router;
  109. $this->clientManager = $clientManager;
  110. $this->eventDispatcher = $eventDispatcher;
  111. $this->twig = $twig;
  112. }
  113. /**
  114. * Authorize.
  115. */
  116. public function authorizeAction(Request $request)
  117. {
  118. $user = $this->tokenStorage->getToken()->getUser();
  119. if (!$user instanceof UserInterface) {
  120. throw new AccessDeniedException('This user does not have access to this section.');
  121. }
  122. if ($this->session && true === $this->session->get('_fos_oauth_server.ensure_logout')) {
  123. $this->session->invalidate(600);
  124. $this->session->set('_fos_oauth_server.ensure_logout', true);
  125. }
  126. $form = $this->authorizeForm;
  127. $formHandler = $this->authorizeFormHandler;
  128. /** @var PreAuthorizationEvent $event */
  129. $event = $this->eventDispatcher->dispatch(new PreAuthorizationEvent($user, $this->getClient()));
  130. if ($event->isAuthorizedClient()) {
  131. $scope = $request->get('scope', null);
  132. return $this->oAuth2Server->finishClientAuthorization(true, $user, $request, $scope);
  133. }
  134. if (true === $formHandler->process()) {
  135. return $this->processSuccess($user, $formHandler, $request);
  136. }
  137. return $this->renderAuthorize([
  138. 'form' => $form->createView(),
  139. 'client' => $this->getClient(),
  140. ]);
  141. }
  142. /**
  143. * @return Response
  144. */
  145. protected function processSuccess(UserInterface $user, AuthorizeFormHandler $formHandler, Request $request)
  146. {
  147. if ($this->session && true === $this->session->get('_fos_oauth_server.ensure_logout')) {
  148. $this->tokenStorage->setToken(null);
  149. $this->session->invalidate();
  150. }
  151. $this->eventDispatcher->dispatch(new PostAuthorizationEvent($user, $this->getClient(), $formHandler->isAccepted()));
  152. $formName = $this->authorizeForm->getName();
  153. if (!$request->query->all() && $request->request->has($formName)) {
  154. $request->query->add($request->request->get($formName));
  155. }
  156. try {
  157. return $this->oAuth2Server
  158. ->finishClientAuthorization($formHandler->isAccepted(), $user, $request, $formHandler->getScope())
  159. ;
  160. } catch (OAuth2ServerException $e) {
  161. return $e->getHttpResponse();
  162. }
  163. }
  164. /**
  165. * Generate the redirection url when the authorize is completed.
  166. *
  167. * @return string
  168. */
  169. protected function getRedirectionUrl(UserInterface $user)
  170. {
  171. return $this->router->generate('fos_oauth_server_profile_show');
  172. }
  173. /**
  174. * @return ClientInterface
  175. */
  176. protected function getClient()
  177. {
  178. if (null !== $this->client) {
  179. return $this->client;
  180. }
  181. if (null === $request = $this->getCurrentRequest()) {
  182. throw new NotFoundHttpException('Client not found.');
  183. }
  184. if (null === $clientId = $request->get('client_id')) {
  185. $formData = $request->get($this->authorizeForm->getName(), []);
  186. $clientId = isset($formData['client_id']) ? $formData['client_id'] : null;
  187. }
  188. $this->client = $this->clientManager->findClientByPublicId($clientId);
  189. if (null === $this->client) {
  190. throw new NotFoundHttpException('Client not found.');
  191. }
  192. return $this->client;
  193. }
  194. protected function renderAuthorize(array $context): Response
  195. {
  196. return new Response(
  197. $this->twig->render('@FOSOAuthServer/Authorize/authorize.html.twig', $context)
  198. );
  199. }
  200. /**
  201. * @return Request|null
  202. */
  203. private function getCurrentRequest()
  204. {
  205. $request = $this->requestStack->getCurrentRequest();
  206. if (null === $request) {
  207. throw new \RuntimeException('No current request.');
  208. }
  209. return $request;
  210. }
  211. }