mirror of
https://github.com/the-djmaze/snappymail.git
synced 2026-08-25 10:09:20 +03:00
Corrected OAuth2 login flow and added better error handling
This commit is contained in:
parent
ba496919dd
commit
b483f2ee76
2 changed files with 348 additions and 270 deletions
|
|
@ -1,54 +1,51 @@
|
||||||
(rl => {
|
((rl) => {
|
||||||
const client_id = rl.pluginSettingsGet('login-o365', 'client_id'),
|
const client_id = rl.pluginSettingsGet("login-o365", "client_id"),
|
||||||
// https://learn.microsoft.com/en-us/entra/identity-platform/reply-url#query-parameter-support-in-redirect-uris
|
// https://learn.microsoft.com/en-us/entra/identity-platform/reply-url#query-parameter-support-in-redirect-uris
|
||||||
query = rl.pluginSettingsGet('login-o365', 'personal') ? '' : '?',
|
tenant = rl.pluginSettingsGet("login-o365", "tenant"),
|
||||||
tenant = rl.pluginSettingsGet('login-o365', 'tenant'),
|
login = () => {
|
||||||
login = () => {
|
document.location = "https://login.microsoftonline.com/" +
|
||||||
document.location = 'https://login.microsoftonline.com/'+tenant+'/oauth2/v2.0/authorize?' + (new URLSearchParams({
|
tenant +
|
||||||
response_type: 'code',
|
"/oauth2/v2.0/authorize?" +
|
||||||
client_id: client_id,
|
new URLSearchParams({
|
||||||
redirect_uri: document.location.href.replace(/\/$/, '') + '/' + query + 'LoginO365',
|
response_type: "code",
|
||||||
scope: [
|
client_id: client_id,
|
||||||
// Associate personal info
|
redirect_uri:
|
||||||
'openid',
|
document.location.href.replace(/\/$/, "") + "/LoginO365",
|
||||||
'offline_access',
|
scope: [
|
||||||
'email',
|
// Associate personal info
|
||||||
'profile',
|
"openid",
|
||||||
// Access IMAP and SMTP through OAUTH
|
"offline_access",
|
||||||
'https://graph.microsoft.com/IMAP.AccessAsUser.All',
|
"email",
|
||||||
// 'https://graph.microsoft.com/Mail.ReadWrite'
|
"profile",
|
||||||
'https://graph.microsoft.com/Mail.Send'
|
// Access IMAP and SMTP through OAUTH
|
||||||
/* // Legacy:
|
"https://outlook.office.com/IMAP.AccessAsUser.All",
|
||||||
'https://outlook.office.com/SMTP.Send',
|
"https://outlook.office.com/SMTP.Send",
|
||||||
'https://outlook.office.com/IMAP.AccessAsUser.All'
|
].join(" "),
|
||||||
*/
|
state: "o365",
|
||||||
].join(' '),
|
access_type: "offline_access"
|
||||||
state: 'o365', // + rl.settings.app('token') + localStorage.getItem('smctoken')
|
// prompt: "consent",
|
||||||
// Force authorize screen, so we always get a refresh_token
|
});
|
||||||
access_type: 'offline',
|
};
|
||||||
prompt: 'consent'
|
|
||||||
}));
|
|
||||||
};
|
|
||||||
|
|
||||||
if (client_id) {
|
if (client_id) {
|
||||||
addEventListener('sm-user-login', e => {
|
addEventListener("sm-user-login", (e) => {
|
||||||
if (event.detail.get('Email').includes('@hotmail.com')) {
|
const email = (e.detail.get("Email") || "").toLowerCase();
|
||||||
e.preventDefault();
|
if (/@(outlook\.com|hotmail\.com|live\.com)$/.test(email)) {
|
||||||
login();
|
e.preventDefault();
|
||||||
}
|
login();
|
||||||
});
|
}
|
||||||
|
});
|
||||||
addEventListener('rl-view-model', e => {
|
|
||||||
if ('Login' === e.detail.viewModelTemplateID) {
|
|
||||||
const
|
|
||||||
container = e.detail.viewModelDom.querySelector('#plugin-Login-BottomControlGroup'),
|
|
||||||
btn = Element.fromHTML('<button type="button">Outlook</button>'),
|
|
||||||
div = Element.fromHTML('<div class="controls"></div>');
|
|
||||||
btn.onclick = login;
|
|
||||||
div.append(btn);
|
|
||||||
container && container.append(div);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
|
addEventListener("rl-view-model", (e) => {
|
||||||
|
if ("Login" === e.detail.viewModelTemplateID) {
|
||||||
|
const
|
||||||
|
container = e.detail.viewModelDom.querySelector("#plugin-Login-BottomControlGroup"),
|
||||||
|
btn = Element.fromHTML('<button type="button">Outlook</button>'),
|
||||||
|
div = Element.fromHTML('<div class="controls"></div>');
|
||||||
|
btn.onclick = login;
|
||||||
|
div.append(btn);
|
||||||
|
container && container.append(div);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
})(window.rl);
|
})(window.rl);
|
||||||
|
|
@ -1,15 +1,20 @@
|
||||||
<?php
|
<?php
|
||||||
/**
|
/**
|
||||||
* Microsoft requires an Azure account that has an active subscription
|
* SnappyMail login-o365 plugin
|
||||||
* I'm not going to pay, so feel free to fix this code yourself.
|
* You need to register an app in Azure portal and add
|
||||||
* https://learn.microsoft.com/en-us/exchange/client-developer/legacy-protocols/how-to-authenticate-an-imap-pop-smtp-application-by-using-oauth
|
* a secret, redirect URIs and the following API permissions:
|
||||||
* https://answers.microsoft.com/en-us/msoffice/forum/all/configuration-for-imap-pop-and-smtp-with-oauth-in/3db47d43-25ac-4e0b-b957-22585e6caf15
|
* https://outlook.office.com/IMAP.AccessAsUser.All
|
||||||
*
|
* https://outlook.office.com/SMTP.Send
|
||||||
* https://portal.azure.com/#view/Microsoft_AAD_IAM/ActiveDirectoryMenuBlade/~/RegisteredApps
|
* openid offline_access email profile
|
||||||
*
|
|
||||||
* https://learn.microsoft.com/en-us/entra/identity-platform/reply-url#query-parameter-support-in-redirect-uris
|
* https://learn.microsoft.com/en-us/entra/identity-platform/reply-url#query-parameter-support-in-redirect-uris
|
||||||
* Azure: redirect_uri=https://{DOMAIN}/?LoginO365
|
* Azure: redirect_uri=https://{DOMAIN}/?LoginO365
|
||||||
* Personal: redirect_uri=https://{DOMAIN}/LoginO365
|
* Personal: redirect_uri=https://{DOMAIN}/LoginO365
|
||||||
|
*
|
||||||
|
* If running behind nginx reverse proxy you might
|
||||||
|
* need to add the following to your nginx config:
|
||||||
|
* location = /LoginO365 {
|
||||||
|
* return 302 /?LoginO365&$args;
|
||||||
|
* }
|
||||||
*/
|
*/
|
||||||
|
|
||||||
use RainLoop\Model\MainAccount;
|
use RainLoop\Model\MainAccount;
|
||||||
|
|
@ -17,232 +22,308 @@ use RainLoop\Providers\Storage\Enumerations\StorageType;
|
||||||
|
|
||||||
class LoginO365Plugin extends \RainLoop\Plugins\AbstractPlugin
|
class LoginO365Plugin extends \RainLoop\Plugins\AbstractPlugin
|
||||||
{
|
{
|
||||||
const
|
const
|
||||||
NAME = 'Office365/Outlook OAuth2',
|
NAME = 'Office365/Outlook OAuth2',
|
||||||
VERSION = '0.3',
|
VERSION = '0.3',
|
||||||
RELEASE = '2024-09-29',
|
RELEASE = '2025-12-18',
|
||||||
REQUIRED = '2.36.1',
|
REQUIRED = '2.36.1',
|
||||||
CATEGORY = 'Login',
|
CATEGORY = 'Login',
|
||||||
DESCRIPTION = 'Office365/Outlook IMAP, Sieve & SMTP login using RFC 7628 OAuth2';
|
DESCRIPTION = 'Office365/Outlook IMAP, Sieve & SMTP login using RFC 7628 OAuth2';
|
||||||
|
|
||||||
// https://login.microsoftonline.com/{{tenant}}/v2.0/.well-known/openid-configuration
|
// v2 endpoints
|
||||||
const
|
const
|
||||||
LOGIN_URI = 'https://login.microsoftonline.com/{{tenant}}/oauth2/v2.0/auth',
|
AUTH_URI = 'https://login.microsoftonline.com/{{tenant}}/oauth2/v2.0/authorize',
|
||||||
TOKEN_URI = 'https://login.microsoftonline.com/{{tenant}}/oauth2/v2.0/token';
|
TOKEN_URI = 'https://login.microsoftonline.com/{{tenant}}/oauth2/v2.0/token';
|
||||||
|
|
||||||
private static ?array $auth = null;
|
private static ?array $auth = null;
|
||||||
|
|
||||||
public function Init() : void
|
public function Init() : void
|
||||||
{
|
{
|
||||||
$this->UseLangs(true);
|
$this->UseLangs(true);
|
||||||
$this->addJs('LoginOAuth2.js');
|
$this->addJs('LoginOAuth2.js');
|
||||||
$this->addHook('imap.before-login', 'clientLogin');
|
$this->addHook('imap.before-login', 'clientLogin');
|
||||||
$this->addHook('smtp.before-login', 'clientLogin');
|
$this->addHook('smtp.before-login', 'clientLogin');
|
||||||
$this->addHook('sieve.before-login', 'clientLogin');
|
$this->addHook('sieve.before-login', 'clientLogin');
|
||||||
|
|
||||||
$this->addPartHook('LoginO365', 'ServiceLoginO365');
|
$this->addPartHook('LoginO365', 'ServiceLoginO365');
|
||||||
|
|
||||||
// Prevent Disallowed Sec-Fetch Dest: document Mode: navigate Site: cross-site User: true
|
// Prevent Disallowed Sec-Fetch Dest: document Mode: navigate Site: cross-site User: true
|
||||||
$this->addHook('filter.http-paths', 'httpPaths');
|
$this->addHook('filter.http-paths', 'httpPaths');
|
||||||
}
|
}
|
||||||
|
|
||||||
public function httpPaths(array &$aPaths) : void
|
public function httpPaths(array &$aPaths) : void
|
||||||
{
|
{
|
||||||
// Personal accounts workaround
|
if (!empty($_SERVER['PATH_INFO']) && \str_ends_with($_SERVER['PATH_INFO'], 'LoginO365')) {
|
||||||
if (!empty($_SERVER['PATH_INFO']) && \str_ends_with($_SERVER['PATH_INFO'], 'LoginO365')) {
|
$aPaths = ['LoginO365'];
|
||||||
$aPaths = ['LoginO365'];
|
}
|
||||||
}
|
|
||||||
|
|
||||||
if (!empty($aPaths[0]) && 'LoginO365' === $aPaths[0]) {
|
if (!empty($aPaths[0]) && 'LoginO365' === $aPaths[0]) {
|
||||||
$oConfig = \RainLoop\Api::Config();
|
$oConfig = \RainLoop\Api::Config();
|
||||||
$oConfig->Set('security', 'secfetch_allow',
|
$oConfig->Set('security', 'secfetch_allow',
|
||||||
\trim($oConfig->Get('security', 'secfetch_allow', '') . ';site=cross-site', ';')
|
\trim($oConfig->Get('security', 'secfetch_allow', '') . ';site=cross-site', ';')
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public function ServiceLoginO365() : string
|
public function ServiceLoginO365() : string
|
||||||
{
|
{
|
||||||
$oActions = \RainLoop\Api::Actions();
|
$oActions = \RainLoop\Api::Actions();
|
||||||
$oHttp = $oActions->Http();
|
$oHttp = $oActions->Http();
|
||||||
$oHttp->ServerNoCache();
|
$oHttp->ServerNoCache();
|
||||||
|
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
if (isset($_GET['error'])) {
|
if (isset($_GET['error'])) {
|
||||||
throw new \RuntimeException("{$_GET['error']}: {$_GET['error_description']}");
|
$desc = $_GET['error_description'] ?? '';
|
||||||
}
|
throw new \RuntimeException("{$_GET['error']}: {$desc}");
|
||||||
if (!isset($_GET['code']) || empty($_GET['state']) || 'o365' !== $_GET['state']) {
|
}
|
||||||
$oActions->Location(\RainLoop\Utils::WebPath());
|
|
||||||
exit;
|
|
||||||
}
|
|
||||||
$oO365 = $this->o365Connector();
|
|
||||||
if (!$oO365) {
|
|
||||||
$oActions->Location(\RainLoop\Utils::WebPath());
|
|
||||||
exit;
|
|
||||||
}
|
|
||||||
|
|
||||||
$iExpires = \time();
|
// Must have code + state
|
||||||
$aResponse = $oO365->getAccessToken(
|
if (!isset($_GET['code']) || empty($_GET['state']) || 'o365' !== $_GET['state']) {
|
||||||
\str_replace('{{tenant}}', $this->Config()->Get('plugin', 'tenant', 'common'), static::TOKEN_URI),
|
$oActions->Location(\RainLoop\Utils::WebPath());
|
||||||
'authorization_code',
|
exit;
|
||||||
array(
|
}
|
||||||
'code' => $_GET['code'],
|
|
||||||
'redirect_uri' => $oHttp->GetFullUrl().'?LoginO365'
|
|
||||||
)
|
|
||||||
);
|
|
||||||
if (200 != $aResponse['code']) {
|
|
||||||
if (isset($aResponse['result']['error'])) {
|
|
||||||
throw new \RuntimeException(
|
|
||||||
$aResponse['code']
|
|
||||||
. ': '
|
|
||||||
. $aResponse['result']['error']
|
|
||||||
. ' / '
|
|
||||||
. $aResponse['result']['error_description']
|
|
||||||
);
|
|
||||||
}
|
|
||||||
throw new \RuntimeException("HTTP: {$aResponse['code']}");
|
|
||||||
}
|
|
||||||
$aResponse = $aResponse['result'];
|
|
||||||
if (empty($aResponse['access_token'])) {
|
|
||||||
throw new \RuntimeException('access_token missing');
|
|
||||||
}
|
|
||||||
if (empty($aResponse['refresh_token'])) {
|
|
||||||
throw new \RuntimeException('refresh_token missing');
|
|
||||||
}
|
|
||||||
|
|
||||||
$sAccessToken = $aResponse['access_token'];
|
$oO365 = $this->o365Connector();
|
||||||
$iExpires += $aResponse['expires_in'];
|
if (!$oO365) {
|
||||||
|
$oActions->Location(\RainLoop\Utils::WebPath());
|
||||||
|
exit;
|
||||||
|
}
|
||||||
|
|
||||||
$oO365->setAccessToken($sAccessToken);
|
$iNow = \time();
|
||||||
$aUserInfo = $oO365->fetch('https://graph.microsoft.com/oidc/userinfo');
|
|
||||||
if (200 != $aUserInfo['code']) {
|
|
||||||
throw new \RuntimeException("HTTP: {$aResponse['code']}");
|
|
||||||
}
|
|
||||||
$aUserInfo = $aUserInfo['result'];
|
|
||||||
if (empty($aUserInfo['id'])) {
|
|
||||||
throw new \RuntimeException('unknown id');
|
|
||||||
}
|
|
||||||
if (empty($aUserInfo['email'])) {
|
|
||||||
throw new \RuntimeException('unknown email address');
|
|
||||||
}
|
|
||||||
|
|
||||||
static::$auth = [
|
// Build absolute base URL (works behind nginx reverse proxy)
|
||||||
'access_token' => $sAccessToken,
|
$scheme = (!empty($_SERVER['HTTP_X_FORWARDED_PROTO']))
|
||||||
'refresh_token' => $aResponse['refresh_token'],
|
? $_SERVER['HTTP_X_FORWARDED_PROTO']
|
||||||
'expires_in' => $aResponse['expires_in'],
|
: ((!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http');
|
||||||
'expires' => $iExpires
|
|
||||||
];
|
|
||||||
|
|
||||||
$oPassword = new \SnappyMail\SensitiveString($aUserInfo['id']);
|
$host = $_SERVER['HTTP_HOST'] ?? $_SERVER['SERVER_NAME'] ?? '';
|
||||||
$oAccount = $oActions->LoginProcess($aUserInfo['email'], $oPassword);
|
if (!$host) {
|
||||||
// $oAccount = MainAccount::NewInstanceFromCredentials($oActions, $aUserInfo['email'], $aUserInfo['email'], $oPassword, true);
|
throw new \RuntimeException('Cannot determine HTTP_HOST');
|
||||||
if ($oAccount) {
|
}
|
||||||
// $oActions->SetMainAuthAccount($oAccount);
|
$base = $scheme . '://' . $host;
|
||||||
// $oActions->SetAuthToken($oAccount);
|
|
||||||
$oActions->StorageProvider()->Put($oAccount, StorageType::SESSION, \RainLoop\Utils::GetSessionToken(),
|
|
||||||
\SnappyMail\Crypt::EncryptToJSON(static::$auth, $oAccount->CryptKey())
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
catch (\Exception $oException)
|
|
||||||
{
|
|
||||||
$oActions->Logger()->WriteException($oException, \LOG_ERR);
|
|
||||||
}
|
|
||||||
$oActions->Location(\RainLoop\Utils::WebPath());
|
|
||||||
exit;
|
|
||||||
}
|
|
||||||
|
|
||||||
public function configMapping() : array
|
// IMPORTANT: default personal=false to match the JS default behavior
|
||||||
{
|
$personal = (bool)$this->Config()->Get('plugin', 'personal', false);
|
||||||
return [
|
$redirectUri = $personal ? ($base . '/?LoginO365') : ($base . '/LoginO365');
|
||||||
\RainLoop\Plugins\Property::NewInstance('personal')
|
|
||||||
->SetLabel('Use with personal accounts')
|
|
||||||
->SetType(\RainLoop\Enumerations\PluginPropertyType::BOOL)
|
|
||||||
->SetDefaultValue(true)
|
|
||||||
->SetAllowedInJs()
|
|
||||||
->SetDescription('Sign in users with personal Microsoft accounts such as Outlook.com (Hotmail)'),
|
|
||||||
\RainLoop\Plugins\Property::NewInstance('client_id')
|
|
||||||
->SetLabel('Client ID')
|
|
||||||
->SetType(\RainLoop\Enumerations\PluginPropertyType::STRING)
|
|
||||||
->SetAllowedInJs()
|
|
||||||
->SetDescription('https://github.com/the-djmaze/snappymail/wiki/FAQ#o365'),
|
|
||||||
\RainLoop\Plugins\Property::NewInstance('client_secret')
|
|
||||||
->SetLabel('Client Secret')
|
|
||||||
->SetType(\RainLoop\Enumerations\PluginPropertyType::STRING)
|
|
||||||
->SetEncrypted(),
|
|
||||||
\RainLoop\Plugins\Property::NewInstance('tenant_id')
|
|
||||||
->SetLabel('Tenant ID')
|
|
||||||
->SetType(\RainLoop\Enumerations\PluginPropertyType::STRING),
|
|
||||||
\RainLoop\Plugins\Property::NewInstance('tenant')->SetLabel('Tenant')
|
|
||||||
->SetType(\RainLoop\Enumerations\PluginPropertyType::SELECTION)
|
|
||||||
->SetDefaultValue(['common','consumers','organizations'])
|
|
||||||
->SetAllowedInJs()
|
|
||||||
];
|
|
||||||
}
|
|
||||||
|
|
||||||
public function clientLogin(\RainLoop\Model\Account $oAccount, \MailSo\Net\NetClient $oClient, \MailSo\Net\ConnectSettings $oSettings) : void
|
$tenant = $this->Config()->Get('plugin', 'tenant', 'common');
|
||||||
{
|
|
||||||
if ($oAccount instanceof MainAccount && \str_ends_with($oAccount->Email(), '@hotmail.com')) {
|
|
||||||
$oActions = \RainLoop\Api::Actions();
|
|
||||||
try {
|
|
||||||
$aData = static::$auth ?: \SnappyMail\Crypt::DecryptFromJSON(
|
|
||||||
$oActions->StorageProvider()->Get($oAccount, StorageType::SESSION, \RainLoop\Utils::GetSessionToken()),
|
|
||||||
$oAccount->CryptKey()
|
|
||||||
);
|
|
||||||
} catch (\Throwable $oException) {
|
|
||||||
// $oActions->Logger()->WriteException($oException, \LOG_ERR);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (!empty($aData['expires']) && !empty($aData['access_token']) && !empty($aData['refresh_token'])) {
|
|
||||||
if (\time() >= $aData['expires']) {
|
|
||||||
$iExpires = \time();
|
|
||||||
$oO365 = $this->o365Connector();
|
|
||||||
if ($oO365) {
|
|
||||||
$aRefreshTokenResponse = $oO365->getAccessToken(
|
|
||||||
\str_replace('{{tenant}}', $this->Config()->Get('plugin', 'tenant', 'common'), static::TOKEN_URI),
|
|
||||||
'refresh_token',
|
|
||||||
array('refresh_token' => $aData['refresh_token'])
|
|
||||||
);
|
|
||||||
if (!empty($aRefreshTokenResponse['result']['access_token'])) {
|
|
||||||
$aData['access_token'] = $aRefreshTokenResponse['result']['access_token'];
|
|
||||||
$aResponse['expires'] = $iExpires + $aResponse['expires_in'];
|
|
||||||
$oActions->StorageProvider()->Put($oAccount, StorageType::SESSION, \RainLoop\Utils::GetSessionToken(),
|
|
||||||
\SnappyMail\Crypt::EncryptToJSON($aData, $oAccount->CryptKey())
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
$oSettings->passphrase = $aData['access_token'];
|
|
||||||
\array_unshift($oSettings->SASLMechanisms, 'OAUTHBEARER', 'XOAUTH2');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
protected function o365Connector() : ?\OAuth2\Client
|
$aTokenWrap = $oO365->getAccessToken(
|
||||||
{
|
\str_replace('{{tenant}}', $tenant, static::TOKEN_URI),
|
||||||
$client_id = \trim($this->Config()->Get('plugin', 'client_id', ''));
|
'authorization_code',
|
||||||
$client_secret = \trim($this->Config()->getDecrypted('plugin', 'client_secret', ''));
|
[
|
||||||
if ($client_id && $client_secret) {
|
'code' => $_GET['code'],
|
||||||
try
|
'redirect_uri' => $redirectUri
|
||||||
{
|
]
|
||||||
$oO365 = new \OAuth2\Client($client_id, $client_secret);
|
);
|
||||||
$oActions = \RainLoop\Api::Actions();
|
|
||||||
$sProxy = $oActions->Config()->Get('labs', 'curl_proxy', '');
|
if (!\is_array($aTokenWrap) || !isset($aTokenWrap['code'])) {
|
||||||
if (\strlen($sProxy)) {
|
throw new \RuntimeException('Token request failed: ' . \json_encode($aTokenWrap));
|
||||||
$oO365->setCurlOption(CURLOPT_PROXY, $sProxy);
|
}
|
||||||
$sProxyAuth = $oActions->Config()->Get('labs', 'curl_proxy_auth', '');
|
if (200 !== (int)$aTokenWrap['code']) {
|
||||||
if (\strlen($sProxyAuth)) {
|
$err = $aTokenWrap['result']['error'] ?? '';
|
||||||
$oO365->setCurlOption(CURLOPT_PROXYUSERPWD, $sProxyAuth);
|
$desc = $aTokenWrap['result']['error_description'] ?? '';
|
||||||
}
|
throw new \RuntimeException("Token HTTP {$aTokenWrap['code']}: {$err} / {$desc}");
|
||||||
}
|
}
|
||||||
return $oO365;
|
|
||||||
}
|
$aToken = $aTokenWrap['result'] ?? [];
|
||||||
catch (\Exception $oException)
|
$accessToken = $aToken['access_token'] ?? '';
|
||||||
{
|
$refreshToken = $aToken['refresh_token'] ?? '';
|
||||||
$oActions->Logger()->WriteException($oException, \LOG_ERR);
|
$expiresIn = (int)($aToken['expires_in'] ?? 0);
|
||||||
}
|
$idToken = $aToken['id_token'] ?? '';
|
||||||
}
|
|
||||||
return null;
|
if ($accessToken === '') {
|
||||||
}
|
throw new \RuntimeException('access_token missing');
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($refreshToken === '') {
|
||||||
|
throw new \RuntimeException('refresh_token missing');
|
||||||
|
}
|
||||||
|
if ($idToken === '') {
|
||||||
|
// We rely on id_token to get email/sub without Graph.
|
||||||
|
throw new \RuntimeException('id_token missing (add openid email profile scopes)');
|
||||||
|
}
|
||||||
|
|
||||||
|
// Parse id_token (JWT) to get identity (sub + email)
|
||||||
|
$claims = $this->decodeJwtPayload($idToken);
|
||||||
|
if (!\is_array($claims)) {
|
||||||
|
throw new \RuntimeException('Cannot decode id_token payload');
|
||||||
|
}
|
||||||
|
|
||||||
|
$email = $claims['email'] ?? ($claims['preferred_username'] ?? ($claims['upn'] ?? ''));
|
||||||
|
$sub = $claims['sub'] ?? '';
|
||||||
|
|
||||||
|
if ($sub === '') {
|
||||||
|
throw new \RuntimeException('unknown id from id_token');
|
||||||
|
}
|
||||||
|
if ($email === '') {
|
||||||
|
throw new \RuntimeException('unknown email address from id_token');
|
||||||
|
}
|
||||||
|
|
||||||
|
static::$auth = [
|
||||||
|
'access_token' => $accessToken,
|
||||||
|
'refresh_token' => $refreshToken,
|
||||||
|
'expires_in' => $expiresIn,
|
||||||
|
'expires' => $iNow + $expiresIn
|
||||||
|
];
|
||||||
|
|
||||||
|
// SnappyMail uses password as opaque string; plugin injects XOAUTH2 later.
|
||||||
|
$oPassword = new \SnappyMail\SensitiveString($sub);
|
||||||
|
$oAccount = $oActions->LoginProcess($email, $oPassword);
|
||||||
|
|
||||||
|
if ($oAccount) {
|
||||||
|
$oActions->StorageProvider()->Put(
|
||||||
|
$oAccount,
|
||||||
|
StorageType::SESSION,
|
||||||
|
\RainLoop\Utils::GetSessionToken(),
|
||||||
|
\SnappyMail\Crypt::EncryptToJSON(static::$auth, $oAccount->CryptKey())
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch (\Throwable $e) {
|
||||||
|
$oActions->Logger()->WriteException($e, \LOG_ERR);
|
||||||
|
}
|
||||||
|
|
||||||
|
$oActions->Location(\RainLoop\Utils::WebPath());
|
||||||
|
exit;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function configMapping() : array
|
||||||
|
{
|
||||||
|
return [
|
||||||
|
\RainLoop\Plugins\Property::NewInstance('client_id')
|
||||||
|
->SetLabel('Client ID')
|
||||||
|
->SetType(\RainLoop\Enumerations\PluginPropertyType::STRING)
|
||||||
|
->SetAllowedInJs(),
|
||||||
|
\RainLoop\Plugins\Property::NewInstance('client_secret')
|
||||||
|
->SetLabel('Client Secret')
|
||||||
|
->SetType(\RainLoop\Enumerations\PluginPropertyType::STRING)
|
||||||
|
->SetEncrypted(),
|
||||||
|
\RainLoop\Plugins\Property::NewInstance('tenant')
|
||||||
|
->SetLabel('Tenant')
|
||||||
|
->SetType(\RainLoop\Enumerations\PluginPropertyType::SELECTION)
|
||||||
|
->SetDefaultValue(['common','consumers','organizations'])
|
||||||
|
->SetAllowedInJs(),
|
||||||
|
\RainLoop\Plugins\Property::NewInstance('personal')
|
||||||
|
->SetLabel('Use /LoginO365 redirect path')
|
||||||
|
->SetType(\RainLoop\Enumerations\PluginPropertyType::BOOL)
|
||||||
|
->SetDefaultValue(false)
|
||||||
|
->SetAllowedInJs()
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
public function clientLogin(\RainLoop\Model\Account $oAccount, \MailSo\Net\NetClient $oClient, \MailSo\Net\ConnectSettings $oSettings) : void
|
||||||
|
{
|
||||||
|
$email = \strtolower($oAccount->Email());
|
||||||
|
|
||||||
|
if (
|
||||||
|
$oAccount instanceof MainAccount
|
||||||
|
&& (
|
||||||
|
\str_ends_with($email, '@hotmail.com')
|
||||||
|
|| \str_ends_with($email, '@outlook.com')
|
||||||
|
|| \str_ends_with($email, '@live.com')
|
||||||
|
)
|
||||||
|
) {
|
||||||
|
$oActions = \RainLoop\Api::Actions();
|
||||||
|
|
||||||
|
try {
|
||||||
|
$blob = $oActions->StorageProvider()->Get(
|
||||||
|
$oAccount,
|
||||||
|
StorageType::SESSION,
|
||||||
|
\RainLoop\Utils::GetSessionToken()
|
||||||
|
);
|
||||||
|
|
||||||
|
$aData = static::$auth ?: \SnappyMail\Crypt::DecryptFromJSON($blob, $oAccount->CryptKey());
|
||||||
|
} catch (\Throwable $e) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (empty($aData['access_token']) || empty($aData['refresh_token']) || empty($aData['expires'])) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Refresh if expired
|
||||||
|
if (\time() >= (int)$aData['expires']) {
|
||||||
|
$oO365 = $this->o365Connector();
|
||||||
|
if ($oO365) {
|
||||||
|
$tenant = $this->Config()->Get('plugin', 'tenant', 'common');
|
||||||
|
$aRefreshWrap = $oO365->getAccessToken(
|
||||||
|
\str_replace('{{tenant}}', $tenant, static::TOKEN_URI),
|
||||||
|
'refresh_token',
|
||||||
|
['refresh_token' => $aData['refresh_token']]
|
||||||
|
);
|
||||||
|
|
||||||
|
if (\is_array($aRefreshWrap) && isset($aRefreshWrap['code']) && 200 === (int)$aRefreshWrap['code']) {
|
||||||
|
$r = $aRefreshWrap['result'] ?? [];
|
||||||
|
if (!empty($r['access_token'])) {
|
||||||
|
$aData['access_token'] = $r['access_token'];
|
||||||
|
}
|
||||||
|
if (!empty($r['refresh_token'])) {
|
||||||
|
$aData['refresh_token'] = $r['refresh_token'];
|
||||||
|
}
|
||||||
|
$expiresIn = (int)($r['expires_in'] ?? 0);
|
||||||
|
if ($expiresIn > 0) {
|
||||||
|
$aData['expires'] = \time() + $expiresIn;
|
||||||
|
}
|
||||||
|
|
||||||
|
$oActions->StorageProvider()->Put(
|
||||||
|
$oAccount,
|
||||||
|
StorageType::SESSION,
|
||||||
|
\RainLoop\Utils::GetSessionToken(),
|
||||||
|
\SnappyMail\Crypt::EncryptToJSON($aData, $oAccount->CryptKey())
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Inject XOAUTH2/OAUTHBEARER
|
||||||
|
$oSettings->passphrase = $aData['access_token'];
|
||||||
|
\array_unshift($oSettings->SASLMechanisms, 'OAUTHBEARER', 'XOAUTH2');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function o365Connector() : ?\OAuth2\Client
|
||||||
|
{
|
||||||
|
$client_id = \trim($this->Config()->Get('plugin', 'client_id', ''));
|
||||||
|
$client_secret = \trim($this->Config()->getDecrypted('plugin', 'client_secret', ''));
|
||||||
|
|
||||||
|
if ($client_id && $client_secret) {
|
||||||
|
try {
|
||||||
|
$oO365 = new \OAuth2\Client($client_id, $client_secret);
|
||||||
|
|
||||||
|
$oActions = \RainLoop\Api::Actions();
|
||||||
|
$sProxy = $oActions->Config()->Get('labs', 'curl_proxy', '');
|
||||||
|
if (\strlen($sProxy)) {
|
||||||
|
$oO365->setCurlOption(CURLOPT_PROXY, $sProxy);
|
||||||
|
$sProxyAuth = $oActions->Config()->Get('labs', 'curl_proxy_auth', '');
|
||||||
|
if (\strlen($sProxyAuth)) {
|
||||||
|
$oO365->setCurlOption(CURLOPT_PROXYUSERPWD, $sProxyAuth);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return $oO365;
|
||||||
|
} catch (\Throwable $e) {
|
||||||
|
\RainLoop\Api::Actions()->Logger()->WriteException($e, \LOG_ERR);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private function decodeJwtPayload(string $jwt) : ?array
|
||||||
|
{
|
||||||
|
$parts = \explode('.', $jwt);
|
||||||
|
if (\count($parts) < 2) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
$payload = $parts[1];
|
||||||
|
$payload .= \str_repeat('=', (4 - (\strlen($payload) % 4)) % 4);
|
||||||
|
$json = \base64_decode(\strtr($payload, '-_', '+/'));
|
||||||
|
if ($json === false) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
$data = \json_decode($json, true);
|
||||||
|
return \is_array($data) ? $data : null;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
Loading…
Add table
Add a link
Reference in a new issue