View source
<?php
namespace Drupal\openid_connect;
use Drupal\Component\Serialization\Json;
use Drupal\Component\Utility\EmailValidatorInterface;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Entity\EntityFieldManagerInterface;
use Drupal\Core\Entity\EntityStorageException;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Extension\ModuleHandlerInterface;
use Drupal\Core\File\FileSystemInterface;
use Drupal\Core\Logger\LoggerChannelFactoryInterface;
use Drupal\Core\Messenger\MessengerInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Session\AccountProxyInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\externalauth\AuthmapInterface;
use Drupal\externalauth\ExternalAuthInterface;
use Drupal\user\UserDataInterface;
use Drupal\user\UserInterface;
class OpenIDConnect {
use StringTranslationTrait;
protected $configFactory;
protected $authmap;
protected $externalAuth;
protected $entityFieldManager;
protected $currentUser;
protected $userData;
protected $userStorage;
protected $messenger;
protected $moduleHandler;
protected $emailValidator;
protected $logger;
private $fileSystem;
protected $session;
public function __construct(ConfigFactoryInterface $config_factory, AuthmapInterface $authmap, ExternalAuthInterface $external_auth, EntityTypeManagerInterface $entity_type_manager, EntityFieldManagerInterface $entity_field_manager, AccountProxyInterface $current_user, UserDataInterface $user_data, EmailValidatorInterface $email_validator, MessengerInterface $messenger, ModuleHandlerInterface $module_handler, LoggerChannelFactoryInterface $logger, FileSystemInterface $fileSystem, OpenIDConnectSessionInterface $session) {
$this->configFactory = $config_factory;
$this->authmap = $authmap;
$this->externalAuth = $external_auth;
$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;
$this->session = $session;
}
public function userPropertiesIgnore(array $context = []) : array {
$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);
$properties_ignore = array_unique($properties_ignore);
return array_combine($properties_ignore, $properties_ignore);
}
private function buildContext(OpenIDConnectClientEntityInterface $client, array $tokens) {
$plugin = $client
->getPlugin();
$user_data = isset($tokens['id_token']) ? is_string($tokens['id_token']) ? $this
->parseToken($tokens['id_token']) : $tokens['id_token'] : NULL;
$access_data = isset($tokens['access_token']) ? is_string($tokens['access_token']) ? $this
->parseToken($tokens['access_token']) : $tokens['access_token'] : NULL;
if ($plugin
->usesUserInfo()) {
$userinfo = $plugin
->retrieveUserInfo($tokens['access_token']);
}
elseif (is_array($user_data)) {
$userinfo = $user_data;
}
elseif (is_array($access_data)) {
$userinfo = $access_data;
}
else {
$userinfo = [];
}
$provider = $client
->id();
$context = [
'tokens' => $tokens,
'plugin_id' => $provider,
'user_data' => $user_data,
];
$this->moduleHandler
->alter('openid_connect_userinfo', $userinfo, $context);
if ((empty($user_data) || !is_array($user_data)) && empty($userinfo)) {
$this->logger
->error('No user information provided by @provider', [
'@provider' => $provider,
]);
return FALSE;
}
if ($userinfo && empty($userinfo['email'])) {
$this->logger
->error('No e-mail address provided by @provider', [
'@provider' => $provider,
]);
return FALSE;
}
if (isset($user_data) && isset($user_data['sub'])) {
$sub = !isset($userinfo['sub']) || $user_data['sub'] == $userinfo['sub'] ? $user_data['sub'] : FALSE;
}
else {
$sub = isset($userinfo['sub']) ? $userinfo['sub'] : FALSE;
}
if (empty($sub)) {
$this->logger
->error('No "sub" found from @provider', [
'@provider' => $provider,
]);
return FALSE;
}
$account = $this->externalAuth
->load($sub, 'openid_connect.' . $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 (is_array($results)) {
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(OpenIDConnectClientEntityInterface $client, array $tokens) : bool {
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 instanceof UserInterface) {
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->externalAuth
->linkExistingAccount($context['sub'], 'openid_connect.' . $client
->id(), $account);
}
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
->id());
break;
case UserInterface::REGISTER_VISITORS_ADMINISTRATIVE_APPROVAL:
$account = $this
->createUser($context['sub'], $context['userinfo'], $client
->id(), 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,
]);
}
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->externalAuth
->userLoginFinalize($account, $context['sub'], 'openid_connect.' . $client
->id());
if (isset($tokens['id_token'])) {
$this->session
->saveIdToken($tokens['id_token']);
}
if (isset($tokens['access_token'])) {
$this->session
->saveAccessToken($tokens['access_token']);
}
$this->moduleHandler
->invokeAll('openid_connect_post_authorize', [
$account,
$context,
]);
return TRUE;
}
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) {
$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;
}
public function hasSetPasswordAccess(AccountInterface $account = NULL) : bool {
if (empty($account)) {
$account = $this->currentUser;
}
if ($account
->hasPermission('openid connect set own password')) {
return TRUE;
}
$connected_accounts = $this->authmap
->getAll($account
->id());
return empty($connected_accounts);
}
public function createUser(string $sub, array $userinfo, string $client_name, int $status = 1) : ?UserInterface {
$account_data = [
'name' => $this
->generateUsername($sub, $userinfo, $client_name),
'mail' => $userinfo['email'],
'init' => $userinfo['email'],
'status' => $status,
];
return $this->externalAuth
->register($sub, 'openid_connect.' . $client_name, $account_data);
}
public function generateUsername(string $sub, array $userinfo, string $client_name) : string {
$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(string $name) : bool {
$users = $this->userStorage
->loadByProperties([
'name' => $name,
]);
return (bool) $users;
}
public function saveUserinfo(UserInterface $account, array $context) : bool {
$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 'entity_reference':
$account
->set($property_name, [
'target_id' => $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['groups'])) {
$role_mappings = $this->configFactory
->get('openid_connect.settings')
->get('role_mappings');
foreach ($role_mappings as $role => $mappings) {
if (!empty(array_intersect($mappings, $userinfo['groups']))) {
$account
->addRole($role);
}
}
}
if (isset($userinfo['name'])) {
$this->userData
->set('openid_connect', $account
->id(), 'oidc_name', $userinfo['name']);
}
$this->moduleHandler
->invokeAll('openid_connect_userinfo_save', [
$account,
$context,
]);
try {
$account
->save();
return TRUE;
} catch (EntityStorageException $e) {
return FALSE;
}
}
protected function parseToken(string $token) {
$parts = explode('.', $token, 3);
if (count($parts) === 3) {
$decoded = Json::decode(base64_decode($parts[1]));
if (is_array($decoded)) {
return $decoded;
}
}
return $token;
}
}