You are here

public function OAuth2ControllerBase::processCallback in Social Post 3.x

Same name and namespace in other branches
  1. 8.2 src/Controller/OAuth2ControllerBase.php \Drupal\social_post\Controller\OAuth2ControllerBase::processCallback()

Process implementer callback path.

Return value

\League\OAuth2\Client\Provider\GenericResourceOwner|null The user info if successful. Null otherwise.

File

src/Controller/OAuth2ControllerBase.php, line 189

Class

OAuth2ControllerBase
Handle responses for Social Post implementer controllers.

Namespace

Drupal\social_post\Controller

Code

public function processCallback() {
  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 NULL;
    }
    $state = $this->dataHandler
      ->get('oauth2state');

    // Retrieves $_GET['state'].
    $retrievedState = $this->request
      ->getCurrentRequest()->query
      ->get('state');
    if (empty($retrievedState) || $retrievedState !== $state) {
      $this->userAuthenticator
        ->nullifySessionKeys();
      $this
        ->messenger()
        ->addError($this
        ->t('Login failed. Invalid OAuth2 state.'));
      return NULL;
    }
    $this->providerManager
      ->setClient($client)
      ->authenticate();

    // Gets user's info from provider.
    if (!($profile = $this->providerManager
      ->getUserInfo())) {
      $this
        ->messenger()
        ->addError($this
        ->t('Login failed, could not load user profile. Contact site administrator.'));
      return NULL;
    }
    return $profile;
  } catch (\Exception $e) {
    $this
      ->messenger()
      ->addError($this
      ->t('There has been an error during authentication.'));
    $this
      ->getLogger($this->pluginId)
      ->error($e
      ->getMessage());
    return NULL;
  }
}