You are here

public function OAuth2ControllerBase::redirectToProvider in Social Post 8.2

Same name and namespace in other branches
  1. 3.x src/Controller/OAuth2ControllerBase.php \Drupal\social_post\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 133

Class

OAuth2ControllerBase
Handle responses for Social Post implementer controllers.

Namespace

Drupal\social_post\Controller

Code

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('entity.user.edit_form', [
          'user' => $this->userAuthenticator
            ->currentUser()
            ->id(),
        ]);
      }

      // 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);
      return new TrustedRedirectResponse($auth_url);
    } catch (\Exception $e) {
      $this
        ->messenger()
        ->addError($this
        ->t('There has been an error during authentication.'));
      $this
        ->getLogger($this->pluginId)
        ->error($e
        ->getMessage());
      return $this
        ->redirect('entity.user.edit_form', [
        'user' => $this->userAuthenticator
          ->currentUser()
          ->id(),
      ]);
    }
  });

  // Add bubbleable metadata to the response.
  if ($response instanceof TrustedRedirectResponse && !$context
    ->isEmpty()) {
    $bubbleable_metadata = $context
      ->pop();
    $response
      ->addCacheableDependency($bubbleable_metadata);
  }
  return $response;
}