From fe6a353589b68e3f9cae35211dd95442ea48b94b Mon Sep 17 00:00:00 2001
From: Brian Canini <canini.16@osu.edu>
Date: Thu, 9 Jul 2020 13:36:51 -0400
Subject: [PATCH] Updating drupal/externalauth (1.1.0 => 1.3.0)

---
 composer.json                                 |  2 +-
 composer.lock                                 | 23 ++++----
 vendor/composer/installed.json                | 23 ++++----
 .../externalauth/externalauth.info.yml        | 10 ++--
 web/modules/externalauth/externalauth.install | 16 ++++++
 .../externalauth/externalauth.services.yml    |  2 +-
 web/modules/externalauth/src/Authmap.php      | 13 +++--
 .../externalauth/src/AuthmapInterface.php     |  6 ++-
 web/modules/externalauth/src/ExternalAuth.php | 42 ++++++++++-----
 .../src/ExternalAuthInterface.php             |  9 +++-
 .../Plugin/migrate/destination/Authmap.php    | 19 +++++--
 .../externalauth/src/Tests/AuthmapTest.php    | 33 ++++++------
 .../tests/src/Kernel/ExternalAuthTest.php     | 54 +++++++++++++++++++
 .../tests/src/Unit/AuthmapTest.php            | 33 +++++++++++-
 .../tests/src/Unit/ExternalAuthTest.php       | 37 ++++++-------
 15 files changed, 230 insertions(+), 92 deletions(-)
 create mode 100644 web/modules/externalauth/tests/src/Kernel/ExternalAuthTest.php

diff --git a/composer.json b/composer.json
index 6c0d5f7ea5..93a6ff46e9 100644
--- a/composer.json
+++ b/composer.json
@@ -118,7 +118,7 @@
         "drupal/entity_clone": "1.0.0-beta4",
         "drupal/entity_embed": "1.1",
         "drupal/entity_reference_revisions": "1.8",
-        "drupal/externalauth": "1.1",
+        "drupal/externalauth": "1.3",
         "drupal/features": "3.8",
         "drupal/field_group": "3.1",
         "drupal/field_permissions": "1.0",
diff --git a/composer.lock b/composer.lock
index 0e0e326872..4168034da2 100644
--- a/composer.lock
+++ b/composer.lock
@@ -4,7 +4,7 @@
         "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
         "This file is @generated automatically"
     ],
