Add identity providers for agents and client contacts: Admin, Identity Providers under Integrations adds Microsoft 365, Google Workspace and Nextcloud (OIDC Identity Provider app) sign-in buttons and IMAP mail-password sign-in, each for agents, client contacts or both and for the email domains listed; no account is created by signing in; Microsoft, Google and Nextcloud stand in for ITFlow two-step sign-in while IMAP still asks for the code; a provider can be required, turning off password sign-in on its domains with passkeys and administrator passwords still working; credentials stay locked after a provider or mail password sign-in until the ITFlow password is typed; the client portal Microsoft Entra single sign-on moves to a Microsoft 365 provider keeping its redirect address; database 4.2.5 adds identity_providers and drops the old Entra settings; 26.12.3 changelog entries

This commit is contained in:
johnnyq
2026-11-29 20:13:10 -05:00
parent 626f472990
commit fffa5680db
32 changed files with 1671 additions and 340 deletions

View File

@@ -639,7 +639,7 @@ function portalContactRoles(array $row) {
/**
* Give a contact of this client portal access and email them how to sign in -
* a link to set their password, or for Microsoft a link to the sign-in page.
* a link to set their password, or for an identity provider a link to the sign-in page.
* Makes their portal user when they have none, turns it back on when it was
* off, and sends the invite again when it is on. $by is the primary contact
* doing it. ['ok' => bool, 'error' => why not, 'emailed' => bool].
@@ -654,7 +654,7 @@ function portalContactInvite($contact_id, $method, $by) {
if (!$contact) {
return ['ok' => false, 'error' => "That person isn't here", 'emailed' => false];
}
if (!isset(portalSignInMethods()[$method])) {
if (!isset(portalSignInMethods($contact['contact_email'])[$method])) {
$method = 'local';
}
$name = (string) $contact['contact_name'];
@@ -675,7 +675,7 @@ function portalContactInvite($contact_id, $method, $by) {
mysqli_query($mysqli, "UPDATE contacts SET contact_user_id = $user_id WHERE contact_id = $contact_id AND contact_client_id = $client_id");
}
// The email - a link to set their password, or for Microsoft the sign-in page (functions/portal.php)
// The email - a link to set their password, or for an identity provider the sign-in page (functions/portal.php)
$emailed = portalMailInvite($user_id, $by);
if (!$emailed && $method !== 'local') {
portalPasswordLinkClear($user_id);

View File

@@ -123,7 +123,7 @@ if (!$portal_view_as) {
// in the request (requestIsMfaSetup()).
// A passkey sign-in is two-step sign-in already (functions/passkey.php)
$portal_mfa_setup_needed = !$portal_view_as && intval($config_client_portal_require_mfa ?? 0) === 1 && $session_auth_method === 'local' && !$session_mfa_on
&& ($_SESSION['signed_in_with'] ?? '') !== 'passkey';
&& !in_array($_SESSION['signed_in_with'] ?? '', ['passkey', 'provider'], true);
if ($portal_mfa_setup_needed && !requestIsMfaSetup([
'client/profile.php' => [[['mfa'], []]],
'client/post.php' => [[[], ['csrf_token', 'portal_mfa_enable', 'verify_code']], [['logout'], []]],

View File

@@ -3,7 +3,7 @@
* Client Portal
* Joining - from an invite (ours, or a colleague's in the portal) or the link
* to finish signing up: ?invite=&token=. The person puts in their name, job
* title, phone and a password - or, when Microsoft 365 sign-in is set up,
* title, phone and a password - or, when an identity provider signs in their address,
* chooses that instead - and is made a contact who can sign in
* (portalInviteAccept(), functions/portal_invite.php). Then they sign in on
* the usual page. A link that has run out, been used or cancelled says so,
@@ -43,6 +43,8 @@ $error = '';
$in = ['name' => '', 'title' => '', 'phone' => ''];
if ($invite && $link['state'] === 'pending') {
// Only an identity provider that signs in their address (functions/identity_provider.php)
$methods = portalSignInMethods($invite['invite_email']);
$who = portalInviteWho($invite['invite_email'], $invite['invite_client_id']);
$in['name'] = trim((string) $invite['invite_name']) !== '' ? (string) $invite['invite_name'] : (string) ($who['name'] ?? '');
@@ -61,7 +63,7 @@ if ($invite && $link['state'] === 'pending') {
if ($contact_id) {
$first = strtok(trim(preg_replace('/\s+/', ' ', $in['name'])), ' ');
$_SESSION['login_message'] = "Welcome, $first - your account is ready. " . (isset($methods[$method]) && $method === 'azure'
? 'Sign in with your Microsoft 365 account below.'
? 'Sign in with your ' . identityProviderContactsWording($invite['invite_email']) . ' account below.'
: 'Sign in with ' . $invite['invite_email'] . ' and your new password.');
$_SESSION['login_message_type'] = 'success';
redirect("/login.php");
@@ -169,7 +171,7 @@ $title = $state === 'pending' ? ($signup ? 'Finish signing up' : 'Join ' . $invi
<button type="submit" class="btn btn-primary w-100 mb-2"><i class="fas fa-check me-2"></i><?= $signup ? 'Create my account' : 'Join' ?></button>
<?php if (isset($methods['azure'])) { ?>
<div class="text-center small text-body-secondary my-2">or, with no password here</div>
<button type="submit" class="btn btn-outline-secondary w-100 mb-3" name="method" value="azure" formnovalidate data-join-microsoft><i class="fab fa-microsoft me-2"></i>Use My Microsoft 365 Account</button>
<button type="submit" class="btn btn-outline-secondary w-100 mb-3" name="method" value="azure" formnovalidate data-join-microsoft><i class="fas fa-id-badge me-2"></i>Use My <?= escapeHtml(identityProviderContactsWording($invite['invite_email'])) ?> Account</button>
<?php } ?>
</form>

View File

@@ -1,203 +1,10 @@
<?php
/*
* Client Portal
* OAuth Login via Microsoft IDP
* Client Portal - signing in with the Microsoft Entra app the portal used before identity
* providers (functions/identity_provider.php). This is the address registered with that app, so
* it stays, for the provider it became (database 4.2.5): login_provider.php, sending people back
* here.
*/
require_once '../config.php';
require_once '../functions.php';
require_once __DIR__ . "/../includes/session_init.php";
// Set Timezone after session starts
require_once "../includes/inc_set_timezone.php";
// A managed instance its manager has suspended (functions/managed.php)
managedRequestGuard('login');
$session_ip = escapeSql(getIP());
$session_user_agent = escapeSql($_SERVER['HTTP_USER_AGENT'] ?? '');
$sql_settings = mysqli_query($mysqli, "SELECT config_azure_client_id, config_azure_client_secret, config_client_portal_enable FROM settings WHERE company_id = 1");
$settings = mysqli_fetch_assoc($sql_settings);
// No portal, no portal sign-in - as with a password
if (intval($settings['config_client_portal_enable'] ?? 0) !== 1) {
redirect("../login.php");
}
$client_id = $settings['config_azure_client_id'];
$client_secret = $settings['config_azure_client_secret'];
$redirect_uri = "https://$config_base_url/client/login_microsoft.php";
# https://docs.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-auth-code-flow
$auth_code_url = "https://login.microsoftonline.com/organizations/oauth2/v2.0/authorize";
$token_grant_url = "https://login.microsoftonline.com/organizations/oauth2/v2.0/token";
// Initial Login Request, via Microsoft
// Returns an authorization code if login was successful
if ($_SERVER['REQUEST_METHOD'] == "GET" && !isset($_GET['code']) && !isset($_GET['error'])) {
// Single-use random state held server side. Never the session ID - that
// would put it in the URL, browser history and Microsoft's logs.
try {
$state = bin2hex(random_bytes(32));
} catch (Throwable $e) {
$state = sha1(uniqid((string) mt_rand(), true));
}
$_SESSION['azure_oauth_state'] = $state;
$_SESSION['azure_oauth_state_expires_at'] = time() + 600;
$params = array (
'client_id' => $client_id,
'redirect_uri' => $redirect_uri,
'response_type' => 'code',
// Must come back as a top-level GET - a SameSite=Lax session cookie is
// not sent on the cross-site POST that form_post produces
'response_mode' => 'query',
'scope' => 'https://graph.microsoft.com/User.Read',
'state' => $state);
redirect($auth_code_url . '?' . http_build_query($params));
}
// Microsoft has redirected back with an authorization code (or an error)
// Request an access token using authorization code (& client secret) (server side)
if (isset($_GET['code']) || isset($_GET['error'])) {
$state = is_string($_GET['state'] ?? null) ? $_GET['state'] : '';
$session_state = $_SESSION['azure_oauth_state'] ?? '';
$session_state_expires = intval($_SESSION['azure_oauth_state_expires_at'] ?? 0);
// Single use, consumed whether or not it validates
unset($_SESSION['azure_oauth_state'], $_SESSION['azure_oauth_state_expires_at']);
if (!empty($_GET['error'])) {
$_SESSION['login_message'] = 'Something went wrong with logging you in: Microsoft returned an error. Please try again.';
redirect("../login.php");
}
if (empty($state) || empty($session_state) || !hash_equals($session_state, $state) || time() > $session_state_expires) {
$_SESSION['login_message'] = 'Something went wrong with logging you in: the sign-in request could not be verified. Please try again.';
redirect("../login.php");
}
$params = array (
'client_id' =>$client_id,
'code' => is_string($_GET['code'] ?? null) ? $_GET['code'] : '',
'redirect_uri' => $redirect_uri,
'grant_type' => 'authorization_code',
'client_secret' => $client_secret
);
// Send request via CURL (server side) so user cannot see the client secret
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $token_grant_url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt(
$ch,
CURLOPT_POSTFIELDS,
http_build_query($params)
);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
#curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); // DEBUG ONLY - WAMP
$access_token_response = json_decode(curl_exec($ch), 1);
// Check if we have an access token
// If we do, send a request to Microsoft Graph API to get user info
if (isset($access_token_response['access_token'])) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPHEADER, array ('Authorization: Bearer '.$access_token_response['access_token'],
'Content-type: application/json'));
curl_setopt($ch, CURLOPT_URL, "https://graph.microsoft.com/v1.0/me/");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
#curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); // DEBUG ONLY - WAMP
$msgraph_response = json_decode(curl_exec($ch), 1);
if (isset($msgraph_response['error'])) {
// Something went wrong verifying the token/using the Graph API - quit
error_log("ITFlow: MS Graph API error during client portal Entra login: " . json_encode($msgraph_response['error']));
$_SESSION['login_message'] = 'Something went wrong with logging you in: could not read your profile from Microsoft. Please try again.';
redirect("../login.php");
} elseif (isset($msgraph_response['id'])) {
$upn = mysqli_real_escape_string($mysqli, $msgraph_response["userPrincipalName"]);
$sql = mysqli_query($mysqli, "SELECT contact_client_id, contact_id, user_auth_method, user_email, user_id, user_password FROM users
LEFT JOIN contacts ON user_id = contact_user_id
LEFT JOIN clients ON contact_client_id = client_id
WHERE user_email = '$upn'
AND user_archived_at IS NULL
AND contact_archived_at IS NULL
AND client_archived_at IS NULL
AND user_type = 2
AND user_status = 1
LIMIT 1"
);
$row = mysqli_fetch_assoc($sql);
$client_id = intval($row['contact_client_id']);
$user_id = intval($row['user_id']);
$session_user_id = $user_id; // to pass the user_id to logAction function
$contact_id = intval($row['contact_id']);
$user_email = escapeSql($row['user_email']);
$user_auth_method = escapeSql($row['user_auth_method']);
if ($user_auth_method == 'azure') {
// New session ID for the authenticated session (CWE-384)
session_regenerate_id(true);
$_SESSION['client_logged_in'] = true;
$_SESSION['client_id'] = $client_id;
$_SESSION['user_id'] = $user_id;
$_SESSION['user_type'] = 2;
$_SESSION['contact_id'] = $contact_id;
$_SESSION['csrf_token'] = randomString(32);
$_SESSION['login_method'] = "azure";
// A later password change ends this session (userSessionStamp())
$_SESSION['user_session_stamp'] = userSessionStamp($row['user_password'] ?? '');
unset($_SESSION['portal_view_as']); // an agent's View as contact in this browser ends here
// Logging
logAudit("Client Login", "Success", "Client contact $upn successfully logged in via Entra", $client_id, $user_id);
redirect("index.php");
} else {
// Logged with why, against the account when there is one (functions/sign_in.php)
$entra_why = $row ? ['user_id' => $user_id, 'client_id' => $client_id, 'reason' => 'the account signs in with a password, not Microsoft 365'] : signInFailureReason($msgraph_response['userPrincipalName']);
signInLogFailure('Client Login', 'Failed', "Failed client portal sign in via Entra as $upn - " . escapeSql($entra_why['reason']), $entra_why['user_id'], $entra_why['client_id']);
$_SESSION['login_message'] = 'Something went wrong with logging you in: Your account is not configured for Entra SSO. Please ensure you are setup in ITFlow as a contact and have Entra SSO configured.';
redirect("../login.php");
}
}
redirect('index.php');
} else {
error_log("ITFlow: no access_token returned during client portal Entra login");
$_SESSION['login_message'] = 'Something went wrong with logging you in: Microsoft did not return an access token. Please try again.';
redirect("../login.php");
}
}
// If the user is just sat on the page, send them back to log in to try again
redirect("../login.php");
require __DIR__ . '/../login_provider.php';

View File

@@ -232,7 +232,7 @@ $csrf = escapeHtml($_SESSION['csrf_token']);
<?php if ($microsoft_account) { ?>
<div class="itflow-portal-panel-body">
<p class="mb-0">You sign in with your Microsoft 365 account - Microsoft looks after your password and its own sign-in checks.</p>
<p class="mb-0">You sign in with your <?= escapeHtml(identityProviderContactsWording(stripslashes($session_contact_email))) ?> account - it looks after your password and its own sign-in checks.</p>
</div>
<?php } elseif (!$password_account) { ?>
<div class="itflow-portal-panel-body">