You are here

public function OpenIDConnectGithubClient::retrieveUserInfo in OpenID Connect / OAuth client 8

Same name and namespace in other branches
  1. 2.x src/Plugin/OpenIDConnectClient/OpenIDConnectGithubClient.php \Drupal\openid_connect\Plugin\OpenIDConnectClient\OpenIDConnectGithubClient::retrieveUserInfo()

Retrieves user info: additional user profile data.

Parameters

string $access_token: Access token.

Return value

array|bool User profile information array, or FALSE if retrieval failed.

Overrides OpenIDConnectClientBase::retrieveUserInfo

File

src/Plugin/OpenIDConnectClient/OpenIDConnectGithubClient.php, line 80

Class

OpenIDConnectGithubClient
GitHub OpenID Connect client.

Namespace

Drupal\openid_connect\Plugin\OpenIDConnectClient

Code

public function retrieveUserInfo($access_token) {
  $request_options = [
    'headers' => [
      'Authorization' => 'token ' . $access_token,
      'Accept' => 'application/json',
    ],
  ];
  $endpoints = $this
    ->getEndpoints();
  $client = $this->httpClient;
  try {
    $claims = [];
    $response = $client
      ->get($endpoints['userinfo'], $request_options);
    $response_data = json_decode((string) $response
      ->getBody(), TRUE);
    foreach ($this->userInfoMapping as $claim => $key) {
      if (array_key_exists($key, $response_data)) {
        $claims[$claim] = $response_data[$key];
      }
    }

    // GitHub names can be empty. Fall back to the login name.
    if (empty($claims['name']) && isset($response_data['login'])) {
      $claims['name'] = $response_data['login'];
    }

    // Convert the updated_at date to a timestamp.
    if (!empty($response_data['updated_at'])) {
      $claims['updated_at'] = strtotime($response_data['updated_at']);
    }

    // The email address is only provided in the User resource if the user has
    // chosen to display it publicly. So we need to make another request to
    // find out the user's email address(es).
    if (empty($claims['email'])) {
      $email_response = $client
        ->get($endpoints['userinfo'] . '/emails', $request_options);
      $email_response_data = json_decode((string) $email_response
        ->getBody(), TRUE);
      foreach ($email_response_data as $email) {

        // See https://developer.github.com/v3/users/emails/
        if (!empty($email['primary'])) {
          $claims['email'] = $email['email'];
          $claims['email_verified'] = $email['verified'];
          break;
        }
      }
    }
    return $claims;
  } catch (\Exception $e) {
    $variables = [
      '@message' => 'Could not retrieve user profile information',
      '@error_message' => $e
        ->getMessage(),
    ];
    $this->loggerFactory
      ->get('openid_connect_' . $this->pluginId)
      ->error('@message. Details: @error_message', $variables);
    return FALSE;
  }
}