dev/core#2141 - If a mail-store has an OAuth2 token, then use it
authorTim Otten <totten@civicrm.org>
Sat, 31 Oct 2020 01:39:21 +0000 (18:39 -0700)
committerTim Otten <totten@civicrm.org>
Tue, 3 Nov 2020 12:32:48 +0000 (04:32 -0800)
ext/oauth-client/CRM/OAuth/MailSetup.php
ext/oauth-client/oauth_client.php

index 7f144f14643a83d5b0dd1f439700ab5a61b27d3e..d12a03a5d07a76b81113c5d936195b8a43f241ef 100644 (file)
@@ -141,4 +141,28 @@ class CRM_OAuth_MailSetup {
     return $values;
   }
 
+  /**
+   * If we have a stored token for this for this, then use it.
+   *
+   * @see CRM_Utils_Hook::alterMailStore()
+   */
+  public static function alterMailStore(&$mailSettings) {
+    $token = civicrm_api4('OAuthSysToken', 'refresh', [
+      'checkPermissions' => FALSE,
+      'where' => [['tag', '=', 'MailSettings:' . $mailSettings['id']]],
+      'orderBy' => ['id' => 'DESC'],
+    ])->first();
+
+    if ($token === NULL) {
+      return;
+    }
+    // Not certain if 'refresh' will complain about staleness. Doesn't hurt to double-check.
+    if (empty($token['access_token']) || $token['expires'] < CRM_Utils_Time::getTimeRaw()) {
+      throw new \OAuthException("Found invalid token for mail store #" . $mailSettings['id']);
+    }
+
+    $mailSettings['auth'] = 'XOAuth2';
+    $mailSettings['password'] = $token['access_token'];
+  }
+
 }
index 684187ab573a558c1e1675ba1109921f421a52be..7623094e5c5513d5de6ac86556429b12c4a81ca9 100644 (file)
@@ -239,3 +239,12 @@ function oauth_client_civicrm_mailSetupActions(&$setupActions) {
 function oauth_client_civicrm_oauthReturn($token, &$nextUrl) {
   CRM_OAuth_MailSetup::onReturn($token, $nextUrl);
 }
+
+/**
+ * Implements hook_civicrm_alterMailStore().
+ *
+ * @see CRM_Utils_Hook::alterMailStore()
+ */
+function oauth_client_civicrm_alterMailStore(&$mailSettings) {
+  CRM_OAuth_MailSetup::alterMailStore($mailSettings);
+}