From: Tim Otten Date: Sat, 31 Oct 2020 01:39:21 +0000 (-0700) Subject: dev/core#2141 - If a mail-store has an OAuth2 token, then use it X-Git-Url: https://vcs.fsf.org/?a=commitdiff_plain;h=7dfe9078c8452ebef771911d1f751f2e2d8ac612;p=civicrm-core.git dev/core#2141 - If a mail-store has an OAuth2 token, then use it --- diff --git a/ext/oauth-client/CRM/OAuth/MailSetup.php b/ext/oauth-client/CRM/OAuth/MailSetup.php index 7f144f1464..d12a03a5d0 100644 --- a/ext/oauth-client/CRM/OAuth/MailSetup.php +++ b/ext/oauth-client/CRM/OAuth/MailSetup.php @@ -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']; + } + } diff --git a/ext/oauth-client/oauth_client.php b/ext/oauth-client/oauth_client.php index 684187ab57..7623094e5c 100644 --- a/ext/oauth-client/oauth_client.php +++ b/ext/oauth-client/oauth_client.php @@ -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); +}