Skip to content

Commit 89d7868

Browse files
authored
Merge pull request #1800 from stloyd/symfony-6
Maintain | Add support for Symfony 6
2 parents 7128fd1 + d6569e3 commit 89d7868

40 files changed

Lines changed: 1041 additions & 605 deletions

CHANGELOG.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ Changelog
22
=========
33
## 2.0.0 (2021-xx-xx)
44
* BC Break: Dropped PHP 7.3 support,
5+
* BC Break: Dropped support for Symfony: >=5.1 & <5.4,
56
* BC Break: `OAuthExtension` is now a lazy Twig extension using a Runtime,
67
* BC Break: removed support for `FOSUserBundle`,
78
* BC Break: changed `process()` argument for `Form/RegistrationFormHandlerInterface`, from `Form $form` to `FormInterface $form`,
@@ -19,6 +20,8 @@ Changelog
1920
* BC Break: changed `__construct()` argument for `OAuth/ResourceOwner/AbstractResourceOwner`, from `HttpMethodsClient $httpClient` to `HttpClientInterface $httpClient`,
2021
* BC Break: replaced `php-http/httplug-bundle` with `symfony/http-client`
2122
* BC Break: removed `hwi_oauth.http` configuration
23+
* Added support for PHP 8.1,
24+
* Added support for Symfony 5.6,
2225

2326
## 1.4.2 (2021-08-09)
2427
* Bugfix: remove `@final` declaration from `OAuthFactory` & `FOSUBUserProvider`,

Controller/ConnectController.php

Lines changed: 68 additions & 43 deletions
Original file line numberDiff line numberDiff line change
@@ -22,33 +22,47 @@
2222
use HWI\Bundle\OAuthBundle\Security\Core\Exception\AccountNotLinkedException;
2323
use HWI\Bundle\OAuthBundle\Security\Http\ResourceOwnerMapLocator;
2424
use HWI\Bundle\OAuthBundle\Security\OAuthUtils;
25-
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
2625
use Symfony\Component\EventDispatcher\Event as DeprecatedEvent;
27-
use Symfony\Component\Form\Extension\Core\Type\FormType;
26+
use Symfony\Component\Form\FormFactoryInterface;
27+
use Symfony\Component\HttpFoundation\RedirectResponse;
2828
use Symfony\Component\HttpFoundation\Request;
2929
use Symfony\Component\HttpFoundation\RequestStack;
3030
use Symfony\Component\HttpFoundation\Response;
3131
use Symfony\Component\HttpFoundation\Session\SessionInterface;
3232
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
33+
use Symfony\Component\Routing\RouterInterface;
3334
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
35+
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
36+
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
3437
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
3538
use Symfony\Component\Security\Core\Exception\AccountStatusException;
3639
use Symfony\Component\Security\Core\User\UserCheckerInterface;
3740
use Symfony\Component\Security\Core\User\UserInterface;
3841
use Symfony\Component\Security\Http\Event\InteractiveLoginEvent;
3942
use Symfony\Component\Security\Http\SecurityEvents;
4043
use Symfony\Contracts\EventDispatcher\Event;
44+
use Symfony\Contracts\EventDispatcher\EventDispatcherInterface;
45+
use Twig\Environment;
4146

