From c6c340b577fb23a9c5a16e03439fbd5136146e21 Mon Sep 17 00:00:00 2001 From: Huong Nguyen Date: Thu, 27 Feb 2025 15:21:47 +0700 Subject: [PATCH] MDL-84222 lib: PHPMailer - Renew the expired token This patch includes: - Get a new token if it is not available. - Renew the token if it is expired using the refresh token. --- lib/phpmailer/moodle_phpmailer_oauth.php | 25 ++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/lib/phpmailer/moodle_phpmailer_oauth.php b/lib/phpmailer/moodle_phpmailer_oauth.php index 9183b3882c6..e246f8fba22 100644 --- a/lib/phpmailer/moodle_phpmailer_oauth.php +++ b/lib/phpmailer/moodle_phpmailer_oauth.php @@ -23,8 +23,33 @@ */ class moodle_phpmailer_oauth extends \PHPMailer\PHPMailer\OAuth { + #[\Override] protected function getToken() { return $this->provider->get_accesstoken()->token; } + #[\Override] + public function getOauth64() { + // Get a new token if it's not available. + if ($this->oauthToken === null) { + $this->oauthToken = $this->getToken(); + } + + $accesstoken = $this->provider->get_accesstoken(); + // Renew the token if it's expired. + if (isset($accesstoken->expires) && time() >= $accesstoken->expires) { + if (isset($accesstoken->refreshtoken)) { + $this->provider->upgrade_token($accesstoken->refreshtoken, 'refresh_token'); + } + $this->oauthToken = $this->getToken(); + } + + return base64_encode( + 'user=' . + $this->oauthUserEmail . + "\001auth=Bearer " . + $this->oauthToken . + "\001\001" + ); + } }