You are here

public function OpenIDConnect::connectCurrentUser in OpenID Connect / OAuth client 8

Same name and namespace in other branches
  1. 2.x src/OpenIDConnect.php \Drupal\openid_connect\OpenIDConnect::connectCurrentUser()

Connect the current user's account to an external provider.

Parameters

\Drupal\openid_connect\Plugin\OpenIDConnectClientInterface $client: The client.

array $tokens: The tokens as returned from OpenIDConnectClientInterface::retrieveTokens().

Return value

bool TRUE on success, FALSE on failure.

File

src/OpenIDConnect.php, line 421

Class

OpenIDConnect
Main service of the OpenID Connect module.

Namespace

Drupal\openid_connect

Code

public function connectCurrentUser(OpenIDConnectClientInterface $client, array $tokens) {
  if (!$this->currentUser
    ->isAuthenticated()) {
    throw new \RuntimeException('User not logged in');
  }
  $context = $this
    ->buildContext($client, $tokens);
  if ($context === FALSE) {
    return FALSE;
  }
  $account = $context['account'];
  if ($account !== FALSE && $account
    ->id() !== $this->currentUser
    ->id()) {
    $this->messenger
      ->addError($this
      ->t('Another user is already connected to this @provider account.', [
      '@provider' => $client
        ->getPluginId(),
    ]));
    return FALSE;
  }
  if ($account === FALSE) {
    $account = $this->userStorage
      ->load($this->currentUser
      ->id());
    $this->authmap
      ->createAssociation($account, $client
      ->getPluginId(), $context['sub']);
  }
  $always_save_userinfo = $this->configFactory
    ->get('openid_connect.settings')
    ->get('always_save_userinfo');
  if ($always_save_userinfo) {
    $this
      ->saveUserinfo($account, $context);
  }
  $this->moduleHandler
    ->invokeAll('openid_connect_post_authorize', [
    $account,
    $context,
  ]);
  return TRUE;
}