-    "content-hash": "09f1b84dc9ea1c200a4d901869c1b774",
+    "content-hash": "6eb516300fe877e637f6d4d55a1e7058",
     "packages": [
         {
             "name": "alchemy/zippy",
@@ -4670,29 +4670,26 @@
         },
         {
             "name": "drupal/externalauth",
-            "version": "1.1.0",
+            "version": "1.3.0",
             "source": {
                 "type": "git",
                 "url": "https://git.drupalcode.org/project/externalauth.git",
-                "reference": "8.x-1.1"
+                "reference": "8.x-1.3"
             },
             "dist": {
                 "type": "zip",
-                "url": "https://ftp.drupal.org/files/projects/externalauth-8.x-1.1.zip",
-                "reference": "8.x-1.1",
-                "shasum": "171d8482df27aa66cb1b389bad4c711edd58136d"
+                "url": "https://ftp.drupal.org/files/projects/externalauth-8.x-1.3.zip",
+                "reference": "8.x-1.3",
+                "shasum": "b1b38e6718fe66bd38fc894dab1f9d7a7d60f10b"
             },
             "require": {
-                "drupal/core": "~8.0"
+                "drupal/core": "^8 || ^9"
             },
             "type": "drupal-module",
             "extra": {
-                "branch-alias": {
-                    "dev-1.x": "1.x-dev"
-                },
                 "drupal": {
-                    "version": "8.x-1.1",
-                    "datestamp": "1521730685",
+                    "version": "8.x-1.3",
+                    "datestamp": "1587629529",
                     "security-coverage": {
                         "status": "covered",
                         "message": "Covered by Drupal's security advisory policy"
@@ -4720,7 +4717,7 @@
             "description": "Helper module to authenticate users using an external site / service and storing identification details",
             "homepage": "https://www.drupal.org/project/externalauth",
             "support": {
-                "source": "http://cgit.drupalcode.org/externalauth"
+                "source": "https://git.drupalcode.org/project/externalauth"
             }
         },
         {
diff --git a/vendor/composer/installed.json b/vendor/composer/installed.json
index e23abfd062..a2590df229 100644
--- a/vendor/composer/installed.json
+++ b/vendor/composer/installed.json
@@ -4808,30 +4808,27 @@
     },
     {
         "name": "drupal/externalauth",
-        "version": "1.1.0",
-        "version_normalized": "1.1.0.0",
+        "version": "1.3.0",
+        "version_normalized": "1.3.0.0",
         "source": {
             "type": "git",
             "url": "https://git.drupalcode.org/project/externalauth.git",
-            "reference": "8.x-1.1"
+            "reference": "8.x-1.3"
         },
         "dist": {
             "type": "zip",
-            "url": "https://ftp.drupal.org/files/projects/externalauth-8.x-1.1.zip",
-            "reference": "8.x-1.1",
-            "shasum": "171d8482df27aa66cb1b389bad4c711edd58136d"
+            "url": "https://ftp.drupal.org/files/projects/externalauth-8.x-1.3.zip",
+            "reference": "8.x-1.3",
+            "shasum": "b1b38e6718fe66bd38fc894dab1f9d7a7d60f10b"
         },
         "require": {
-            "drupal/core": "~8.0"
+            "drupal/core": "^8 || ^9"
         },
         "type": "drupal-module",
         "extra": {
-            "branch-alias": {
-                "dev-1.x": "1.x-dev"
-            },
             "drupal": {
-                "version": "8.x-1.1",
-                "datestamp": "1521730685",
+                "version": "8.x-1.3",
+                "datestamp": "1587629529",
                 "security-coverage": {
                     "status": "covered",
                     "message": "Covered by Drupal's security advisory policy"
@@ -4860,7 +4857,7 @@
         "description": "Helper module to authenticate users using an external site / service and storing identification details",
         "homepage": "https://www.drupal.org/project/externalauth",
         "support": {
-            "source": "http://cgit.drupalcode.org/externalauth"
+            "source": "https://git.drupalcode.org/project/externalauth"
         }
     },
     {
diff --git a/web/modules/externalauth/externalauth.info.yml b/web/modules/externalauth/externalauth.info.yml
index 65a11cf08b..87c03eb99f 100644
--- a/web/modules/externalauth/externalauth.info.yml
+++ b/web/modules/externalauth/externalauth.info.yml
@@ -1,11 +1,11 @@
 name: External Authentication
 type: module
 description: Helper module to authenticate users using an external site / service and storing identification details
-# core: 8.x
+core: 8.x
+core_version_requirement: ^8 || ^9
 package: Authentication
 
-# Information added by Drupal.org packaging script on 2018-03-22
-version: '8.x-1.1'
-core: '8.x'
+# Information added by Drupal.org packaging script on 2020-04-23
+version: '8.x-1.3'
 project: 'externalauth'
-datestamp: 1521730701
+datestamp: 1587629530
diff --git a/web/modules/externalauth/externalauth.install b/web/modules/externalauth/externalauth.install
index 30e3fc33b7..f67c30241a 100644
--- a/web/modules/externalauth/externalauth.install
+++ b/web/modules/externalauth/externalauth.install
@@ -7,6 +7,14 @@
 
 use Drupal\Core\Database\Database;
 
+/**
+ * Implements hook_install().
+ */
+function externalauth_install() {
+  // Increase module weight to perform the authmap cleanup later.
+  module_set_weight('externalauth', 10);
+}
+
 /**
  * Implements hook_schema().
  */
@@ -83,3 +91,11 @@ function externalauth_update_8102() {
   $schema->addUniqueKey('authmap', 'authname_provider', ['authname', 'provider']);
   $schema->dropIndex('authmap', 'auth_provider');
 }
+
+/**
+ * Increase externalauth module weight.
+ */
+function externalauth_update_8103() {
+  // Increase module weight to perform the authmap cleanup later.
+  module_set_weight('externalauth', 10);
+}
diff --git a/web/modules/externalauth/externalauth.services.yml b/web/modules/externalauth/externalauth.services.yml
index e2578ea125..99bfb6da8b 100644
--- a/web/modules/externalauth/externalauth.services.yml
+++ b/web/modules/externalauth/externalauth.services.yml
@@ -4,7 +4,7 @@ services:
     arguments: ['@database']
   externalauth.externalauth:
     class: Drupal\externalauth\ExternalAuth
-    arguments: ['@entity.manager', '@externalauth.authmap', '@logger.channel.externalauth', '@event_dispatcher']
+    arguments: ['@entity_type.manager', '@externalauth.authmap', '@logger.channel.externalauth', '@event_dispatcher']
   logger.channel.externalauth:
     parent: logger.channel_base
     arguments: ['externalauth']
diff --git a/web/modules/externalauth/src/Authmap.php b/web/modules/externalauth/src/Authmap.php
index 27934d6928..1962d99fa0 100644
--- a/web/modules/externalauth/src/Authmap.php
+++ b/web/modules/externalauth/src/Authmap.php
@@ -122,10 +122,15 @@ public function getUid($authname, $provider) {
   /**
    * {@inheritdoc}
    */
-  public function delete($uid) {
-    $this->connection->delete('authmap')
-      ->condition('uid', $uid)
-      ->execute();
+  public function delete($uid, $provider = NULL) {
+    $query = $this->connection->delete('authmap')
+      ->condition('uid', $uid);
+
+    if ($provider) {
+      $query->condition('provider', $provider);
+    }
+
+    $query->execute();
   }
 
   /**
diff --git a/web/modules/externalauth/src/AuthmapInterface.php b/web/modules/externalauth/src/AuthmapInterface.php
index ffdcd11f27..a004ed7206 100644
--- a/web/modules/externalauth/src/AuthmapInterface.php
+++ b/web/modules/externalauth/src/AuthmapInterface.php
@@ -82,10 +82,14 @@ public function getUid($authname, $provider);
   /**
    * Delete authmap entries for a given Drupal user ID.
    *
+   * Deletion will be restricted to the specified provider, if passed.
+   *
    * @param int $uid
    *   The Drupal user ID.
+   * @param string $provider
+   *   (optional) The name of the service providing external authentication.
    */
-  public function delete($uid);
+  public function delete($uid, $provider = NULL);
 
   /**
    * Delete all authmap entries for a given provider.
diff --git a/web/modules/externalauth/src/ExternalAuth.php b/web/modules/externalauth/src/ExternalAuth.php
index 2e4cd3b7c7..fa6d58dbf0 100644
--- a/web/modules/externalauth/src/ExternalAuth.php
+++ b/web/modules/externalauth/src/ExternalAuth.php
@@ -2,7 +2,8 @@
 
 namespace Drupal\externalauth;
 
-use Drupal\Core\Entity\EntityManagerInterface;
+use Drupal\Core\DependencyInjection\DeprecatedServicePropertyTrait;
+use Drupal\Core\Entity\EntityTypeManagerInterface;
 use Psr\Log\LoggerInterface;
 use Symfony\Component\EventDispatcher\EventDispatcherInterface;
 use Drupal\externalauth\Event\ExternalAuthEvents;
@@ -19,12 +20,19 @@
  */
 class ExternalAuth implements ExternalAuthInterface {
 
+  use DeprecatedServicePropertyTrait;
+
+  /**
+   * {@inheritdoc}
+   */
+  protected $deprecatedProperties = ['entityManager' => 'entity.manager'];
+
   /**
-   * The entity manager.
+   * The entity type manager service.
    *
-   * @var \Drupal\Core\Entity\EntityManagerInterface
+   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
    */
-  protected $entityManager;
+  protected $entityTypeManager;
 
   /**
    * The authmap service.
@@ -50,8 +58,8 @@ class ExternalAuth implements ExternalAuthInterface {
   /**
    * {@inheritdoc}
    *
-   * @param \Drupal\Core\Entity\EntityManagerInterface $entity_manager
-   *   The entity manager.
+   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
+   *   The entity type manager service.
    * @param AuthmapInterface $authmap
    *   The authmap service.
    * @param \Psr\Log\LoggerInterface $logger
@@ -59,8 +67,8 @@ class ExternalAuth implements ExternalAuthInterface {
    * @param \Symfony\Component\EventDispatcher\EventDispatcherInterface $event_dispatcher
    *   The event dispatcher.
    */
-  public function __construct(EntityManagerInterface $entity_manager, AuthmapInterface $authmap, LoggerInterface $logger, EventDispatcherInterface $event_dispatcher) {
-    $this->entityManager = $entity_manager;
+  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;
@@ -71,7 +79,7 @@ public function __construct(EntityManagerInterface $entity_manager, AuthmapInter
    */
   public function load($authname, $provider) {
     if ($uid = $this->authmap->getUid($authname, $provider)) {
-      return $this->entityManager->getStorage('user')->load($uid);
+      return $this->entityTypeManager->getStorage('user')->load($uid);
     }
     return FALSE;
   }
@@ -91,9 +99,16 @@ public function login($authname, $provider) {
    * {@inheritdoc}
    */
   public function register($authname, $provider, array $account_data = [], $authmap_data = NULL) {
-    $username = $provider . '_' . $authname;
+    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->entityManager->getStorage('user');
+    $entity_storage = $this->entityTypeManager->getStorage('user');
 
     $account_search = $entity_storage->loadByProperties(['name' => $authmap_event->getUsername()]);
     if ($account = reset($account_search)) {
@@ -106,7 +121,7 @@ public function register($authname, $provider, array $account_data = [], $authma
         'name' => $authmap_event->getUsername(),
         'init' => $provider . '_' . $authmap_event->getAuthname(),
         'status' => 1,
-        'access' => (int) $_SERVER['REQUEST_TIME'],
+        'access' => 0,
       ],
       $account_data
     );
@@ -158,8 +173,7 @@ 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)) {
-      $username = $provider . '_' . $authname;
-      $authmap_event = $this->eventDispatcher->dispatch(ExternalAuthEvents::AUTHMAP_ALTER, new ExternalAuthAuthmapAlterEvent($provider, $authname, $username, NULL));
+      $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());
     }
   }
diff --git a/web/modules/externalauth/src/ExternalAuthInterface.php b/web/modules/externalauth/src/ExternalAuthInterface.php
index 251e4625f6..0cc5b88e05 100644
--- a/web/modules/externalauth/src/ExternalAuthInterface.php
+++ b/web/modules/externalauth/src/ExternalAuthInterface.php
@@ -44,13 +44,20 @@ public function login($authname, $provider);
   /**
    * Register a Drupal user based on an external authname.
    *
+   * The Drupal username of the account to be created defaults to the external
+   * authentication name prefixed with the provider ID. The caller may enforce
+   * a custom Drupal username by setting that value in $account_data['name'].
+   *
    * @param string $authname
    *   The unique, external authentication name provided by authentication
    *   provider.
    * @param string $provider
    *   The module providing external authentication.
    * @param array $account_data
-   *   An array of additional properties to be saved with the user entity.
+   *   An array of additional properties to be saved with the user entity. If
+   *   the array contains a 'name' string value, it will be used as local Drupal
+   *   username, otherwise a default local Drupal username will be computed as
+   *   "{$provider}_{$authname}".
    * @param mixed $authmap_data
    *   Additional data to be stored in the authmap entry.
    *
diff --git a/web/modules/externalauth/src/Plugin/migrate/destination/Authmap.php b/web/modules/externalauth/src/Plugin/migrate/destination/Authmap.php
index 0f0c95faf9..8844daa75d 100644
--- a/web/modules/externalauth/src/Plugin/migrate/destination/Authmap.php
+++ b/web/modules/externalauth/src/Plugin/migrate/destination/Authmap.php
@@ -3,10 +3,10 @@
 namespace Drupal\externalauth\Plugin\migrate\destination;
 
 use Drupal\externalauth\AuthmapInterface;
-use Drupal\user\Entity\User;
 use Drupal\migrate\Plugin\MigrationInterface;
 use Drupal\migrate\Row;
 use Drupal\migrate\Plugin\migrate\destination\DestinationBase;
+use Drupal\user\UserStorageInterface;
 use Symfony\Component\DependencyInjection\ContainerInterface;
 use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
 
@@ -26,6 +26,13 @@ class Authmap extends DestinationBase implements ContainerFactoryPluginInterface
    */
   protected $authmap;
 
+  /**
+   * User storage.
+   *
+   * @var \Drupal\user\UserStorageInterface
+   */
+  protected $userStorage;
+
   /**
    * Constructs an entity destination plugin.
    *
@@ -39,10 +46,13 @@ class Authmap extends DestinationBase implements ContainerFactoryPluginInterface
    *   The migration.
    * @param \Drupal\externalauth\AuthmapInterface $authmap
    *   The Authmap handling class.
+   * @param \Drupal\user\UserStorageInterface $user_storage
+   *   The user storage.
    */
-  public function __construct(array $configuration, $plugin_id, $plugin_definition, MigrationInterface $migration, AuthmapInterface $authmap) {
+  public function __construct(array $configuration, $plugin_id, $plugin_definition, MigrationInterface $migration, AuthmapInterface $authmap, UserStorageInterface $user_storage) {
     parent::__construct($configuration, $plugin_id, $plugin_definition, $migration);
     $this->authmap = $authmap;
+    $this->userStorage = $user_storage;
   }
 
   /**
@@ -54,7 +64,8 @@ public static function create(ContainerInterface $container, array $configuratio
       $plugin_id,
       $plugin_definition,
       $migration,
-      $container->get('externalauth.authmap')
+      $container->get('externalauth.authmap'),
+      $container->get('entity_type.manager')->getStorage('user')
     );
   }
 
@@ -85,7 +96,7 @@ public function fields(MigrationInterface $migration = NULL) {
    */
   public function import(Row $row, array $old_destination_id_values = []) {
     /** @var \Drupal\user\UserInterface $account */
-    $account = User::load($row->getDestinationProperty('uid'));
+    $account = $this->userStorage->load($row->getDestinationProperty('uid'));
     $provider = $row->getDestinationProperty('provider');
     $authname = $row->getDestinationProperty('authname');
     $this->authmap->save($account, $provider, $authname);
diff --git a/web/modules/externalauth/src/Tests/AuthmapTest.php b/web/modules/externalauth/src/Tests/AuthmapTest.php
index 79fceaacec..eea6ba6384 100644
--- a/web/modules/externalauth/src/Tests/AuthmapTest.php
+++ b/web/modules/externalauth/src/Tests/AuthmapTest.php
@@ -2,7 +2,7 @@
 
 namespace Drupal\externalauth\Tests;
 
-use Drupal\simpletest\KernelTestBase;
+use Drupal\KernelTests\KernelTestBase;
 use Drupal\user\Entity\User;
 
 /**
@@ -14,6 +14,9 @@
  */
 class AuthmapTest extends KernelTestBase {
 
+  /**
+   * {@inheritdoc}
+   */
   public static $modules = ['system', 'user', 'field', 'externalauth'];
 
   /**
@@ -57,18 +60,18 @@ public function testAuthmap() {
     }
 
     // Test get() method.
-    $count = db_query('SELECT COUNT(*) FROM {authmap}')->fetchField();
-    $this->assertEqual($count, 2, 'Number of authmap entries is correct.');
-    $this->assertEqual($this->authmap->get($account->id(), 'provider1'), $external_ids['provider1']['authname'], 'Authname can be retrieved for user via get().');
-    $this->assertEqual($this->authmap->get($account->id(), 'provider2'), $external_ids['provider2']['authname'], 'Authname can be retrieved for user via get().');
+    $count = \Drupal::database()->query('SELECT COUNT(*) FROM {authmap}')->fetchField();
+    $this->assertEquals($count, 2, 'Number of authmap entries is correct.');
+    $this->assertEquals($this->authmap->get($account->id(), 'provider1'), $external_ids['provider1']['authname'], 'Authname can be retrieved for user via get().');
+    $this->assertEquals($this->authmap->get($account->id(), 'provider2'), $external_ids['provider2']['authname'], 'Authname can be retrieved for user via get().');
 
     // Test getAuthData() method.
     $provider1_authdata = $this->authmap->getAuthData($account->id(), 'provider1');
-    $this->assertEqual($provider1_authdata['authname'], $external_ids['provider1']['authname'], 'Authname can be retrieved via getAuthData().');
-    $this->assertEqual($provider1_authdata['data'], $external_ids['provider1']['data'], 'Auth data can be retrieved via getAuthData().');
+    $this->assertEquals($provider1_authdata['authname'], $external_ids['provider1']['authname'], 'Authname can be retrieved via getAuthData().');
+    $this->assertEquals($provider1_authdata['data'], $external_ids['provider1']['data'], 'Auth data can be retrieved via getAuthData().');
     $provider2_authdata = $this->authmap->getAuthData($account->id(), 'provider2');
-    $this->assertEqual($provider2_authdata['authname'], $external_ids['provider2']['authname'], 'Authname can be retrieved via getAuthData().');
-    $this->assertEqual($provider2_authdata['data'], $external_ids['provider2']['data'], 'Auth data can be retrieved via getAuthData().');
+    $this->assertEquals($provider2_authdata['authname'], $external_ids['provider2']['authname'], 'Authname can be retrieved via getAuthData().');
+    $this->assertEquals($provider2_authdata['data'], $external_ids['provider2']['data'], 'Auth data can be retrieved via getAuthData().');
 
     // Test getAll() method.
     $all_authnames = $this->authmap->getAll($account->id());
@@ -76,21 +79,21 @@ public function testAuthmap() {
       'provider1' => $external_ids['provider1']['authname'],
       'provider2' => $external_ids['provider2']['authname'],
     ];
-    $this->assertEqual($all_authnames, $expected_authnames, 'All authnames for user can be retrieved.');
+    $this->assertEquals($all_authnames, $expected_authnames, 'All authnames for user can be retrieved.');
 
     // Test getUid() method.
     $uid = $this->authmap->getUid($external_ids['provider1']['authname'], 'provider1');
-    $this->assertEqual($uid, $account->id(), 'User ID can be retrieved based on authname & provider.');
+    $this->assertEquals($uid, $account->id(), 'User ID can be retrieved based on authname & provider.');
 
     // Test deleteProvider() method.
     $this->authmap->deleteProvider('provider1');
-    $count = db_query('SELECT COUNT(*) FROM {authmap}')->fetchField();
-    $this->assertEqual($count, 1, 'Provider data deleted successfully.');
+    $count = \Drupal::database()->query('SELECT COUNT(*) FROM {authmap}')->fetchField();
+    $this->assertEquals($count, 1, 'Provider data deleted successfully.');
 
     // Test delete() method.
     $this->authmap->delete($account->id());
-    $count = db_query('SELECT COUNT(*) FROM {authmap}')->fetchField();
-    $this->assertEqual($count, 0, 'User authnames deleted successfully.');
+    $count = \Drupal::database()->query('SELECT COUNT(*) FROM {authmap}')->fetchField();
+    $this->assertEquals($count, 0, 'User authnames deleted successfully.');
   }
 
 }
diff --git a/web/modules/externalauth/tests/src/Kernel/ExternalAuthTest.php b/web/modules/externalauth/tests/src/Kernel/ExternalAuthTest.php
new file mode 100644
index 0000000000..2c0be3ad7f
--- /dev/null
+++ b/web/modules/externalauth/tests/src/Kernel/ExternalAuthTest.php
@@ -0,0 +1,54 @@
+<?php
+
+namespace Drupal\Tests\externalauth\Kernel;
+
+use Drupal\KernelTests\KernelTestBase;
+
+/**
+ * Tests the 'externalauth.externalauth' service.
+ *
+ * @group externalauth
+ */
+class ExternalAuthTest extends KernelTestBase {
+
+  public static $modules = [
+    'externalauth',
+    'system',
+    'user',
+  ];
+
+  /**
+   * Tests the local Drupal username on registration.
+   */
+  public function testRegisterDrupalUsername() {
+    $this->installSchema('system', ['sequences']);
+    $this->installEntitySchema('user');
+    $this->installSchema('user', ['users_data']);
+    $this->installSchema('externalauth', ['authmap']);
+
+    $externalauth = $this->container->get('externalauth.externalauth');
+    $authmap = $this->container->get('externalauth.authmap');
+    $provider = 'arbitrary_provider';
+
+    // Register a new account.
+    $externalauth->register('external_name', $provider);
+
+    // Check that the registered account username is prefixed with the provider.
+    $account = user_load_by_name("{$provider}_external_name");
+    $this->assertNotFalse($account);
+    $this->assertSame('external_name', $authmap->get($account->id(), $provider));
+
+    $account->delete();
+
+    // Re-register the account but enforce a Drupal username.
+    $externalauth->register('external_name', $provider, [
+      'name' => 'enforced_name',
+    ]);
+
+    // Check that the registered account username match the enforced name.
+    $account = user_load_by_name('enforced_name');
+    $this->assertNotFalse($account);
+    $this->assertSame('external_name', $authmap->get($account->id(), $provider));
+  }
+
+}
diff --git a/web/modules/externalauth/tests/src/Unit/AuthmapTest.php b/web/modules/externalauth/tests/src/Unit/AuthmapTest.php
index 9e32e24929..5fb6b67eef 100644
--- a/web/modules/externalauth/tests/src/Unit/AuthmapTest.php
+++ b/web/modules/externalauth/tests/src/Unit/AuthmapTest.php
@@ -107,7 +107,7 @@ protected function setUp() {
    * @covers ::__construct
    */
   public function testSave() {
-    $account = $this->getMock('Drupal\user\UserInterface');
+    $account = $this->createMock('Drupal\user\UserInterface');
 
     $merge = $this->getMockBuilder('Drupal\Core\Database\Query\Merge')
       ->disableOriginalConstructor()
@@ -241,6 +241,35 @@ public function testDelete() {
     $authmap->delete(2);
   }
 
+  /**
+   * Test delete() method, when passing in $provider.
+   *
+   * @covers ::delete
+   * @covers ::__construct
+   */
+  public function testDeleteWithProvider() {
+    // Create a Mock Delete object and set expectations.
+    $this->delete = $this->getMockBuilder('Drupal\Core\Database\Query\Delete')
+      ->disableOriginalConstructor()
+      ->getMock();
+
+    $this->delete->expects($this->exactly(2))
+      ->method('condition')
+      ->will($this->returnSelf());
+
+    $this->delete->expects($this->any())
+      ->method('execute')
+      ->will($this->returnValue($this->statement));
+
+    $this->connection->expects($this->once())
+      ->method('delete')
+      ->with($this->equalTo('authmap'))
+      ->will($this->returnValue($this->delete));
+
+    $authmap = new Authmap($this->connection);
+    $authmap->delete(2, 'some_provider');
+  }
+
   /**
    * Test deleteProviders() method.
    *
@@ -254,7 +283,7 @@ public function testDeleteProviders() {
       ->will($this->returnValue($this->delete));
 
     $authmap = new Authmap($this->connection);
-    $authmap->delete("test_provider");
+    $authmap->deleteProvider("test_provider");
   }
 
 }
diff --git a/web/modules/externalauth/tests/src/Unit/ExternalAuthTest.php b/web/modules/externalauth/tests/src/Unit/ExternalAuthTest.php
index 52801605e4..b07f386e78 100644
--- a/web/modules/externalauth/tests/src/Unit/ExternalAuthTest.php
+++ b/web/modules/externalauth/tests/src/Unit/ExternalAuthTest.php
@@ -2,6 +2,7 @@
 
 namespace Drupal\Tests\externalauth\Unit;
 
+use Drupal\Core\Entity\EntityTypeManagerInterface;
 use Drupal\Tests\UnitTestCase;
 use Drupal\user\UserInterface;
 use Drupal\externalauth\ExternalAuth;
@@ -18,11 +19,11 @@
 class ExternalAuthTest extends UnitTestCase {
 
   /**
-   * The mocked Entity Manager.
+   * The mocked entity type manager service.
    *
-   * @var \Drupal\Core\Entity\EntityManagerInterface|\PHPUnit_Framework_MockObject_MockObject
+   * @var \Drupal\Core\Entity\EntityTypeManagerInterface|\PHPUnit_Framework_MockObject_MockObject
    */
-  protected $entityManager;
+  protected $entityTypeManager;
 
   /**
    * The mocked authmap service.
@@ -51,8 +52,8 @@ class ExternalAuthTest extends UnitTestCase {
   protected function setUp() {
     parent::setUp();
 
-    // Create a Mock EntityManager object.
-    $this->entityManager = $this->getMock('\Drupal\Core\Entity\EntityManagerInterface');
+    // Create a mock EntityTypeManager object.
+    $this->entityTypeManager = $this->createMock(EntityTypeManagerInterface::class);
 
     // Create a Mock Logger object.
     $this->logger = $this->getMockBuilder('\Psr\Log\LoggerInterface')
@@ -89,18 +90,18 @@ public function testLoad() {
       ->will($this->returnValue(2));
 
     // Mock the User storage layer.
-    $account = $this->getMock('Drupal\user\UserInterface');
-    $entity_storage = $this->getMock('Drupal\Core\Entity\EntityStorageInterface');
+    $account = $this->createMock('Drupal\user\UserInterface');
+    $entity_storage = $this->createMock('Drupal\Core\Entity\EntityStorageInterface');
     // Expect the external loading method to return a user object.
     $entity_storage->expects($this->once())
       ->method('load')
       ->will($this->returnValue($account));
-    $this->entityManager->expects($this->once())
+    $this->entityTypeManager->expects($this->once())
       ->method('getStorage')
       ->will($this->returnValue($entity_storage));
 
     $externalauth = new ExternalAuth(
-      $this->entityManager,
+      $this->entityTypeManager,
       $authmap,
       $this->logger,
       $this->eventDispatcher
@@ -121,7 +122,7 @@ public function testLogin() {
     $externalauth = $this->getMockBuilder('Drupal\externalauth\ExternalAuth')
       ->setMethods(['load', 'userLoginFinalize'])
       ->setConstructorArgs([
-        $this->entityManager,
+        $this->entityTypeManager,
         $this->authmap,
         $this->logger,
         $this->eventDispatcher,
@@ -151,7 +152,7 @@ public function testLogin() {
    */
   public function testRegister($registration_data, $expected_data) {
     // Mock the returned User object.
-    $account = $this->getMock('Drupal\user\UserInterface');
+    $account = $this->createMock('Drupal\user\UserInterface');
     $account->expects($this->once())
       ->method('enforceIsNew');
     $account->expects($this->once())
@@ -161,7 +162,7 @@ public function testRegister($registration_data, $expected_data) {
       ->will($this->returnValue($expected_data['timezone']));
 
     // Mock the User storage layer to create a new user.
-    $entity_storage = $this->getMock('Drupal\Core\Entity\EntityStorageInterface');
+    $entity_storage = $this->createMock('Drupal\Core\Entity\EntityStorageInterface');
     // Expect the external registration to return us a user object.
     $entity_storage->expects($this->any())
       ->method('create')
@@ -169,7 +170,7 @@ public function testRegister($registration_data, $expected_data) {
     $entity_storage->expects($this->any())
       ->method('loadByProperties')
       ->will($this->returnValue([]));
-    $this->entityManager->expects($this->any())
+    $this->entityTypeManager->expects($this->any())
       ->method('getStorage')
       ->will($this->returnValue($entity_storage));
 
@@ -202,7 +203,7 @@ public function testRegister($registration_data, $expected_data) {
       ->will($this->returnValue($dispatched_event));
 
     $externalauth = new ExternalAuth(
-      $this->entityManager,
+      $this->entityTypeManager,
       $authmap,
       $this->logger,
       $this->eventDispatcher
@@ -276,14 +277,14 @@ public function registerDataProvider() {
    * @covers ::__construct
    */
   public function testLoginRegister() {
-    $account = $this->getMock('Drupal\user\UserInterface');
+    $account = $this->createMock('Drupal\user\UserInterface');
 
     // Set up a mock for ExternalAuth class,
     // mocking login(), register() & userLoginFinalize() methods.
     $externalauth = $this->getMockBuilder('Drupal\externalauth\ExternalAuth')
       ->setMethods(['login', 'register', 'userLoginFinalize'])
       ->setConstructorArgs([
-        $this->entityManager,
+        $this->entityTypeManager,
         $this->authmap,
         $this->logger,
         $this->eventDispatcher,
@@ -309,7 +310,7 @@ public function testLoginRegister() {
    * Test linking an existing account.
    */
   public function testLinkExistingAccount() {
-    $account = $this->getMock('Drupal\user\UserInterface');
+    $account = $this->createMock('Drupal\user\UserInterface');
     $account->expects($this->once())
       ->method('id')
       ->will($this->returnValue(5));
@@ -347,7 +348,7 @@ public function testLinkExistingAccount() {
       ->will($this->returnValue($dispatched_event));
 
     $externalauth = new ExternalAuth(
-      $this->entityManager,
+      $this->entityTypeManager,
       $authmap,
       $this->logger,
       $this->eventDispatcher
-- 
GitLab