Merge pull request #22378 from eileenmcnaughton/notice
[civicrm-core.git] / ext / authx / authx.php
index a30dcede14f054457e3081fee07acba6cf925dd7..25fe959f4c37ddce5b238e5780010f2974a8a16a 100644 (file)
@@ -38,6 +38,44 @@ Civi::dispatcher()->addListener('civi.invoke.auth', function($e) {
   }
 });
 
+/**
+ * Perform a system login.
+ *
+ * This is useful for backend scripts that need to switch to a specific user.
+ *
+ * As needed, this will update the Civi session and CMS data.
+ *
+ * @param array{flow: ?string, useSession: ?bool, principal: ?array, cred: ?string,} $details
+ *   Describe the authentication process with these properties:
+ *
+ *   - string $flow (default 'script');
+ *     The type of authentication flow being used
+ *     Ex: 'param', 'header', 'auto'
+ *   - bool $useSession (default FALSE)
+ *     If TRUE, then the authentication should be persistent (in a session variable).
+ *     If FALSE, then the authentication should be ephemeral (single page-request).
+ *
+ *   And then ONE of these properties to describe the user/principal:
+ *
+ *   - string $cred
+ *     The credential, as formatted in the 'Authorization' header.
+ *     Ex: 'Bearer 12345', 'Basic ASDFFDSA=='
+ *   - array $principal
+ *     Description of a validated principal.
+ *     Must include 'contactId', 'userId', xor 'user'
+ * @return array{contactId: int, userId: ?int, flow: string, credType: string, useSession: bool}
+ *   An array describing the authenticated session.
+ * @throws \Civi\Authx\AuthxException
+ */
+function authx_login(array $details): array {
+  $defaults = ['flow' => 'script', 'useSession' => FALSE];
+  $details = array_merge($defaults, $details);
+  $auth = new \Civi\Authx\Authenticator();
+  $auth->setRejectMode('exception');
+  $auth->auth(NULL, array_merge($defaults, $details));
+  return \CRM_Core_Session::singleton()->get("authx");
+}
+
 /**
  * @return \Civi\Authx\AuthxInterface
  */