OpenIDConnectGithubClient.php in OpenID Connect / OAuth client 2.x
File
src/Plugin/OpenIDConnectClient/OpenIDConnectGithubClient.php
View source
<?php
namespace Drupal\openid_connect\Plugin\OpenIDConnectClient;
use Drupal\Component\Serialization\Json;
use Drupal\Core\Form\FormStateInterface;
use Drupal\openid_connect\Plugin\OpenIDConnectClientBase;
use Symfony\Component\HttpFoundation\Response;
class OpenIDConnectGithubClient extends OpenIDConnectClientBase {
protected $userInfoMapping = [
'name' => 'name',
'sub' => 'id',
'email' => 'email',
'preferred_username' => 'login',
'picture' => 'avatar_url',
'profile' => 'html_url',
'website' => 'blog',
];
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;
}
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',
];
}
public function authorize(string $scope = 'openid email') : Response {
return parent::authorize('user:email');
}
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];
}
}
if (empty($claims['name']) && isset($response_data['login'])) {
$claims['name'] = $response_data['login'];
}
if (!empty($response_data['updated_at'])) {
$claims['updated_at'] = strtotime($response_data['updated_at']);
}
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) {
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;
}
}