authx - Support Drupal 8 users+sessions
authorTim Otten <totten@civicrm.org>
Tue, 16 Feb 2021 09:12:45 +0000 (01:12 -0800)
committerTim Otten <totten@civicrm.org>
Tue, 2 Mar 2021 19:37:53 +0000 (11:37 -0800)
ext/authx/Civi/Authx/Drupal8.php [new file with mode: 0644]

diff --git a/ext/authx/Civi/Authx/Drupal8.php b/ext/authx/Civi/Authx/Drupal8.php
new file mode 100644 (file)
index 0000000..34debea
--- /dev/null
@@ -0,0 +1,60 @@
+<?php
+/*
+ +--------------------------------------------------------------------+
+ | Copyright CiviCRM LLC. All rights reserved.                        |
+ |                                                                    |
+ | This work is published under the GNU AGPLv3 license with some      |
+ | permitted exceptions and without any warranty. For full license    |
+ | and copyright information, see https://civicrm.org/licensing       |
+ +--------------------------------------------------------------------+
+ */
+
+namespace Civi\Authx;
+
+class Drupal8 implements AuthxInterface {
+
+  /**
+   * @inheritDoc
+   */
+  public function checkPassword(string $username, string $password) {
+    $uid = \Drupal::service('user.auth')->authenticate($username, $password);
+    // Ensure strict nullness.
+    return $uid ? $uid : NULL;
+  }
+
+  /**
+   * @inheritDoc
+   */
+  public function loginSession($userId) {
+    $user = user_load($userId);
+    user_login_finalize($user);
+  }
+
+  /**
+   * @inheritDoc
+   */
+  public function logoutSession() {
+    user_logout();
+  }
+
+  /**
+   * @inheritDoc
+   */
+  public function loginStateless($userId) {
+    $user = user_load($userId);
+    // In theory, we could use either account_switcher->switchTo() or current_user->setAccount().
+    // switchTo() sounds more conscientious, but setAccount() might be a more accurate rendition
+    // of "stateless login". At time of writing, there doesn't seem to be a compelling difference.
+    // But if you're looking at this line while investigating some bug... then maybe there is?
+    \Drupal::service('account_switcher')->switchTo($user);
+  }
+
+  /**
+   * @inheritDoc
+   */
+  public function getCurrentUserId() {
+    $user = \Drupal::currentUser();
+    return $user ? $user->getAccount()->id() : NULL;
+  }
+
+}