4247
/**
4348
* @author Alexander <iam.asm89@gmail.com>
4449
*
4550
* @internal
4651
*/
47-
final class ConnectController extends AbstractController
52+
final class ConnectController
4853
{
4954
private OAuthUtils $oauthUtils;
5055
private ResourceOwnerMapLocator $resourceOwnerMapLocator;
5156
private RequestStack $requestStack;
57+
private EventDispatcherInterface $dispatcher;
58+
private TokenStorageInterface $tokenStorage;
59+
private AccountConnectorInterface $accountConnector;
60+
private UserCheckerInterface $userChecker;
61+
private RegistrationFormHandlerInterface $formHandler;
62+
private AuthorizationCheckerInterface $authorizationChecker;
63+
private FormFactoryInterface $formFactory;
64+
private Environment $twig;
65+
private RouterInterface $router;
5266
private bool $enableConnect;
5367
private string $grantRule;
5468
private bool $failedUseReferer;
@@ -64,6 +78,15 @@ public function __construct(
6478
OAuthUtils $oauthUtils,
6579
ResourceOwnerMapLocator $resourceOwnerMapLocator,
6680
RequestStack $requestStack,
81+
EventDispatcherInterface $dispatcher,
82+
TokenStorageInterface $tokenStorage,
83+
AccountConnectorInterface $accountConnector,
84+
UserCheckerInterface $userChecker,
85+
RegistrationFormHandlerInterface $formHandler,
86+
AuthorizationCheckerInterface $authorizationChecker,
87+
FormFactoryInterface $formFactory,
88+
Environment $twig,
89+
RouterInterface $router,
6790
bool $enableConnect,
6891
string $grantRule,
6992
bool $failedUseReferer,
@@ -82,6 +105,15 @@ public function __construct(
82105
$this->enableConnectConfirmation = $enableConnectConfirmation;
83106
$this->firewallNames = $firewallNames;
84107
$this->registrationForm = $registrationForm;
108+
$this->dispatcher = $dispatcher;
109+
$this->accountConnector = $accountConnector;
110+
$this->tokenStorage = $tokenStorage;
111+
$this->userChecker = $userChecker;
112+
$this->formHandler = $formHandler;
113+
$this->authorizationChecker = $authorizationChecker;
114+
$this->formFactory = $formFactory;
115+
$this->twig = $twig;
116+
$this->router = $router;
85117
}
86118

87119
/**
@@ -100,7 +132,7 @@ public function registrationAction(Request $request, string $key): Response
100132
throw new NotFoundHttpException();
101133
}
102134

103-
$hasUser = $this->isGranted($this->grantRule);
135+
$hasUser = $this->authorizationChecker->isGranted($this->grantRule);
104136
if ($hasUser) {
105137
throw new AccessDeniedException('Cannot connect already registered account.');
106138
}
@@ -124,28 +156,24 @@ public function registrationAction(Request $request, string $key): Response
124156
->getUserInformation($error->getRawToken())
125157
;
126158

127-
$form = $this->createForm($this->registrationForm);
159+
$form = $this->formFactory->create($this->registrationForm);
128160

129-
/** @var RegistrationFormHandlerInterface $formHandler */
130-
$formHandler = $this->get('hwi_oauth.registration.form.handler');
131-
if ($formHandler->process($request, $form, $userInformation)) {
161+
if ($this->formHandler->process($request, $form, $userInformation)) {
132162
$event = new FormEvent($form, $request);
133163
$this->dispatch($event, HWIOAuthEvents::REGISTRATION_SUCCESS);
134164

135-
/** @var AccountConnectorInterface $connector */
136-
$connector = $this->get('hwi_oauth.account.connector');
137-
$connector->connect($form->getData(), $userInformation);
165+
$this->accountConnector->connect($form->getData(), $userInformation);
138166

139167
// Authenticate the user
140168
$this->authenticateUser($request, $form->getData(), $error->getResourceOwnerName(), $error->getAccessToken());
141169

142170
if (null === $response = $event->getResponse()) {
143171
if ($targetPath = $this->getTargetPath($session)) {
144-
$response = $this->redirect($targetPath);
172+
$response = new RedirectResponse($targetPath);
145173
} else {
146-
$response = $this->render('@HWIOAuth/Connect/registration_success.html.twig', [
174+
$response = new Response($this->twig->render('@HWIOAuth/Connect/registration_success.html.twig', [
147175
'userInformation' => $userInformation,
148-
]);
176+
]));
149177
}
150178
}
151179

@@ -167,11 +195,11 @@ public function registrationAction(Request $request, string $key): Response
167195
return $response;
168196
}
169197

170-
return $this->render('@HWIOAuth/Connect/registration.html.twig', [
198+
return new Response($this->twig->render('@HWIOAuth/Connect/registration.html.twig', [
171199
'key' => $key,
172200
'form' => $form->createView(),
173201
'userInformation' => $userInformation,
174-
]);
202+
]));
175203
}
176204

177205
/**
@@ -189,7 +217,7 @@ public function connectServiceAction(Request $request, string $service): Respons
189217
throw new NotFoundHttpException();
190218
}
191219

192-
$hasUser = $this->isGranted($this->grantRule);
220+
$hasUser = $this->authorizationChecker->isGranted($this->grantRule);
193221
if (!$hasUser) {
194222
throw new AccessDeniedException('Cannot connect an account.');
195223
}
@@ -222,38 +250,41 @@ public function connectServiceAction(Request $request, string $service): Respons
222250
// Redirect to the login path if the token is empty (Eg. User cancelled auth)
223251
if (null === $accessToken) {
224252
if ($this->failedUseReferer && $targetPath = $this->getTargetPath($session)) {
225-
return $this->redirect($targetPath);
253+
return new RedirectResponse($targetPath);
226254
}
227255

228-
return $this->redirectToRoute($this->failedAuthPath);
256+
return new RedirectResponse($this->router->generate($this->failedAuthPath));
229257
}
230258

231259
// Show confirmation page?
232260
if (!$this->enableConnectConfirmation) {
233261
return $this->getConfirmationResponse($request, $accessToken, $service);
234262
}
235263

236-
$form = $this->createForm(FormType::class);
264+
$form = $this->formFactory->create();
237265
$form->handleRequest($request);
238266

239267
if ($form->isSubmitted() && $form->isValid()) {
240268
return $this->getConfirmationResponse($request, $accessToken, $service);
241269
}
242270

243-
$event = new GetResponseUserEvent($this->getUser(), $request);
271+
/** @var TokenInterface $token */
272+
$token = $this->tokenStorage->getToken();
273+
274+
$event = new GetResponseUserEvent($token->getUser(), $request);
244275

245276
$this->dispatch($event, HWIOAuthEvents::CONNECT_INITIALIZE);
246277

247278
if ($response = $event->getResponse()) {
248279
return $response;
249280
}
250281

251-
return $this->render('@HWIOAuth/Connect/connect_confirm.html.twig', [
282+
return new Response($this->twig->render('@HWIOAuth/Connect/connect_confirm.html.twig', [
252283
'key' => $key,
253284
'service' => $service,
254285
'form' => $form->createView(),
255286
'userInformation' => $resourceOwner->getUserInformation($accessToken),
256-
]);
287+
]));
257288
}
258289

259290
/**
@@ -285,10 +316,8 @@ private function getResourceOwnerByName(string $name): ResourceOwnerInterface
285316
private function authenticateUser(Request $request, UserInterface $user, string $resourceOwnerName, $accessToken, bool $fakeLogin = true): void
286317
{
287318
try {
288-
/** @var UserCheckerInterface $userChecker */
289-
$userChecker = $this->get('hwi_oauth.user_checker');
290-
$userChecker->checkPreAuth($user);
291-
$userChecker->checkPostAuth($user);
319+
$this->userChecker->checkPreAuth($user);
320+
$this->userChecker->checkPostAuth($user);
292321
} catch (AccountStatusException $e) {
293322
// Don't authenticate locked, disabled or expired users
294323
return;
@@ -297,11 +326,13 @@ private function authenticateUser(Request $request, UserInterface $user, string
297326
$token = new OAuthToken($accessToken, $user->getRoles());
298327
$token->setResourceOwnerName($resourceOwnerName);
299328
$token->setUser($user);
300-
$token->setAuthenticated(true);
301329

302-
/** @var TokenStorageInterface $tokenStorage */
303-
$tokenStorage = $this->get('security.token_storage');
304-
$tokenStorage->setToken($token);
330+
// required for compatibility with Symfony 5.4
331+
if (method_exists($token, 'setAuthenticated')) {
332+
$token->setAuthenticated(true, false);
333+
}
334+
335+
$this->tokenStorage->setToken($token);
305336

306337
if ($fakeLogin) {
307338
// Since we're "faking" normal login, we need to throw our INTERACTIVE_LOGIN event manually
@@ -335,11 +366,8 @@ private function getTargetPath(?SessionInterface $session): ?string
335366
*/
336367
private function getConfirmationResponse(Request $request, array $accessToken, string $service): Response
337368
{
338-
/** @var TokenStorageInterface $tokenStorage */
339-
$tokenStorage = $this->get('security.token_storage');
340-
341369
/** @var OAuthToken $currentToken */
342-
$currentToken = $tokenStorage->getToken();
370+
$currentToken = $this->tokenStorage->getToken();
343371
/** @var UserInterface $currentUser */
344372
$currentUser = $currentToken->getUser();
345373

@@ -349,14 +377,11 @@ private function getConfirmationResponse(Request $request, array $accessToken, s
349377
$event = new GetResponseUserEvent($currentUser, $request);
350378
$this->dispatch($event, HWIOAuthEvents::CONNECT_CONFIRMED);
351379

352-
/** @var AccountConnectorInterface $connector */
353-
$connector = $this->get('hwi_oauth.account.connector');
354-
$connector->connect($currentUser, $userInformation);
380+
$this->accountConnector->connect($currentUser, $userInformation);
355381

356382
if ($currentToken instanceof OAuthToken) {
357383
// Update user token with new details
358384
$newToken =
359-
\is_array($accessToken) &&
360385
(isset($accessToken['access_token']) || isset($accessToken['oauth_token'])) ?
361386
$accessToken : $currentToken->getRawToken();
362387

@@ -365,12 +390,12 @@ private function getConfirmationResponse(Request $request, array $accessToken, s
365390

366391
if (null === $response = $event->getResponse()) {
367392
if ($targetPath = $this->getTargetPath($request->getSession())) {
368-
$response = $this->redirect($targetPath);
393+
$response = new RedirectResponse($targetPath);
369394
} else {
370-
$response = $this->render('@HWIOAuth/Connect/connect_success.html.twig', [
395+
$response = new Response($this->twig->render('@HWIOAuth/Connect/connect_success.html.twig', [
371396
'userInformation' => $userInformation,
372397
'service' => $service,
373-
]);
398+
]));
374399
}
375400
}
376401

@@ -385,7 +410,7 @@ private function getConfirmationResponse(Request $request, array $accessToken, s
385410
*/
386411
private function dispatch($event, string $eventName = null): void
387412
{
388-
$this->get('event_dispatcher')->dispatch($event, $eventName);
413+
$this->dispatcher->dispatch($event, $eventName);
389414
}
390415

391416
private function getSession(): ?SessionInterface

0 commit comments

Comments
 (0)