public function OAuth2ControllerBase::redirectToProvider in Social Auth 8.2
Same name and namespace in other branches
- 3.x src/Controller/OAuth2ControllerBase.php \Drupal\social_auth\Controller\OAuth2ControllerBase::redirectToProvider()
Response for implementer authentication url.
Redirects the user to provider for authentication.
This is done in a render context in order to bubble cacheable metadata created during authentication URL generation.
See also
https://www.drupal.org/project/social_auth/issues/3033444
File
- src/
Controller/ OAuth2ControllerBase.php, line 160
Class
- OAuth2ControllerBase
- Handle responses for Social Auth implementer controllers.
Namespace
Drupal\social_auth\ControllerCode
public function redirectToProvider() {
$context = new RenderContext();
/** @var \Drupal\Core\Routing\TrustedRedirectResponse|\Symfony\Component\HttpFoundation\RedirectResponse $response */
$response = $this->renderer
->executeInRenderContext($context, function () {
try {
/** @var \League\OAuth2\Client\Provider\AbstractProvider|false $client */
$client = $this->networkManager
->createInstance($this->pluginId)
->getSdk();
// If provider client could not be obtained.
if (!$client) {
$this->messenger
->addError($this
->t('%module not configured properly. Contact site administrator.', [
'%module' => $this->module,
]));
return $this
->redirect('user.login');
}
/*
* If destination parameter is set, save it.
*
* The destination parameter is also _removed_ from the current request
* to prevent it from overriding Social Auth's TrustedRedirectResponse.
*
* @see https://www.drupal.org/project/drupal/issues/2950883
*
* TODO: Remove the remove() call after 2950883 is solved.
*/
$destination = $this->request
->getCurrentRequest()
->get('destination');
if ($destination) {
$this->userAuthenticator
->setDestination($destination);
$this->request
->getCurrentRequest()->query
->remove('destination');
}
// Provider service was returned, inject it to $providerManager.
$this->providerManager
->setClient($client);
// Generates the URL for authentication.
$auth_url = $this->providerManager
->getAuthorizationUrl();
$state = $this->providerManager
->getState();
$this->dataHandler
->set('oauth2state', $state);
$this->userAuthenticator
->dispatchBeforeRedirect($destination);
return new TrustedRedirectResponse($auth_url);
} catch (PluginException $exception) {
$this->messenger
->addError($this
->t('There has been an error when creating plugin.'));
return $this
->redirect('user.login');
}
});
// Add bubbleable metadata to the response.
if ($response instanceof TrustedRedirectResponse && !$context
->isEmpty()) {
$bubbleable_metadata = $context
->pop();
$response
->addCacheableDependency($bubbleable_metadata);
}
return $response;
}