Files
itflow/admin/oauth_microsoft_mail_callback.php

94 lines
4.2 KiB
PHP

<?php
require_once "../config.php";
require_once "../functions.php";
require_once "../includes/check_login.php";
$settings_mail_path = '/admin/settings_mail.php?tab=oauth';
if (!isset($session_is_admin) || !$session_is_admin) {
flashAlert("Admin access required.", 'error');
redirect($settings_mail_path);
}
$state = escapeSql($_GET['state'] ?? '');
$code = $_GET['code'] ?? '';
$error = escapeSql($_GET['error'] ?? '');
$error_description = escapeSql($_GET['error_description'] ?? '');
$session_state = $_SESSION['mail_oauth_state'] ?? '';
$session_state_expires = intval($_SESSION['mail_oauth_state_expires_at'] ?? 0);
// Graph's permissions or Exchange's - what Connect asked Microsoft for (functions/mail_graph.php)
$way = ($_SESSION['mail_oauth_way'] ?? '') === 'graph' ? 'graph' : 'exchange';
unset($_SESSION['mail_oauth_state'], $_SESSION['mail_oauth_state_expires_at'], $_SESSION['mail_oauth_way']);
if (!empty($error)) {
$msg = "Microsoft OAuth authorization failed: $error";
if (!empty($error_description)) {
$msg .= " ($error_description)";
}
flashAlert($msg, 'error');
redirect($settings_mail_path);
}
if (empty($state) || empty($code) || empty($session_state) || !hash_equals($session_state, $state) || time() > $session_state_expires) {
flashAlert("Microsoft OAuth callback validation failed. Please try connecting again.", 'error');
redirect($settings_mail_path);
}
if (empty($config_mail_oauth_client_id) || empty($config_mail_oauth_client_secret) || empty($config_mail_oauth_tenant_id)) {
flashAlert("Microsoft OAuth settings are incomplete. Please fill Client ID, Client Secret, and Tenant ID.", 'error');
redirect($settings_mail_path);
}
if (defined('BASE_URL') && !empty(BASE_URL)) {
$base_url = rtrim((string) BASE_URL, '/');
} else {
$base_url = 'https://' . rtrim((string) $config_base_url, '/');
}
$redirect_uri = $base_url . '/admin/oauth_microsoft_mail_callback.php';
// Redeemed for what was asked for - a sign-in to one API at a time
$response = mailGraphHttp('POST', MAIL_MICROSOFT_LOGIN_URL . rawurlencode($config_mail_oauth_tenant_id) . '/oauth2/v2.0/token', [], [
'client_id' => $config_mail_oauth_client_id,
'client_secret' => $config_mail_oauth_client_secret,
'grant_type' => 'authorization_code',
'code' => $code,
'redirect_uri' => $redirect_uri,
'scope' => mailMicrosoftConnectScope($way),
], 20);
$json = $response['json'];
if (empty($json['refresh_token']) || empty($json['access_token'])) {
flashAlert(escapeHtml($response['status'] >= 200 && $response['status'] < 300
? 'Microsoft OAuth token exchange failed: refresh token or access token missing.'
: mailGraphError($response, 'Microsoft OAuth token exchange')), 'error');
redirect($settings_mail_path);
}
$refresh_token = (string) $json['refresh_token'];
// An SMTP and IMAP sign-in is kept as what they sign in with - a Graph one isn't theirs, so they get their own when needed
$access_token = $way === 'exchange' ? (string) $json['access_token'] : '';
$expires_at_sql = $way === 'exchange' ? "'" . date('Y-m-d H:i:s', time() + intval($json['expires_in'] ?? 3600)) . "'" : 'NULL';
// Only the token - Sending and Receiving stay as they were set; connecting for one doesn't turn on the other. Sealed (functions/mail_secret.php)
mysqli_query($mysqli, "UPDATE settings SET
" . mailSecretSql('config_mail_oauth_refresh_token', $refresh_token) . ",
" . mailSecretSql('config_mail_oauth_access_token', $access_token) . ",
config_mail_oauth_access_token_expires_at = $expires_at_sql
WHERE company_id = 1
");
// What Microsoft Graph can do is asked afresh with the new sign-in, and SMTP and IMAP for the rest (functions/mail_graph.php)
mailGraphForget();
$check = mailMicrosoftCheck($config_smtp_provider === 'microsoft_oauth', $config_imap_provider === 'microsoft_oauth', false);
logAudit("Settings", "Edit", "$session_name connected Microsoft 365 for mail" . ($way === 'graph' ? ' through Microsoft Graph' : ' by SMTP and IMAP'));
flashAlert($check['ok']
? 'Microsoft 365 connected. ' . escapeHtml($check['message'])
: '<strong>Microsoft 365 is connected, but email can\'t go yet:</strong> ' . escapeHtml($check['message']), $check['ok'] ? 'success' : 'warning');
redirect($settings_mail_path);