You are here

ExternalAuth.php in External Authentication 2.0.x

Same filename and directory in other branches
  1. 8 src/ExternalAuth.php

File

src/ExternalAuth.php
View source
<?php

namespace Drupal\externalauth;

use Drupal\Core\DependencyInjection\DeprecatedServicePropertyTrait;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Psr\Log\LoggerInterface;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Drupal\externalauth\Event\ExternalAuthEvents;
use Drupal\externalauth\Event\ExternalAuthLoginEvent;
use Drupal\externalauth\Event\ExternalAuthRegisterEvent;
use Drupal\externalauth\Event\ExternalAuthAuthmapAlterEvent;
use Drupal\user\UserInterface;
use Drupal\externalauth\Exception\ExternalAuthRegisterException;

/**
 * Class ExternalAuth.
 *
 * @package Drupal\externalauth
 */
class ExternalAuth implements ExternalAuthInterface {
  use DeprecatedServicePropertyTrait;

  /**
   * {@inheritdoc}
   */
  protected $deprecatedProperties = [
    'entityManager' => 'entity.manager',
  ];

  /**
   * The entity type manager service.
   *
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
   */
  protected $entityTypeManager;

  /**
   * The authmap service.
   *
   * @var \Drupal\externalauth\AuthmapInterface
   */
  protected $authmap;

  /**
   * A logger instance.
   *
   * @var \Psr\Log\LoggerInterface
   */
  protected $logger;

  /**
   * The event dispatcher.
   *
   * @var \Symfony\Component\EventDispatcher\EventDispatcherInterface
   */
  protected $eventDispatcher;

  /**
   * {@inheritdoc}
   *
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
   *   The entity type manager service.
   * @param AuthmapInterface $authmap
   *   The authmap service.
   * @param \Psr\Log\LoggerInterface $logger
   *   A logger instance.
   * @param \Symfony\Component\EventDispatcher\EventDispatcherInterface $event_dispatcher
   *   The event dispatcher.
   */
  public function __construct(EntityTypeManagerInterface $entity_type_manager, AuthmapInterface $authmap, LoggerInterface $logger, EventDispatcherInterface $event_dispatcher) {
    $this->entityTypeManager = $entity_type_manager;
    $this->authmap = $authmap;
    $this->logger = $logger;
    $this->eventDispatcher = $event_dispatcher;
  }

  /**
   * {@inheritdoc}
   */
  public function load($authname, $provider) {
    if ($uid = $this->authmap
      ->getUid($authname, $provider)) {
      return $this->entityTypeManager
        ->getStorage('user')
        ->load($uid);
    }
    return FALSE;
  }

  /**
   * {@inheritdoc}
   */
  public function login($authname, $provider) {
    $account = $this
      ->load($authname, $provider);
    if ($account) {
      return $this
        ->userLoginFinalize($account, $authname, $provider);
    }
    return FALSE;
  }

  /**
   * {@inheritdoc}
   */
  public function register($authname, $provider, array $account_data = [], $authmap_data = NULL) {
    if (!empty($account_data['name'])) {
      $username = $account_data['name'];
      unset($account_data['name']);
    }
    else {
      $username = $provider . '_' . $authname;
    }
    $authmap_event = $this->eventDispatcher
      ->dispatch(ExternalAuthEvents::AUTHMAP_ALTER, new ExternalAuthAuthmapAlterEvent($provider, $authname, $username, $authmap_data));
    $entity_storage = $this->entityTypeManager
      ->getStorage('user');
    $account_search = $entity_storage
      ->loadByProperties([
      'name' => $authmap_event
        ->getUsername(),
    ]);
    if ($account = reset($account_search)) {
      throw new ExternalAuthRegisterException(sprintf('User could not be registered. There is already an account with username "%s"', $authmap_event
        ->getUsername()));
    }

    // Set up the account data to be used for the user entity.
    $account_data = array_merge([
      'name' => $authmap_event
        ->getUsername(),
      'init' => $provider . '_' . $authmap_event
        ->getAuthname(),
      'status' => 1,
      'access' => 0,
    ], $account_data);
    $account = $entity_storage
      ->create($account_data);
    $account
      ->enforceIsNew();
    $account
      ->save();
    $this->authmap
      ->save($account, $provider, $authmap_event
      ->getAuthname(), $authmap_event
      ->getData());
    $this->eventDispatcher
      ->dispatch(ExternalAuthEvents::REGISTER, new ExternalAuthRegisterEvent($account, $provider, $authmap_event
      ->getAuthname(), $authmap_event
      ->getData()));
    $this->logger
      ->notice('External registration of user %name from provider %provider and authname %authname', [
      '%name' => $account
        ->getAccountName(),
      '%provider' => $provider,
      '%authname' => $authname,
    ]);
    return $account;
  }

  /**
   * {@inheritdoc}
   */
  public function loginRegister($authname, $provider, array $account_data = [], $authmap_data = NULL) {
    $account = $this
      ->login($authname, $provider);
    if (!$account) {
      $account = $this
        ->register($authname, $provider, $account_data, $authmap_data);
      return $this
        ->userLoginFinalize($account, $authname, $provider);
    }
    return $account;
  }

  /**
   * {@inheritdoc}
   *
   * @codeCoverageIgnore
   */
  public function userLoginFinalize(UserInterface $account, $authname, $provider) {
    user_login_finalize($account);
    $this->logger
      ->notice('External login of user %name', [
      '%name' => $account
        ->getAccountName(),
    ]);
    $this->eventDispatcher
      ->dispatch(ExternalAuthEvents::LOGIN, new ExternalAuthLoginEvent($account, $provider, $authname));
    return $account;
  }

  /**
   * {@inheritdoc}
   */
  public function linkExistingAccount($authname, $provider, UserInterface $account) {

    // If a mapping (for the same provider) to this account already exists, we
    // silently skip saving this auth mapping.
    if (!$this->authmap
      ->get($account
      ->id(), $provider)) {
      $authmap_event = $this->eventDispatcher
        ->dispatch(ExternalAuthEvents::AUTHMAP_ALTER, new ExternalAuthAuthmapAlterEvent($provider, $authname, $account
        ->getAccountName(), NULL));
      $this->authmap
        ->save($account, $provider, $authmap_event
        ->getAuthname(), $authmap_event
        ->getData());
    }
  }

}

Classes

Namesort descending Description
ExternalAuth Class ExternalAuth.