View source
<?php
namespace Drupal\openid_connect;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Entity\EntityFieldManagerInterface;
use Drupal\Core\Extension\ModuleHandler;
use Drupal\Core\File\FileSystemInterface;
use Drupal\Core\Logger\LoggerChannelFactoryInterface;
use Drupal\Core\Messenger\MessengerInterface;
use Drupal\Core\Session\AccountProxyInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\openid_connect\Plugin\OpenIDConnectClientInterface;
use Drupal\user\UserDataInterface;
use Drupal\user\UserInterface;
use Drupal\Component\Utility\EmailValidatorInterface;
class OpenIDConnect {
use StringTranslationTrait;
protected $configFactory;
protected $authmap;
protected $entityFieldManager;
protected $currentUser;
protected $userData;
protected $userStorage;
protected $messenger;
protected $moduleHandler;
protected $emailValidator;
protected $logger;
private $fileSystem;
public function __construct(ConfigFactoryInterface $config_factory, OpenIDConnectAuthmap $authmap, EntityTypeManagerInterface $entity_type_manager, EntityFieldManagerInterface $entity_field_manager, AccountProxyInterface $current_user, UserDataInterface $user_data, EmailValidatorInterface $email_validator, MessengerInterface $messenger, ModuleHandler $module_handler, LoggerChannelFactoryInterface $logger, FileSystemInterface $fileSystem) {
$this->configFactory = $config_factory;
$this->authmap = $authmap;
$this->userStorage = $entity_type_manager
->getStorage('user');
$this->entityFieldManager = $entity_field_manager;
$this->currentUser = $current_user;
$this->userData = $user_data;
$this->emailValidator = $email_validator;
$this->messenger = $messenger;
$this->moduleHandler = $module_handler;
$this->logger = $logger
->get('openid_connect');
$this->fileSystem = $fileSystem;
}
public function userPropertiesIgnore(array $context = []) {
$properties_ignore = [
'uid',
'uuid',
'langcode',
'preferred_langcode',
'preferred_admin_langcode',
'name',
'pass',
'mail',
'status',
'created',
'changed',
'access',
'login',
'init',
'roles',
'default_langcode',
];
$this->moduleHandler
->alter('openid_connect_user_properties_ignore', $properties_ignore, $context);
$this->moduleHandler
->alterDeprecated('hook_openid_connect_user_properties_to_skip_alter() is deprecated and will be removed in 8.x-2.0.', 'openid_connect_user_properties_to_skip', $properties_ignore, $context);
$properties_ignore = array_unique($properties_ignore);
return array_combine($properties_ignore, $properties_ignore);
}
public function extractSub($user_data, $userinfo) {
if (isset($user_data) && isset($user_data['sub'])) {
return !isset($userinfo['sub']) || $user_data['sub'] == $userinfo['sub'] ? $user_data['sub'] : FALSE;
}
else {
return isset($userinfo['sub']) ? $userinfo['sub'] : FALSE;
}
}
private function buildContext(OpenIDConnectClientInterface $client, array $tokens) {
$user_data = $client
->decodeIdToken($tokens['id_token']);
$userinfo = $client
->retrieveUserInfo($tokens['access_token']);
$provider = $client
->getPluginId();
$context = [
'tokens' => $tokens,
'plugin_id' => $provider,
'user_data' => $user_data,
];
$this->moduleHandler
->alter('openid_connect_userinfo', $userinfo, $context);
if (empty($user_data) && empty($userinfo)) {
$this->logger
->error('No user information provided by @provider (@code @error). Details: @details', [
'@provider' => $provider,
]);
return FALSE;
}
if ($userinfo && empty($userinfo['email'])) {
$this->logger
->error('No e-mail address provided by @provider (@code @error). Details: @details', [
'@provider' => $provider,
]);
return FALSE;
}
$sub = $this
->extractSub($user_data, $userinfo);
if (empty($sub)) {
$this->logger
->error('No "sub" found from @provider (@code @error). Details: @details', [
'@provider' => $provider,
]);
return FALSE;
}
$account = $this->authmap
->userLoadBySub($sub, $provider);
$context = [
'tokens' => $tokens,
'plugin_id' => $provider,
'user_data' => $user_data,
'userinfo' => $userinfo,
'sub' => $sub,
'account' => $account,
];
$results = $this->moduleHandler
->invokeAll('openid_connect_pre_authorize', [
$account,
$context,
]);
if (in_array(FALSE, $results, TRUE)) {
$this->logger
->error('Login denied for @email via pre-authorize hook.', [
'@email' => $userinfo['email'],
]);
return FALSE;
}
foreach ($results as $result) {
if ($result instanceof UserInterface) {
$context['account'] = $result;
break;
}
}
return $context;
}
public function completeAuthorization(OpenIDConnectClientInterface $client, array $tokens, &$destination) {
if ($this->currentUser
->isAuthenticated()) {
throw new \RuntimeException('User already logged in');
}
$context = $this
->buildContext($client, $tokens);
if ($context === FALSE) {
return FALSE;
}
$account = $context['account'];
if ($account !== FALSE) {
if ($this->configFactory
->get('openid_connect.settings')
->get('always_save_userinfo')) {
$this
->saveUserinfo($account, $context + [
'is_new' => FALSE,
]);
}
}
else {
$email = $context['userinfo']['email'];
if (!$this->emailValidator
->isValid($email)) {
$this->messenger
->addError($this
->t('The e-mail address is not valid: @email', [
'@email' => $email,
]));
return FALSE;
}
$accounts = $this->userStorage
->loadByProperties([
'mail' => $email,
]);
if ($accounts) {
$account = reset($accounts);
$connect_existing_users = $this->configFactory
->get('openid_connect.settings')
->get('connect_existing_users');
if ($connect_existing_users) {
$this->authmap
->createAssociation($account, $client
->getPluginId(), $context['sub']);
}
else {
$this->messenger
->addError($this
->t('The e-mail address is already taken: @email', [
'@email' => $email,
]));
return FALSE;
}
}
$register = $this->configFactory
->get('user.settings')
->get('register');
$register_override = $this->configFactory
->get('openid_connect.settings')
->get('override_registration_settings');
if ($register === UserInterface::REGISTER_ADMINISTRATORS_ONLY && $register_override) {
$register = UserInterface::REGISTER_VISITORS;
}
if (empty($account)) {
switch ($register) {
case UserInterface::REGISTER_ADMINISTRATORS_ONLY:
$this->messenger
->addError($this
->t('Only administrators can register new accounts.'));
return FALSE;
case UserInterface::REGISTER_VISITORS:
$account = $this
->createUser($context['sub'], $context['userinfo'], $client
->getPluginId(), 1);
break;
case UserInterface::REGISTER_VISITORS_ADMINISTRATIVE_APPROVAL:
$account = $this
->createUser($context['sub'], $context['userinfo'], $client
->getPluginId(), 0);
$this->messenger
->addMessage($this
->t('Thank you for applying for an account. Your account is currently pending approval by the site administrator.'));
break;
}
}
$this
->saveUserinfo($account, $context + [
'is_new' => TRUE,
]);
$this->authmap
->createAssociation($account, $client
->getPluginId(), $context['sub']);
}
if ($account
->isBlocked()) {
if (empty($context['is_new'])) {
$this->messenger
->addError($this
->t('The username %name has not been activated or is blocked.', [
'%name' => $account
->getAccountName(),
]));
}
return FALSE;
}
$this
->loginUser($account);
$this->moduleHandler
->invokeAll('openid_connect_post_authorize', [
$account,
$context,
]);
return TRUE;
}
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;
}
public function hasSetPasswordAccess(AccountInterface $account = NULL) {
if (empty($account)) {
$account = $this->currentUser;
}
if ($account
->hasPermission('openid connect set own password')) {
return TRUE;
}
$connected_accounts = $this->authmap
->getConnectedAccounts($account);
return empty($connected_accounts);
}
public function createUser($sub, array $userinfo, $client_name, $status = 1) {
$account = $this->userStorage
->create([
'name' => $this
->generateUsername($sub, $userinfo, $client_name),
'pass' => user_password(),
'mail' => $userinfo['email'],
'init' => $userinfo['email'],
'status' => $status,
'openid_connect_client' => $client_name,
'openid_connect_sub' => $sub,
]);
$account
->save();
return $account;
}
protected function loginUser(UserInterface $account) {
user_login_finalize($account);
}
public function generateUsername($sub, array $userinfo, $client_name) {
$name = 'oidc_' . $client_name . '_' . md5($sub);
$candidates = [
'preferred_username',
'name',
];
foreach ($candidates as $candidate) {
if (!empty($userinfo[$candidate])) {
$name = trim($userinfo[$candidate]);
break;
}
}
for ($original = $name, $i = 1; $this
->usernameExists($name); $i++) {
$name = $original . '_' . $i;
}
return $name;
}
public function usernameExists($name) {
$users = $this->userStorage
->loadByProperties([
'name' => $name,
]);
return (bool) $users;
}
public function saveUserinfo(UserInterface $account, array $context) {
$userinfo = $context['userinfo'];
$properties = $this->entityFieldManager
->getFieldDefinitions('user', 'user');
$properties_skip = $this
->userPropertiesIgnore($context);
foreach ($properties as $property_name => $property) {
if (isset($properties_skip[$property_name])) {
continue;
}
$userinfo_mappings = $this->configFactory
->get('openid_connect.settings')
->get('userinfo_mappings');
if (isset($userinfo_mappings[$property_name])) {
$claim = $userinfo_mappings[$property_name];
if ($claim && isset($userinfo[$claim])) {
$claim_value = $userinfo[$claim];
$property_type = $property
->getType();
$claim_context = $context + [
'claim' => $claim,
'property_name' => $property_name,
'property_type' => $property_type,
'userinfo_mappings' => $userinfo_mappings,
];
$this->moduleHandler
->alter('openid_connect_userinfo_claim', $claim_value, $claim_context);
try {
switch ($property_type) {
case 'string':
case 'string_long':
case 'list_string':
case 'datetime':
$account
->set($property_name, $claim_value);
break;
case 'boolean':
$account
->set($property_name, !empty($claim_value));
break;
case 'image':
$basename = explode('?', $this->fileSystem
->basename($claim_value))[0];
$data = file_get_contents($claim_value);
$file = file_save_data($data, 'public://user-picture-' . $account
->id() . '-' . $basename, FileSystemInterface::EXISTS_RENAME);
if ($file) {
$old_file = $account->{$property_name}->entity;
if ($old_file) {
$old_file
->delete();
}
}
$account
->set($property_name, [
'target_id' => $file
->id(),
]);
break;
default:
$this->logger
->error('Could not save user info, property type not implemented: %property_type', [
'%property_type' => $property_type,
]);
break;
}
} catch (\InvalidArgumentException $e) {
$this->logger
->error($e
->getMessage());
}
}
}
}
if (isset($userinfo['name'])) {
$this->userData
->set('openid_connect', $account
->id(), 'oidc_name', $userinfo['name']);
}
$this->moduleHandler
->invokeAllDeprecated('openid_connect_save_userinfo() is deprecated and will be removed in 8.x-2.0.', 'openid_connect_save_userinfo', [
$account,
$context,
]);
$this->moduleHandler
->invokeAll('openid_connect_userinfo_save', [
$account,
$context,
]);
$account
->save();
}
}