oidc-1.0.0-alpha2/src/EventSubscriber/LinkExistingAccountSubscriber.php
src/EventSubscriber/LinkExistingAccountSubscriber.php
<?php
namespace Drupal\oidc\EventSubscriber;
use Drupal\Core\Entity\EntityStorageInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\oidc\ExistingAccountValidatorInterface;
use Drupal\oidc\Event\LinkExistingAccountEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
/**
* Event subscriber to link an existing account by email.
*/
class LinkExistingAccountSubscriber implements EventSubscriberInterface {
/**
* The user storage.
*
* @var \Drupal\Core\Entity\EntityStorageInterface
*/
protected EntityStorageInterface $userStorage;
/**
* The existing account validator.
*
* @var \Drupal\oidc\ExistingAccountValidatorInterface
*/
protected ExistingAccountValidatorInterface $existingAccountValidator;
/**
* Class constructor.
*
* @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
* The entity type manager.
* @param \Drupal\oidc\ExistingAccountValidatorInterface $existing_account_validator
* The existing account validator service.
*
* @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException
* @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException
*/
public function __construct(EntityTypeManagerInterface $entity_type_manager, ExistingAccountValidatorInterface $existing_account_validator) {
$this->userStorage = $entity_type_manager->getStorage('user');
$this->existingAccountValidator = $existing_account_validator;
}
/**
* {@inheritdoc}
*/
public static function getSubscribedEvents() {
$events[LinkExistingAccountEvent::class][] = ['linkAccountByEmail', 1000];
return $events;
}
/**
* Try to link an existing account by email.
*
* @param \Drupal\oidc\Event\LinkExistingAccountEvent $event
* The link existing account event.
*/
public function linkAccountByEmail(LinkExistingAccountEvent $event) {
$email = $event->getJsonWebTokens()->getEmail();
if (!$email) {
return;
}
/** @var \Drupal\user\UserInterface[] $users */
$users = $this->userStorage->loadByProperties([
'mail' => $email,
]);
foreach ($users as $user) {
if (!$this->existingAccountValidator->isValid($user)) {
continue;
}
$event->setAccount($user);
$event->stopPropagation();
break;
}
}
}
