You are here

public function OpenIDConnect::connectCurrentUser in OpenID Connect / OAuth client 2.x

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

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

Parameters

\Drupal\openid_connect\OpenIDConnectClientEntityInterface $client: The client.

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

Return value

bool TRUE on success, FALSE on failure.

Throws

\Exception

File

src/OpenIDConnect.php, line 442

Class

OpenIDConnect
Main service of the OpenID Connect module.

Namespace

Drupal\openid_connect

Code

public function connectCurrentUser(OpenIDConnectClientEntityInterface $client, array $tokens) : bool {
  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 instanceof UserInterface && $account
    ->id() !== $this->currentUser
    ->id()) {
    $this->messenger
      ->addError($this
      ->t('Another user is already connected to this @provider account.', [
      '@provider' => $client
        ->id(),
    ]));
    return FALSE;
  }
  if (!$account instanceof UserInterface) {

    /** @var \Drupal\user\UserInterface $account */
    $account = $this->userStorage
      ->load($this->currentUser
      ->id());
    if ($account) {
      $this->externalAuth
        ->linkExistingAccount($context['sub'], 'openid_connect.' . $client
        ->id(), $account);
    }
  }
  if ($account) {
    $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;
  }
  return FALSE;
}