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

@@ -73,13 +73,13 @@ function contactAvatarData($client_id, $contact_id, $name, $photo) {
/**
* How they log in to the client portal, or '' with no access: 'Password'
* or 'Microsoft'.
* or 'Identity provider' (only through one, functions/identity_provider.php).
*/
function contactPortalAccess($contact_user_id, $auth_method) {
if (!intval($contact_user_id) || (string) $auth_method === '') {
return '';
}
return $auth_method === 'azure' ? 'Microsoft' : 'Password';
return $auth_method === 'azure' ? 'Identity provider' : 'Password';
}
/**

View File

@@ -268,7 +268,7 @@ function credentialFormSet($post, $client_id, &$error = '') {
$password = encryptCredentialEntry(trim((string) ($post['password'] ?? '')));
$otp = credentialOtpEncrypt($otp);
if ($username === false || $password === false || $otp === false) {
$error = vaultLocked() ? 'Your credentials are locked - you signed in with a passkey that can\'t open them. Unlock them with your password (the lock beside a username), then save again.'
$error = vaultLocked() ? 'Your credentials are locked - ' . vaultLockedReason() . '. Unlock them with your password (the lock beside a username), then save again.'
: 'Your vault session has expired, so the login could not be encrypted - sign out and back in, then try again.';
return null;
}

View File

@@ -62,7 +62,7 @@ const DEMO_MODE_LOCKS = [
],
[
'message' => "Sign-in security and identity providers can't be changed in the demo.",
'keys' => ['edit_security_settings', 'edit_identity_provider'],
'keys' => ['edit_security_settings', 'save_identity_provider', 'turn_identity_provider_on', 'turn_identity_provider_off', 'delete_identity_provider'],
],
[
'message' => "API keys can't be made or changed in the demo.",

View File

@@ -0,0 +1,679 @@
<?php
/*
* ITFlow - identity providers (database 4.2.5, identity_providers): agents and client contacts
* signing in with their Microsoft 365, Google Workspace or Nextcloud account, or with their mail
* password through an IMAP server (Admin > Identity Providers, admin/identity_providers.php).
*
* Who a provider signs in goes by email domain: each provider is for agents, client contacts or
* both, and lists the email domains it signs in - any account on them can use it. Microsoft 365
* and Google can leave the list empty and sign in any account, as both vouch for the address
* (Microsoft's sign-in name is on a domain its directory has proved it owns, and Google says when
* an address is verified); Nextcloud and IMAP need it, as a Nextcloud's users can set their own email
* address, and a mail server only says whether a password is right.
* A provider made required turns off password sign-in for the accounts on its domains - an
* agent with an administrator role keeps theirs, to get back in when it is down. No one is made
* an account by signing in: an agent, or a contact with portal access, has to be there already.
*
* Microsoft 365, Google and Nextcloud sign in by OpenID Connect's code flow (login_provider.php):
* the button on the sign-in page goes to the provider, which sends them back with a code; ITFlow
* swaps it for a token, server to server with the app's secret and PKCE, and asks the provider
* who they are - Microsoft Graph's /me, or the userinfo endpoint. Their own two-step sign-in
* stands in for ITFlow's. IMAP is a password, so it is checked in the password step of
* login.php instead of ITFlow's - against the mail server - and the two-step code is still asked.
* An administrator's ITFlow password still works too, for when the mail server is down.
*
* An agent signed in through a provider has their credentials locked until they type their ITFlow
* password once (vaultUnlock()), as the vault key is opened with it and the provider never sees it.
*/
/** Whether the database has identity providers yet (4.2.5). */
function identityProvidersReady() {
global $mysqli;
static $ready = null;
if ($ready === null) {
if (defined('CURRENT_DATABASE_VERSION')) {
$version = CURRENT_DATABASE_VERSION;
} else {
$result = mysqli_query($mysqli, "SELECT config_current_database_version FROM settings WHERE company_id = 1");
$version = $result && ($row = mysqli_fetch_row($result)) ? (string) $row[0] : '0';
}
$ready = version_compare($version, '4.2.5', '>=');
}
return $ready;
}
/** The kinds of identity provider, and what each needs. */
function identityProviderKinds() {
return [
'microsoft' => [
'name' => 'Microsoft 365',
'button' => 'Sign in with Microsoft',
'icon' => 'fab fa-microsoft',
'oauth' => true,
'domains_optional' => true,
'about' => 'Work accounts in Microsoft 365 - an app registered in Microsoft Entra',
'fields' => ['client_id', 'client_secret', 'tenant'],
],
'google' => [
'name' => 'Google Workspace',
'button' => 'Sign in with Google',
'icon' => 'fab fa-google',
'oauth' => true,
'domains_optional' => true,
'about' => 'Google Workspace accounts - an OAuth client in Google Cloud',
'fields' => ['client_id', 'client_secret'],
],
'nextcloud' => [
'name' => 'Nextcloud',
'button' => 'Sign in with Nextcloud',
'icon' => 'fas fa-cloud',
'oauth' => true,
'domains_optional' => false,
'about' => 'Nextcloud accounts - its OIDC Identity Provider app',
'fields' => ['url', 'client_id', 'client_secret'],
],
'imap' => [
'name' => 'IMAP',
'button' => '',
'icon' => 'fas fa-envelope',
'oauth' => false,
'domains_optional' => false,
'about' => 'A mail server - the password typed on the sign-in page is checked with it',
'fields' => ['url', 'port', 'security', 'username'],
],
];
}
/** The kind of an identity_providers row, or null when this ITFlow doesn't know it. */
function identityProviderKind(array $row) {
return identityProviderKinds()[(string) ($row['identity_provider_kind'] ?? '')] ?? null;
}
/** An identity provider's row, or null. */
function identityProviderRow($identity_provider_id) {
global $mysqli;
if (!identityProvidersReady()) {
return null;
}
return mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT * FROM identity_providers WHERE identity_provider_id = " . intval($identity_provider_id))) ?: null;
}
/** Every provider that is on, of a known kind - once a request. */
function identityProvidersOn() {
global $mysqli;
static $rows = null;
if ($rows === null) {
$rows = [];
if (identityProvidersReady()) {
$sql = mysqli_query($mysqli, "SELECT * FROM identity_providers WHERE identity_provider_enabled = 1 ORDER BY identity_provider_name ASC, identity_provider_id ASC");
while ($row = mysqli_fetch_assoc($sql)) {
if (identityProviderKind($row)) {
$rows[] = $row;
}
}
}
}
return $rows;
}
/** A list of email domains as they are kept - lowercase, one each, no @ - from what was typed. */
function identityProviderDomainList($text) {
$domains = [];
foreach (preg_split('/[\s,;]+/', strtolower((string) $text)) as $domain) {
$domain = trim($domain, " \t.@");
if ($domain !== '') {
$domains[$domain] = true;
}
}
return array_keys($domains);
}
/** Whether a domain is one - letters, digits and hyphens, in parts. */
function identityProviderDomainValid($domain) {
return (bool) preg_match('/^(?=.{1,253}$)([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z][a-z0-9-]{0,61}[a-z0-9]$/', $domain);
}
/** The domains a provider signs in - [] for any, where its kind allows that. */
function identityProviderDomains(array $row) {
return identityProviderDomainList($row['identity_provider_domains'] ?? '');
}
/** The part of an email address after the @, lowercase. */
function identityProviderEmailDomain($email) {
$at = strrpos((string) $email, '@');
return $at === false ? '' : strtolower(substr((string) $email, $at + 1));
}
/** Whether a provider signs in this email address - its domain is on the list, or the list is empty where that means any. */
function identityProviderCovers(array $row, $email) {
$kind = identityProviderKind($row);
if (!$kind) {
return false;
}
$domains = identityProviderDomains($row);
if (!$domains) {
return !empty($kind['domains_optional']);
}
return in_array(identityProviderEmailDomain($email), $domains, true);
}
/** Whether a provider is for this kind of account - 1 an agent, 2 a client contact (only while the portal is on). */
function identityProviderFor(array $row, $user_type) {
global $config_client_portal_enable;
if (intval($user_type) === 1) {
return intval($row['identity_provider_agents']) === 1;
}
return intval($row['identity_provider_contacts']) === 1 && intval($config_client_portal_enable ?? 0) === 1;
}
/** The IMAP provider that checks this account's password, or null. */
function identityProviderImapFor($email, $user_type) {
foreach (identityProvidersOn() as $row) {
if ($row['identity_provider_kind'] === 'imap' && identityProviderFor($row, $user_type) && identityProviderCovers($row, $email)) {
return $row;
}
}
return null;
}
/**
* The provider this account has to sign in with, when one on its domains is required - null when
* its password still works. An agent whose role is an administrator's keeps their password, to
* get back in when the provider is down or set up wrong.
*/
function identityProviderRequiredFor($email, $user_type, $role_id = 0) {
foreach (identityProvidersOn() as $row) {
$kind = identityProviderKind($row);
if (!$kind['oauth'] || intval($row['identity_provider_required']) !== 1 || !identityProviderDomains($row)
|| !identityProviderFor($row, $user_type) || !identityProviderCovers($row, $email)) {
continue;
}
if (intval($user_type) === 1 && identityProviderAdminRole($role_id)) {
continue;
}
return $row;
}
return null;
}
/** Whether an agent's role is an administrator's - who keeps their ITFlow password, to get back in when a provider is down. */
function identityProviderAdminRole($role_id) {
global $mysqli;
if (intval($role_id) <= 0) {
return false;
}
$admin = mysqli_fetch_row(mysqli_query($mysqli, "SELECT role_is_admin FROM user_roles WHERE role_id = " . intval($role_id)));
return intval($admin[0] ?? 0) === 1;
}
/** The providers with a button on the sign-in page - Microsoft 365, Google and Nextcloud that sign anyone in here. */
function identityProviderButtons() {
return array_values(array_filter(identityProvidersOn(), function ($row) {
return identityProviderKind($row)['oauth'] && (identityProviderFor($row, 1) || identityProviderFor($row, 2));
}));
}
/** Where a provider sends people back to - the address registered with it. */
function identityProviderRedirectUri(array $row) {
global $config_base_url;
$path = (string) ($row['identity_provider_redirect_path'] ?? '') ?: '/login_provider.php';
return 'https://' . preg_replace('#^https?://#', '', rtrim((string) $config_base_url, '/')) . $path;
}
/**
* The names of the providers on for client contacts, Microsoft 365, Google or Nextcloud - for what
* the portal tells them. With an email address, only the ones that sign that address in.
*/
function identityProviderNamesForContacts($email = null) {
$names = [];
foreach (identityProvidersOn() as $row) {
if (identityProviderKind($row)['oauth'] && identityProviderFor($row, 2) && ($email === null || identityProviderCovers($row, $email))) {
$names[] = (string) $row['identity_provider_name'];
}
}
return array_values(array_unique($names));
}
/** What contacts sign in with besides a password, for what they and agents are told - "Microsoft 365 or Google Workspace", or "an identity provider". */
function identityProviderContactsWording($email = null) {
$names = identityProviderNamesForContacts($email);
return $names ? implode(' or ', $names) : 'an identity provider';
}
/** A Nextcloud's address, as typed - https, no trailing slash. */
function identityProviderNextcloudUrl(array $row) {
return rtrim(trim((string) ($row['identity_provider_url'] ?? '')), '/');
}
/** An HTTP request to a provider - [status, decoded JSON or null, raw body]. Never sent anywhere but its own endpoints. */
function identityProviderHttp($method, $url, $fields = null, $headers = []) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
curl_setopt($ch, CURLOPT_TIMEOUT, 20);
curl_setopt($ch, CURLOPT_PROTOCOLS, CURLPROTO_HTTPS);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);
if ($method === 'POST') {
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query((array) $fields));
}
curl_setopt($ch, CURLOPT_HTTPHEADER, array_merge(['Accept: application/json'], $headers));
$body = curl_exec($ch);
$status = intval(curl_getinfo($ch, CURLINFO_HTTP_CODE));
curl_close($ch);
$json = is_string($body) ? json_decode($body, true) : null;
return [$status, is_array($json) ? $json : null, is_string($body) ? $body : ''];
}
/**
* Where a provider's sign-in happens - authorize, token and userinfo endpoints, and how the token
* endpoint takes the secret. Microsoft and Google are fixed; a Nextcloud says in its OpenID
* configuration. [endpoints, error].
*/
function identityProviderEndpoints(array $row) {
$kind = (string) $row['identity_provider_kind'];
if ($kind === 'microsoft') {
$tenant = trim((string) ($row['identity_provider_tenant'] ?? '')) ?: 'organizations';
$tenant = preg_match('/^[a-z0-9.-]{1,100}$/i', $tenant) ? $tenant : 'organizations';
return [[
'authorize' => "https://login.microsoftonline.com/$tenant/oauth2/v2.0/authorize",
'token' => "https://login.microsoftonline.com/$tenant/oauth2/v2.0/token",
'userinfo' => 'https://graph.microsoft.com/v1.0/me',
'scope' => 'openid profile email User.Read',
'auth' => 'post',
], ''];
}
if ($kind === 'google') {
return [[
'authorize' => 'https://accounts.google.com/o/oauth2/v2/auth',
'token' => 'https://oauth2.googleapis.com/token',
'userinfo' => 'https://openidconnect.googleapis.com/v1/userinfo',
'scope' => 'openid email profile',
'auth' => 'post',
], ''];
}
if ($kind === 'nextcloud') {
$base = identityProviderNextcloudUrl($row);
if (!preg_match('#^https://[^/\s]+#i', $base)) {
return [null, 'its address is not an https:// one'];
}
$config = null;
foreach (["$base/index.php/.well-known/openid-configuration", "$base/.well-known/openid-configuration"] as $url) {
[$status, $json] = identityProviderHttp('GET', $url);
if ($status === 200 && $json && !empty($json['authorization_endpoint']) && !empty($json['token_endpoint']) && !empty($json['userinfo_endpoint'])) {
$config = $json;
break;
}
}
if (!$config) {
return [null, "it didn't give its OpenID configuration - is its OIDC Identity Provider app installed?"];
}
foreach (['authorization_endpoint', 'token_endpoint', 'userinfo_endpoint'] as $key) {
if (stripos((string) $config[$key], 'https://') !== 0) {
return [null, 'its OpenID configuration gives an address that is not https://'];
}
}
$methods = (array) ($config['token_endpoint_auth_methods_supported'] ?? ['client_secret_post']);
return [[
'authorize' => (string) $config['authorization_endpoint'],
'token' => (string) $config['token_endpoint'],
'userinfo' => (string) $config['userinfo_endpoint'],
'scope' => 'openid profile email',
'auth' => in_array('client_secret_post', $methods, true) ? 'post' : 'basic',
], ''];
}
return [null, 'it is not a kind that signs in with a button'];
}
/** PKCE - a random verifier, and its S256 challenge. */
function identityProviderPkce() {
$verifier = rtrim(strtr(base64_encode(random_bytes(48)), '+/', '-_'), '=');
$challenge = rtrim(strtr(base64_encode(hash('sha256', $verifier, true)), '+/', '-_'), '=');
return [$verifier, $challenge];
}
/** The address that starts signing in with a provider. */
function identityProviderAuthorizeUrl(array $row, array $endpoints, $state, $challenge) {
$params = [
'client_id' => (string) $row['identity_provider_client_id'],
'redirect_uri' => identityProviderRedirectUri($row),
'response_type' => 'code',
// Back as a top-level GET - the session cookie isn't sent on a cross-site POST
'response_mode' => 'query',
'scope' => $endpoints['scope'],
'state' => $state,
'code_challenge' => $challenge,
'code_challenge_method' => 'S256',
'prompt' => 'select_account',
];
$domains = identityProviderDomains($row);
if ($row['identity_provider_kind'] === 'google' && count($domains) === 1) {
$params['hd'] = $domains[0]; // straight to their Workspace's accounts
}
if ($row['identity_provider_kind'] === 'nextcloud') {
unset($params['prompt'], $params['response_mode']);
}
return $endpoints['authorize'] . (str_contains($endpoints['authorize'], '?') ? '&' : '?') . http_build_query($params);
}
/**
* Who signed in, from the code the provider sent back - ['email' => ..., 'name' => ...], or
* ['error' => why, for the log]. The code is swapped for a token server to server, with the app's
* secret and the PKCE verifier, then the provider is asked who it is for.
*/
function identityProviderIdentity(array $row, array $endpoints, $code, $verifier) {
$fields = [
'grant_type' => 'authorization_code',
'code' => (string) $code,
'redirect_uri' => identityProviderRedirectUri($row),
'client_id' => (string) $row['identity_provider_client_id'],
'code_verifier' => (string) $verifier,
];
$headers = [];
if ($endpoints['auth'] === 'basic') {
$headers[] = 'Authorization: Basic ' . base64_encode(rawurlencode((string) $row['identity_provider_client_id']) . ':' . rawurlencode((string) $row['identity_provider_client_secret']));
} else {
$fields['client_secret'] = (string) $row['identity_provider_client_secret'];
}
[$status, $token] = identityProviderHttp('POST', $endpoints['token'], $fields, $headers);
if (empty($token['access_token']) || !is_string($token['access_token'])) {
$why = is_array($token) && !empty($token['error']) ? (string) $token['error'] . (!empty($token['error_description']) ? ' - ' . mb_substr((string) $token['error_description'], 0, 200) : '') : "HTTP $status";
return ['error' => "it gave no token for the code ($why)"];
}
[$status, $who] = identityProviderHttp('GET', $endpoints['userinfo'], null, ['Authorization: Bearer ' . $token['access_token']]);
if (!$who || $status !== 200) {
return ['error' => "it didn't say who signed in (HTTP $status)"];
}
$kind = (string) $row['identity_provider_kind'];
if ($kind === 'microsoft') {
// The sign-in name, on a domain the directory has proved it owns - not mail, which anyone in a directory can be given
$email = (string) ($who['userPrincipalName'] ?? '');
$name = (string) ($who['displayName'] ?? '');
if (str_contains($email, '#EXT#')) {
return ['error' => 'it is a guest account in another organization'];
}
} else {
$email = (string) ($who['email'] ?? '');
$name = (string) ($who['name'] ?? '');
if ($kind === 'google' && ($who['email_verified'] ?? false) !== true && ($who['email_verified'] ?? '') !== 'true') {
return ['error' => "Google hasn't verified the address $email"];
}
// A Nextcloud that says the address isn't verified is taken at its word
if ($kind === 'nextcloud' && array_key_exists('email_verified', $who) && $who['email_verified'] !== true && $who['email_verified'] !== 'true') {
return ['error' => "Nextcloud hasn't verified the address $email"];
}
}
$email = strtolower(trim($email));
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
return ['error' => 'it gave no email address'];
}
return ['email' => $email, 'name' => $name];
}
/**
* The accounts a provider can sign in for this address - ['agent' => user id or 0, 'client' =>
* user id or 0]: an agent that is active, and a contact with portal access at a current client.
*/
function identityProviderAccounts(array $row, $email) {
global $mysqli;
$accounts = ['agent' => 0, 'client' => 0];
if (!identityProviderCovers($row, $email)) {
return $accounts;
}
$email_sql = escapeSql($email);
if (identityProviderFor($row, 1)) {
$agent = mysqli_fetch_row(mysqli_query($mysqli, "SELECT user_id FROM users WHERE user_email = '$email_sql' AND user_type = 1 AND user_status = 1
AND user_archived_at IS NULL" . serviceAccountsOutSql('users.user_service_account') . " ORDER BY user_id LIMIT 1"));
$accounts['agent'] = intval($agent[0] ?? 0);
}
if (identityProviderFor($row, 2)) {
$contact = mysqli_fetch_row(mysqli_query($mysqli, "SELECT users.user_id FROM users
JOIN contacts ON contact_user_id = users.user_id AND contact_archived_at IS NULL
JOIN clients ON client_id = contact_client_id AND client_archived_at IS NULL
WHERE user_email = '$email_sql' AND user_type = 2 AND user_status = 1 AND user_archived_at IS NULL AND user_auth_method IN ('local', 'azure')
ORDER BY users.user_id LIMIT 1"));
$accounts['client'] = intval($contact[0] ?? 0);
}
return $accounts;
}
/** The name an IMAP server is given for this address - the address, or the part before the @. */
function identityProviderImapUsername(array $row, $email) {
return ($row['identity_provider_username'] ?? '') === 'local' ? substr((string) $email, 0, strrpos((string) $email, '@')) : (string) $email;
}
/**
* Whether the mail server takes this password for the address - [ok, why not, for the log]. A
* server that can't be reached is said apart from a wrong password, and goes in the app log.
*/
function identityProviderImapCheck(array $row, $email, #[\SensitiveParameter] $password) {
static $checked = [];
if ((string) $password === '' || strpos((string) $email, '@') === false) {
return [false, 'no password was typed'];
}
$key = intval($row['identity_provider_id']) . '|' . strtolower((string) $email) . '|' . hash('sha256', (string) $password);
if (isset($checked[$key])) {
return $checked[$key];
}
require_once dirname(__DIR__) . '/libs/vendor/autoload.php';
$security = (string) ($row['identity_provider_security'] ?? 'ssl');
$mailbox = new \DirectoryTree\ImapEngine\Mailbox([
'host' => (string) $row['identity_provider_url'],
'port' => intval($row['identity_provider_port']) ?: ($security === 'ssl' ? 993 : 143),
'encryption' => $security === 'none' ? '' : $security,
'validate_cert' => true,
'timeout' => 10,
'username' => identityProviderImapUsername($row, $email),
'password' => (string) $password,
]);
try {
$mailbox->connect();
try {
$mailbox->disconnect();
} catch (\Throwable $e) {
// Signed in is all that was asked
}
return $checked[$key] = [true, ''];
} catch (\DirectoryTree\ImapEngine\Exceptions\ImapCommandException $e) {
return $checked[$key] = [false, 'the mail server said the password is wrong'];
} catch (\Throwable $e) {
logApp('Identity Provider', 'warning', 'Could not reach the mail server for ' . $row['identity_provider_name'] . ' (' . $row['identity_provider_url'] . '): ' . mb_substr($e->getMessage(), 0, 300));
return $checked[$key] = [false, "the mail server couldn't be reached"];
}
}
/** A provider was just used to sign in - for its list. */
function identityProviderUsed($identity_provider_id) {
global $mysqli;
if (identityProvidersReady()) {
mysqli_query($mysqli, "UPDATE identity_providers SET identity_provider_used_at = NOW(), identity_provider_updated_at = identity_provider_updated_at WHERE identity_provider_id = " . intval($identity_provider_id));
}
}
/*
* ---------- Admin > Identity Providers ----------
*
* Add and Edit are one window (admin/modals/identity_provider/identity_provider_edit.php), saved by
* save_identity_provider (admin/post/identity_provider.php). Which kind it is stays once added.
* The secret is never put back into the page - left empty, it stays as saved.
*/
/** What is typed in an identity provider's window, checked - [the row to save, errors by field]. */
function identityProviderCheck(array $in, ?array $before): array
{
$errors = [];
$kind_key = $before ? (string) $before['identity_provider_kind'] : (string) ($in['kind'] ?? '');
$kind = identityProviderKinds()[$kind_key] ?? null;
if (!$kind) {
return [[], ['kind' => 'Pick the kind of identity provider.']];
}
$text = function ($key, $max = 255) use ($in) {
return trim((string) ($in[$key] ?? ''));
};
$fields = $kind['fields'];
$name = $text('name');
if ($name === '') {
$errors['name'] = 'Give it a name - its button on the sign-in page says Sign in with it.';
} elseif (mb_strlen($name) > 100) {
$errors['name'] = 'Its name is 100 characters at most.';
}
$agents = intval($in['agents'] ?? 0) === 1 ? 1 : 0;
$contacts = intval($in['contacts'] ?? 0) === 1 ? 1 : 0;
if (!$agents && !$contacts) {
$errors['agents'] = 'Pick who it signs in - agents, client contacts or both.';
}
$domains = identityProviderDomainList($text('domains'));
$bad = array_values(array_filter($domains, function ($domain) {
return !identityProviderDomainValid($domain);
}));
if ($bad) {
$errors['domains'] = $bad[0] . ' isn\'t an email domain - type them as example.com, with a comma between.';
} elseif (!$domains && !$kind['domains_optional']) {
$errors['domains'] = 'List the email domains it signs in - ' . ($kind_key === 'imap' ? 'the ones whose mailboxes are all on this server.' : 'the ones whose people are all on your Nextcloud.');
} elseif (strlen(implode(', ', $domains)) > 1000) {
$errors['domains'] = 'That many email domains don\'t fit - split them over two providers.';
}
$required = $kind['oauth'] && intval($in['required'] ?? 0) === 1 ? 1 : 0;
if ($required && !$domains) {
$errors['required'] = 'List the email domains it is required for.';
}
$client_id = $secret = $tenant = $url = '';
$port = 0;
$security = $username = '';
if (in_array('client_id', $fields, true)) {
$client_id = $text('client_id');
if ($client_id === '') {
$errors['client_id'] = $kind_key === 'microsoft' ? 'The Application (client) ID, from the app\'s Overview.' : 'Its client ID.';
} elseif ($kind_key === 'microsoft' && !preg_match('/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i', $client_id)) {
$errors['client_id'] = 'The Application (client) ID - 32 letters and numbers in five groups, as e721e3b6-01d6-50e8-7f22-c84d951a52e7.';
} elseif ($kind_key === 'google' && !preg_match('/^[A-Za-z0-9-]+\.apps\.googleusercontent\.com$/', $client_id)) {
$errors['client_id'] = 'The Client ID of the OAuth client - it ends in .apps.googleusercontent.com.';
} elseif (strlen($client_id) > 255 || preg_match('/\s/', $client_id)) {
$errors['client_id'] = 'That isn\'t a client ID - copy it again, with no spaces.';
}
$secret = (string) ($in['client_secret'] ?? '');
$secret = trim($secret) !== '' ? trim($secret) : (string) ($before['identity_provider_client_secret'] ?? '');
if ($secret === '') {
$errors['client_secret'] = $kind_key === 'microsoft' ? 'And a secret for it, from Certificates & secrets - its Value, not its ID.' : 'And its client secret.';
} elseif (strlen($secret) > 1000) {
$errors['client_secret'] = 'That is too long for a client secret - copy it again.';
}
}
if (in_array('tenant', $fields, true)) {
$tenant = strtolower($text('tenant'));
if (in_array($tenant, ['common', 'consumers'], true)) {
$errors['tenant'] = 'Personal Microsoft accounts can\'t sign in here - leave it empty for any organization\'s work accounts.';
} elseif ($tenant === 'organizations') {
$tenant = '';
} elseif ($tenant !== '' && !preg_match('/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/', $tenant) && !identityProviderDomainValid($tenant)) {
$errors['tenant'] = 'The Directory (tenant) ID, or one of its domains as contoso.onmicrosoft.com - or leave it empty.';
}
}
if ($kind_key === 'nextcloud') {
$url = rtrim($text('url'), '/');
$parts = parse_url($url);
if ($url === '' || !$parts || strtolower($parts['scheme'] ?? '') !== 'https' || empty($parts['host']) || isset($parts['query']) || isset($parts['fragment']) || isset($parts['user']) || strlen($url) > 500) {
$errors['url'] = 'Your Nextcloud\'s address, starting with https:// - as https://cloud.example.com.';
}
}
if ($kind_key === 'imap') {
$url = strtolower($text('url'));
if ($url === '' || (!identityProviderDomainValid($url) && !filter_var($url, FILTER_VALIDATE_IP))) {
$errors['url'] = 'The mail server\'s name, as mail.example.com.';
}
$security = (string) ($in['security'] ?? 'ssl');
if (!in_array($security, ['ssl', 'starttls', 'none'], true)) {
$security = 'ssl';
}
$port_text = $text('port');
$port = $port_text === '' ? ($security === 'ssl' ? 993 : 143) : intval($port_text);
if ($port < 1 || $port > 65535 || ($port_text !== '' && !ctype_digit($port_text))) {
$errors['port'] = 'A port is a number from 1 to 65535 - 993 for SSL/TLS, 143 for STARTTLS.';
}
$username = ($in['username'] ?? 'email') === 'local' ? 'local' : 'email';
}
$after = [
'identity_provider_kind' => $kind_key,
'identity_provider_name' => mb_substr($name, 0, 100),
'identity_provider_enabled' => intval($in['enabled'] ?? 0) === 1 ? 1 : 0,
'identity_provider_agents' => $agents,
'identity_provider_contacts' => $contacts,
'identity_provider_domains' => implode(', ', $domains),
'identity_provider_required' => $required,
'identity_provider_client_id' => $client_id,
'identity_provider_client_secret' => $secret,
'identity_provider_tenant' => $tenant,
'identity_provider_url' => $url,
'identity_provider_port' => $port,
'identity_provider_security' => $security,
'identity_provider_username' => $username,
];
// A Nextcloud has to say where its OpenID Connect is - asked when its address is new
if (!$errors && $kind_key === 'nextcloud' && (!$before || identityProviderNextcloudUrl($before) !== $url)) {
[, $why] = identityProviderEndpoints($after);
if ($why) {
$errors['url'] = 'ITFlow asked your Nextcloud, but ' . $why;
}
}
return [$after, $errors];
}
/** Save an identity provider's row - a new one when $identity_provider_id is 0. Its id. */
function identityProviderWrite(array $after, int $identity_provider_id = 0): int
{
global $mysqli;
$set = implode(', ', array_map(function ($column, $value) {
return "`$column` = '" . escapeSql((string) $value) . "'";
}, array_keys($after), $after));
if ($identity_provider_id) {
mysqli_query($mysqli, "UPDATE identity_providers SET $set WHERE identity_provider_id = $identity_provider_id");
return $identity_provider_id;
}
mysqli_query($mysqli, "INSERT INTO identity_providers SET $set");
return intval(mysqli_insert_id($mysqli));
}
/** What changed on an identity provider, for the audit log - its secret is never written down. */
function identityProviderChangeLines(array $before, array $after): array
{
$labels = [
'identity_provider_name' => 'name', 'identity_provider_enabled' => 'on', 'identity_provider_agents' => 'agents',
'identity_provider_contacts' => 'client contacts', 'identity_provider_domains' => 'email domains', 'identity_provider_required' => 'required',
'identity_provider_client_id' => 'client ID', 'identity_provider_client_secret' => 'secret', 'identity_provider_tenant' => 'tenant',
'identity_provider_url' => 'address', 'identity_provider_port' => 'port', 'identity_provider_security' => 'security', 'identity_provider_username' => 'username',
];
$switches = [
'identity_provider_enabled' => ['turned it on', 'turned it off'],
'identity_provider_agents' => ['signs in agents', 'no longer signs in agents'],
'identity_provider_contacts' => ['signs in client contacts', 'no longer signs in client contacts'],
'identity_provider_required' => ['made it required', 'made it not required'],
];
$lines = [];
foreach ($labels as $column => $label) {
$old = (string) ($before[$column] ?? '');
$new = (string) ($after[$column] ?? '');
if ($old === $new) {
continue;
}
if (isset($switches[$column])) {
$lines[] = $switches[$column][$new === '1' ? 0 : 1];
} elseif ($column === 'identity_provider_client_secret') {
$lines[] = 'a new secret';
} else {
$lines[] = "$label: " . ($old === '' ? '(none)' : $old) . ' to ' . ($new === '' ? '(none)' : $new);
}
}
return $lines;
}

View File

@@ -435,10 +435,22 @@ function vaultUnlock($user_id, #[\SensitiveParameter] $password) {
return [true, ''];
}
/*
* Why the vault is locked, as it is said to the agent - how they signed in without the password
* that opens it (login.php): a passkey that can't, an identity provider, or their mail password.
*/
function vaultLockedReason() {
$via = trim((string) ($_SESSION['signed_in_via'] ?? ''));
return [
'provider' => 'you signed in with ' . ($via !== '' ? $via : 'an identity provider') . ', which can\'t open them',
'imap' => 'you signed in with your mail password, which can\'t open them',
][$_SESSION['signed_in_with'] ?? ''] ?? 'you signed in with a passkey that can\'t open them';
}
/** The note in a credential window while the vault is locked - with the button that unlocks it (js/credentials.js). */
function vaultLockedAlertHtml() {
return '<div class="alert alert-warning small d-flex align-items-center gap-2"><i class="fas fa-lock"></i>'
. '<span class="flex-grow-1">Your credentials are locked - you signed in with a passkey that can\'t open them.</span>'
. '<span class="flex-grow-1">Your credentials are locked - ' . escapeHtml(vaultLockedReason()) . '.</span>'
. '<button type="button" class="btn btn-sm btn-warning text-nowrap" data-vault-unlock><i class="fas fa-unlock me-1"></i>Unlock</button></div>';
}

View File

@@ -100,7 +100,8 @@ function portalContactLastSignIn($user_id) {
/**
* Whether a contact can sign in to the portal, and how: key none (never set
* up), off (turned off), local (a password) or azure (Microsoft) - with a
* up), off (turned off), local (a password) or azure (only through an identity
* provider, functions/identity_provider.php) - with a
* label, icon and class for portalStateBadge() in client/functions.php. From
* a row with user_id, user_auth_method, user_status and user_archived_at
* (LEFT JOIN users).
@@ -113,7 +114,7 @@ function portalContactAccess(array $row) {
if (!in_array($method, ['local', 'azure'], true) || intval($row['user_status'] ?? 0) !== 1 || !empty($row['user_archived_at'])) {
return ['key' => 'off', 'label' => 'Portal access off', 'icon' => 'fa-ban', 'class' => 'itflow-portal-state-closed'];
}
return ['key' => $method, 'label' => $method === 'azure' ? 'Signs in with Microsoft' : 'Signs in with a password', 'icon' => 'fa-check', 'class' => 'itflow-portal-state-resolved'];
return ['key' => $method, 'label' => $method === 'azure' ? 'Signs in with ' . identityProviderContactsWording() : 'Signs in with a password', 'icon' => 'fa-check', 'class' => 'itflow-portal-state-resolved'];
}
/*
@@ -202,7 +203,7 @@ function portalUserAccessOn($user_id, $method) {
if (!empty($row['client_archived_at']) || !empty($row['contact_archived_at'])) {
return ($row['client_archived_at'] ? 'Their client' : 'The contact') . ' is archived - restore it first';
}
if (!isset(portalSignInMethods()[$method])) {
if (!isset(portalSignInMethods($row['user_email'])[$method])) {
$method = 'local';
}
$error = '';
@@ -213,12 +214,15 @@ function portalUserAccessOn($user_id, $method) {
return '';
}
/** The ways a portal user can sign in here - a password, and Microsoft when it is set up. method => label. */
function portalSignInMethods() {
global $config_azure_client_id;
/*
* The ways a portal user can sign in here - a password (and any identity provider on their email's
* domain), and only through a provider, when one is on for contacts - for this email address, when
* it is given. method => label.
*/
function portalSignInMethods($email = null) {
$methods = ['local' => 'With a password'];
if (!empty($config_azure_client_id)) {
$methods['azure'] = 'With their Microsoft 365 account';
if (identityProviderNamesForContacts($email)) {
$methods['azure'] = 'Only with ' . identityProviderContactsWording($email) . ' - no password';
}
return $methods;
}
@@ -228,7 +232,7 @@ function portalSignInMethods() {
*
* A portal user's authenticator secret is users.user_token, as an agent's is,
* and a browser ticked to be remembered is a remember_tokens row - so sign-in
* (login.php) treats both alike. Microsoft 365 accounts are left to Microsoft.
* (login.php) treats both alike. A sign-in through an identity provider is left to it.
*/
/** How many browsers this user ticked to be remembered, still in date. */
@@ -331,7 +335,7 @@ function portalMailInvite($user_id, $by = '') {
} else {
portalPasswordLinkClear($user_id);
$button = ['label' => 'Sign in', 'url' => "https://$config_base_url/login.php"];
$how = 'Sign in with your Microsoft 365 account - choose Login with Microsoft on the sign-in page.';
$how = 'Sign in with your ' . identityProviderContactsWording($row['user_email']) . ' account - choose its button on the sign-in page.';
$after = 'Questions? Reply to this email.';
}
return (bool) emailQueue([['email' => $row['user_email'], 'name' => $row['contact_name'],

View File

@@ -7,7 +7,7 @@
* it from the client's Contacts (the Invites tab), a primary contact from
* Contacts in the portal. Nobody is a contact until they accept: the link
* opens client/join.php, where they put in their name, title, phone and a
* password (or choose their Microsoft 365 account), and they are made a
* password (or choose an identity provider's account), and they are made a
* contact with portal access - or, when the client already has a contact
* with that address, that contact is given access.
*
@@ -432,7 +432,7 @@ function portalInviteAccept(array $invite, array $in, &$error = '') {
$title = trim(mb_substr((string) ($in['title'] ?? ''), 0, 200));
$phone = substr(preg_replace('/[^0-9]/', '', (string) ($in['phone'] ?? '')), 0, 200);
$method = (string) ($in['method'] ?? 'local');
if (!isset(portalSignInMethods()[$method])) {
if (!isset(portalSignInMethods($email)[$method])) {
$method = 'local';
}
$password = (string) ($in['password'] ?? '');
@@ -501,7 +501,7 @@ function portalInviteAccept(array $invite, array $in, &$error = '') {
WHERE contact_id = $contact_id AND contact_client_id = $client_id");
}
// Their portal account - a password, or their Microsoft 365 account
// Their portal account - a password, or only an identity provider (functions/identity_provider.php)
$hash = escapeSql(password_hash($method === 'local' ? $password : randomString(32), PASSWORD_DEFAULT));
$user_id = intval($who['user_id'] ?? 0);
if ($user_id) {
@@ -804,7 +804,7 @@ function portalMailSignupExists($user_id) {
'kind' => 'Client portal', 'tone' => 'primary', 'preview' => 'Sign in with the account you have',
'title' => "You already have a $company_name client portal account",
'intro' => ["Someone - probably you - tried to sign up for the $company_name client portal with this address, but it has an account already.",
$local ? 'Forgot your password? Choose a new one with the button below.' : 'Sign in with your Microsoft 365 account - choose Login with Microsoft on the sign-in page.'],
$local ? 'Forgot your password? Choose a new one with the button below.' : 'Sign in with your ' . identityProviderContactsWording($row['user_email']) . ' account - choose its button on the sign-in page.'],
'summary' => ['Account' => (string) $row['user_email']],
'button' => $local ? ['label' => 'Set a new password', 'url' => portalPasswordLink($user_id, PORTAL_RESET_LINK_MINUTES)] : ['label' => 'Sign in', 'url' => "https://$config_base_url/login.php"],
'after' => [$local ? 'The link works once, for the next ' . PORTAL_RESET_LINK_MINUTES . ' minutes. If you did not ask, ignore this email - your account stays as it is.' : 'If you did not ask, ignore this email - your account stays as it is.'],

View File

@@ -65,8 +65,6 @@ function settingsPages() {
'about' => 'The sign-in page, two-step sign-in, passkeys, failed sign-ins, API keys and shared links.'],
'client_portal' => ['group' => 'access', 'title' => 'Client Portal', 'icon' => 'fa-user-shield', 'url' => 'settings_client_portal.php', 'module' => 'portal',
'about' => 'How your clients\' contacts sign in to the portal, and the announcements they see there.'],
'identity' => ['group' => 'access', 'title' => 'Single Sign-on', 'icon' => 'fa-fingerprint', 'url' => 'identity_providers.php', 'module' => 'portal',
'about' => 'Contacts signing in to the client portal with their Microsoft 365 account.'],
'module' => ['group' => 'system', 'title' => 'Modules', 'icon' => 'fa-cube', 'url' => 'settings_module.php',
'about' => 'The parts of ITFlow in use - IT documentation, ticketing, invoicing, the calendar, the Knowledge Base and the client portal, and the parts that come with them - and white-labelling.'],
'logs' => ['group' => 'system', 'title' => 'Log Settings', 'icon' => 'fa-scroll', 'url' => 'settings_logs.php', 'under' => 'logs',
@@ -421,10 +419,6 @@ function settingsFields() {
'config_client_portal_require_mfa' => ['page' => 'client_portal', 'section' => 'Signing in', 'label' => 'Require two-step sign-in', 'words' => 'portal mfa 2fa two factor contacts'] + $on_off,
'config_client_portal_signup' => ['page' => 'client_portal', 'section' => 'Signing up', 'label' => 'Let people sign up', 'words' => 'portal sign up register registration self create account domain'] + $on_off,
// Single sign-on
'config_azure_client_id' => ['page' => 'identity', 'section' => 'Microsoft Entra', 'label' => 'Application (client) ID', 'words' => 'sso entra azure microsoft 365 single sign-on portal'],
'config_azure_client_secret' => ['page' => 'identity', 'section' => 'Microsoft Entra', 'label' => 'Client secret', 'kind' => 'secret', 'words' => 'sso entra azure secret'],
// Modules
'config_module_enable_itdoc' => ['page' => 'module', 'section' => 'Modules', 'label' => 'IT documentation', 'words' => 'module itdoc documentation assets credentials'] + $on_off,
'config_module_enable_ticketing' => ['page' => 'module', 'section' => 'Modules', 'label' => 'Ticketing', 'words' => 'module tickets support'] + $on_off,

View File

@@ -7,7 +7,7 @@
* (signInNewIpIds()); and telling the admins about a run of failures from one
* address or against one account (signInWatch()) - how many is Admin >
* Settings > Security (config_login_alert_failures, 0 for never). login.php,
* client/login_microsoft.php and api/v1/validate_api_key.php write it; Admin >
* login_provider.php and api/v1/validate_api_key.php write it; Admin >
* Sign-ins, the audit log and Your account > Activity read it.
*/