You are here

class OpenIDConnectGithubClient in OpenID Connect / OAuth client 2.x

Same name and namespace in other branches
  1. 8 src/Plugin/OpenIDConnectClient/OpenIDConnectGithubClient.php \Drupal\openid_connect\Plugin\OpenIDConnectClient\OpenIDConnectGithubClient

GitHub OpenID Connect client.

Implements OpenID Connect Client plugin for GitHub.

Plugin annotation


@OpenIDConnectClient(
  id = "github",
  label = @Translation("GitHub")
)

Hierarchy

Expanded class hierarchy of OpenIDConnectGithubClient

File

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

Namespace

Drupal\openid_connect\Plugin\OpenIDConnectClient
View source
class OpenIDConnectGithubClient extends OpenIDConnectClientBase {

  /**
   * A mapping of OpenID Connect user claims to GitHub user properties.
   *
   * See https://developer.github.com/v3/users .
   *
   * @var array
   */
  protected $userInfoMapping = [
    'name' => 'name',
    'sub' => 'id',
    'email' => 'email',
    'preferred_username' => 'login',
    'picture' => 'avatar_url',
    'profile' => 'html_url',
    'website' => 'blog',
  ];

  /**
   * {@inheritdoc}
   */
  public function buildConfigurationForm(array $form, FormStateInterface $form_state) : array {
    $form = parent::buildConfigurationForm($form, $form_state);
    $url = 'https://github.com/settings/developers';
    $form['description'] = [
      '#markup' => '<div class="description">' . $this
        ->t('Set up your app in <a href="@url" target="_blank">developer applications</a> on GitHub.', [
        '@url' => $url,
      ]) . '</div>',
    ];
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function getEndpoints() : array {
    return [
      'authorization' => 'https://github.com/login/oauth/authorize',
      'token' => 'https://github.com/login/oauth/access_token',
      'userinfo' => 'https://api.github.com/user',
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function authorize(string $scope = 'openid email') : Response {

    // Use GitHub specific authorisations.
    return parent::authorize('user:email');
  }

  /**
   * {@inheritdoc}
   */
  public function retrieveUserInfo(string $access_token) : ?array {
    $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());
      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());
        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 NULL;
  }

}

Members

Namesort descending Modifiers Type Description Overrides
DependencySerializationTrait::$_entityStorages protected property
DependencySerializationTrait::$_serviceIds protected property
DependencySerializationTrait::__sleep public function 2
DependencySerializationTrait::__wakeup public function 2
MessengerTrait::$messenger protected property The messenger. 27
MessengerTrait::messenger public function Gets the messenger. 27
MessengerTrait::setMessenger public function Sets the messenger.
OpenIDConnectClientBase::$autoDiscover protected property The OpenID well-known discovery service.
OpenIDConnectClientBase::$dateTime protected property The datetime.time service.
OpenIDConnectClientBase::$httpClient protected property The HTTP client to fetch the feed data with.
OpenIDConnectClientBase::$languageManager protected property The language manager.
OpenIDConnectClientBase::$loggerFactory protected property The logger factory used for logging.
OpenIDConnectClientBase::$pageCacheKillSwitch protected property Page cache kill switch.
OpenIDConnectClientBase::$parentEntityId protected property The parent entity identifier.
OpenIDConnectClientBase::$requestStack protected property The request stack used to access request globals.
OpenIDConnectClientBase::$stateToken protected property The OpenID state token service.
OpenIDConnectClientBase::calculateDependencies public function Calculates dependencies for the configured plugin. Overrides DependentPluginInterface::calculateDependencies
OpenIDConnectClientBase::create public static function Creates an instance of the plugin. Overrides ContainerFactoryPluginInterface::create
OpenIDConnectClientBase::defaultConfiguration public function Gets default configuration for this plugin. Overrides ConfigurableInterface::defaultConfiguration 3
OpenIDConnectClientBase::getClientScopes public function Gets an array of of scopes. Overrides OpenIDConnectClientInterface::getClientScopes 2
OpenIDConnectClientBase::getConfiguration public function Gets this plugin's configuration. Overrides ConfigurableInterface::getConfiguration
OpenIDConnectClientBase::getLabel public function Return the plugin label as defined in the annotation. Overrides OpenIDConnectClientInterface::getLabel
OpenIDConnectClientBase::getParentEntityId public function Returns the parent entity ID. Overrides OpenIDConnectClientInterface::getParentEntityId
OpenIDConnectClientBase::getRedirectUrl protected function Returns the redirect URL.
OpenIDConnectClientBase::getRequestOptions protected function Helper function for request options.
OpenIDConnectClientBase::getUrlOptions protected function Helper function for URL options.
OpenIDConnectClientBase::retrieveTokens public function Retrieve access token and ID token. Overrides OpenIDConnectClientInterface::retrieveTokens
OpenIDConnectClientBase::setConfiguration public function Sets the configuration for this plugin instance. Overrides ConfigurableInterface::setConfiguration
OpenIDConnectClientBase::setParentEntityId public function Sets the parent entity ID. Overrides OpenIDConnectClientInterface::setParentEntityId
OpenIDConnectClientBase::submitConfigurationForm public function Form submission handler. Overrides PluginFormInterface::submitConfigurationForm 2
OpenIDConnectClientBase::unsetConfigurationKeys protected function Unsets some elements of the configuration.
OpenIDConnectClientBase::usesUserInfo public function Check if the client uses the userinfo endpoint. Overrides OpenIDConnectClientInterface::usesUserInfo
OpenIDConnectClientBase::validateConfigurationForm public function Form validation handler. Overrides PluginFormInterface::validateConfigurationForm 1
OpenIDConnectClientBase::__construct public function The constructor. Overrides PluginBase::__construct
OpenIDConnectGithubClient::$userInfoMapping protected property A mapping of OpenID Connect user claims to GitHub user properties.
OpenIDConnectGithubClient::authorize public function Redirects the user to the authorization endpoint. Overrides OpenIDConnectClientBase::authorize
OpenIDConnectGithubClient::buildConfigurationForm public function Form constructor. Overrides OpenIDConnectClientBase::buildConfigurationForm
OpenIDConnectGithubClient::getEndpoints public function Returns an array of endpoints. Overrides OpenIDConnectClientInterface::getEndpoints
OpenIDConnectGithubClient::retrieveUserInfo public function Retrieves user info: additional user profile data. Overrides OpenIDConnectClientBase::retrieveUserInfo
PluginBase::$configuration protected property Configuration information passed into the plugin. 1
PluginBase::$pluginDefinition protected property The plugin implementation definition. 1
PluginBase::$pluginId protected property The plugin_id.
PluginBase::DERIVATIVE_SEPARATOR constant A string which is used to separate base plugin IDs from the derivative ID.
PluginBase::getBaseId public function Gets the base_plugin_id of the plugin instance. Overrides DerivativeInspectionInterface::getBaseId
PluginBase::getDerivativeId public function Gets the derivative_id of the plugin instance. Overrides DerivativeInspectionInterface::getDerivativeId
PluginBase::getPluginDefinition public function Gets the definition of the plugin implementation. Overrides PluginInspectionInterface::getPluginDefinition 2
PluginBase::getPluginId public function Gets the plugin_id of the plugin instance. Overrides PluginInspectionInterface::getPluginId
PluginBase::isConfigurable public function Determines if the plugin is configurable.
PluginWithFormsTrait::getFormClass public function Implements \Drupal\Core\Plugin\PluginWithFormsInterface::getFormClass().
PluginWithFormsTrait::hasFormClass public function Implements \Drupal\Core\Plugin\PluginWithFormsInterface::hasFormClass().
StringTranslationTrait::$stringTranslation protected property The string translation service. 4
StringTranslationTrait::formatPlural protected function Formats a string containing a count of items.
StringTranslationTrait::getNumberOfPlurals protected function Returns the number of plurals supported by a given language.
StringTranslationTrait::getStringTranslation protected function Gets the string translation service.
StringTranslationTrait::setStringTranslation public function Sets the string translation service to use. 2
StringTranslationTrait::t protected function Translates a string to the current language or to a given language.