add composer-unused, comprehensive docs, and project restructure
- Add icanhazstring/composer-unused as dev dependency for dependency hygiene checks - Add German documentation (docs/) covering architecture, conventions, workflows, and developer checklists - Add API layer (ApiAuth, ApiBootstrap, ApiResponse), audit, scheduler, custom fields, and SSO services - Add Microsoft OIDC SSO, API token management, and user lifecycle features - Add swagger-ui vendor integration and OpenAPI spec - Add production Docker setup and bin/ scripts - Update composer dependencies, config, templates, and frontend assets throughout Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
262
lib/Service/Auth/SsoUserLinkService.php
Normal file
262
lib/Service/Auth/SsoUserLinkService.php
Normal file
@@ -0,0 +1,262 @@
|
||||
<?php
|
||||
|
||||
namespace MintyPHP\Service\Auth;
|
||||
|
||||
use MintyPHP\Repository\Tenant\UserTenantRepository;
|
||||
use MintyPHP\Repository\User\UserExternalIdentityRepository;
|
||||
use MintyPHP\Repository\User\UserRepository;
|
||||
use MintyPHP\Service\Settings\SettingService;
|
||||
use MintyPHP\Service\User\UserAvatarService;
|
||||
use MintyPHP\Service\User\UserService;
|
||||
|
||||
class SsoUserLinkService
|
||||
{
|
||||
public static function linkOrProvisionMicrosoftUser(array $tenant, array $claims): array
|
||||
{
|
||||
$tenantId = (int) ($tenant['id'] ?? 0);
|
||||
$tid = trim((string) ($claims['tid'] ?? ''));
|
||||
$oid = trim((string) ($claims['oid'] ?? ''));
|
||||
$issuer = trim((string) ($claims['issuer'] ?? ''));
|
||||
$subject = trim((string) ($claims['subject'] ?? ''));
|
||||
$email = strtolower(trim((string) ($claims['email'] ?? '')));
|
||||
|
||||
if ($tenantId <= 0 || $tid === '' || $oid === '' || $issuer === '' || $subject === '') {
|
||||
return ['ok' => false, 'error' => 'identity_invalid'];
|
||||
}
|
||||
|
||||
$identity = UserExternalIdentityRepository::findByProviderTidOid(
|
||||
TenantSsoService::PROVIDER_MICROSOFT,
|
||||
$tid,
|
||||
$oid
|
||||
);
|
||||
if (!$identity) {
|
||||
$identity = UserExternalIdentityRepository::findByProviderIssuerSubject(
|
||||
TenantSsoService::PROVIDER_MICROSOFT,
|
||||
$issuer,
|
||||
$subject
|
||||
);
|
||||
}
|
||||
|
||||
if ($identity) {
|
||||
$userId = (int) ($identity['user_id'] ?? 0);
|
||||
$user = UserRepository::find($userId);
|
||||
if (!$user || empty($user['active'])) {
|
||||
return ['ok' => false, 'error' => 'user_inactive'];
|
||||
}
|
||||
$tenantIds = array_values(array_map('intval', UserTenantRepository::listTenantIdsByUserId($userId)));
|
||||
if (!in_array($tenantId, $tenantIds, true)) {
|
||||
return ['ok' => false, 'error' => 'tenant_not_assigned'];
|
||||
}
|
||||
self::syncProfileFromMicrosoft($userId, $claims);
|
||||
return ['ok' => true, 'user_id' => $userId, 'created' => false];
|
||||
}
|
||||
|
||||
if ($email === '' || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
|
||||
return ['ok' => false, 'error' => 'email_missing'];
|
||||
}
|
||||
|
||||
$user = UserRepository::findByEmail($email);
|
||||
if ($user) {
|
||||
$userId = (int) ($user['id'] ?? 0);
|
||||
if ($userId <= 0 || empty($user['active'])) {
|
||||
return ['ok' => false, 'error' => 'user_inactive'];
|
||||
}
|
||||
|
||||
self::ensureTenantAssignment($userId, $tenantId);
|
||||
self::createIdentityLink($userId, $tid, $oid, $issuer, $subject, $email);
|
||||
self::syncProfileFromMicrosoft($userId, $claims);
|
||||
return ['ok' => true, 'user_id' => $userId, 'created' => false];
|
||||
}
|
||||
|
||||
$firstName = trim((string) ($claims['given_name'] ?? ''));
|
||||
$lastName = trim((string) ($claims['family_name'] ?? ''));
|
||||
$fullName = trim((string) ($claims['name'] ?? ''));
|
||||
if ($firstName === '' && $lastName === '' && $fullName !== '') {
|
||||
$parts = preg_split('/\s+/', $fullName) ?: [];
|
||||
$firstName = (string) ($parts[0] ?? '');
|
||||
$lastName = implode(' ', array_slice($parts, 1));
|
||||
}
|
||||
if ($firstName === '') {
|
||||
$firstName = ucfirst(explode('@', $email, 2)[0]);
|
||||
}
|
||||
|
||||
$createdId = UserRepository::create([
|
||||
'first_name' => $firstName,
|
||||
'last_name' => $lastName,
|
||||
'email' => $email,
|
||||
'password' => self::randomPassword(),
|
||||
'locale' => self::normalizeLocale((string) ($claims['preferred_language'] ?? '')),
|
||||
'totp_secret' => '',
|
||||
'theme' => self::resolveInitialTheme(SettingService::getAppTheme()),
|
||||
'primary_tenant_id' => $tenantId,
|
||||
'current_tenant_id' => $tenantId,
|
||||
'active' => 1,
|
||||
'created_by' => null,
|
||||
'active_changed_at' => gmdate('Y-m-d H:i:s'),
|
||||
'active_changed_by' => null,
|
||||
]);
|
||||
|
||||
if (!$createdId) {
|
||||
return ['ok' => false, 'error' => 'user_create_failed'];
|
||||
}
|
||||
|
||||
$userId = (int) $createdId;
|
||||
UserRepository::setEmailVerified($userId);
|
||||
UserService::syncTenants($userId, [$tenantId]);
|
||||
$defaultRoleId = SettingService::getDefaultRoleId();
|
||||
if ($defaultRoleId) {
|
||||
UserService::syncRoles($userId, [$defaultRoleId]);
|
||||
}
|
||||
$defaultDepartmentId = SettingService::getDefaultDepartmentId();
|
||||
if ($defaultDepartmentId) {
|
||||
UserService::syncDepartments($userId, [$defaultDepartmentId]);
|
||||
}
|
||||
|
||||
self::createIdentityLink($userId, $tid, $oid, $issuer, $subject, $email);
|
||||
self::syncProfileFromMicrosoft($userId, $claims);
|
||||
return ['ok' => true, 'user_id' => $userId, 'created' => true];
|
||||
}
|
||||
|
||||
private static function syncProfileFromMicrosoft(int $userId, array $claims): void
|
||||
{
|
||||
if ($userId <= 0 || empty($claims['sync_profile_on_login'])) {
|
||||
return;
|
||||
}
|
||||
|
||||
$syncFields = TenantSsoService::normalizeProfileSyncFields($claims['sync_profile_fields'] ?? []);
|
||||
if (!$syncFields) {
|
||||
$syncFields = TenantSsoService::defaultProfileSyncFields();
|
||||
}
|
||||
if (!$syncFields) {
|
||||
return;
|
||||
}
|
||||
$syncAvatar = in_array('avatar', $syncFields, true);
|
||||
|
||||
$mappedValues = [
|
||||
'first_name' => trim((string) ($claims['given_name'] ?? '')) !== ''
|
||||
? trim((string) ($claims['given_name'] ?? ''))
|
||||
: trim((string) ($claims['graph_given_name'] ?? '')),
|
||||
'last_name' => trim((string) ($claims['family_name'] ?? '')) !== ''
|
||||
? trim((string) ($claims['family_name'] ?? ''))
|
||||
: trim((string) ($claims['graph_family_name'] ?? '')),
|
||||
'phone' => trim((string) ($claims['graph_phone'] ?? '')),
|
||||
'mobile' => trim((string) ($claims['graph_mobile'] ?? '')),
|
||||
];
|
||||
|
||||
$updates = [];
|
||||
foreach ($syncFields as $field) {
|
||||
if ($field === 'avatar') {
|
||||
continue;
|
||||
}
|
||||
$value = trim((string) ($mappedValues[$field] ?? ''));
|
||||
if ($value === '') {
|
||||
continue;
|
||||
}
|
||||
$updates[$field] = $value;
|
||||
}
|
||||
if (!$updates) {
|
||||
if ($syncAvatar) {
|
||||
self::syncAvatarFromMicrosoft($userId, $claims);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
UserRepository::updateProfileFieldsFromSso($userId, $updates);
|
||||
if ($syncAvatar) {
|
||||
self::syncAvatarFromMicrosoft($userId, $claims);
|
||||
}
|
||||
}
|
||||
|
||||
private static function syncAvatarFromMicrosoft(int $userId, array $claims): void
|
||||
{
|
||||
$avatarBase64 = trim((string) ($claims['graph_avatar_data_base64'] ?? ''));
|
||||
if ($avatarBase64 === '') {
|
||||
return;
|
||||
}
|
||||
|
||||
$avatarMime = strtolower(trim((string) ($claims['graph_avatar_mime'] ?? '')));
|
||||
if (!in_array($avatarMime, ['image/jpeg', 'image/png', 'image/webp'], true)) {
|
||||
return;
|
||||
}
|
||||
|
||||
$binary = base64_decode($avatarBase64, true);
|
||||
if (!is_string($binary) || $binary === '') {
|
||||
return;
|
||||
}
|
||||
|
||||
$user = UserRepository::find($userId);
|
||||
if (!$user) {
|
||||
return;
|
||||
}
|
||||
$userUuid = (string) ($user['uuid'] ?? '');
|
||||
if (!UserAvatarService::isValidUuid($userUuid)) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Keep avatar current with Microsoft profile photo on each login.
|
||||
UserAvatarService::saveBinary($userUuid, $binary, $avatarMime);
|
||||
}
|
||||
|
||||
private static function ensureTenantAssignment(int $userId, int $tenantId): void
|
||||
{
|
||||
$tenantIds = array_values(array_unique(array_map('intval', UserTenantRepository::listTenantIdsByUserId($userId))));
|
||||
if (!in_array($tenantId, $tenantIds, true)) {
|
||||
$tenantIds[] = $tenantId;
|
||||
UserService::syncTenants($userId, $tenantIds);
|
||||
}
|
||||
}
|
||||
|
||||
private static function createIdentityLink(
|
||||
int $userId,
|
||||
string $tid,
|
||||
string $oid,
|
||||
string $issuer,
|
||||
string $subject,
|
||||
string $email
|
||||
): void {
|
||||
try {
|
||||
UserExternalIdentityRepository::createLink([
|
||||
'user_id' => $userId,
|
||||
'provider' => TenantSsoService::PROVIDER_MICROSOFT,
|
||||
'oid' => $oid,
|
||||
'tid' => $tid,
|
||||
'issuer' => $issuer,
|
||||
'subject' => $subject,
|
||||
'email_at_link_time' => $email,
|
||||
]);
|
||||
} catch (\Throwable $exception) {
|
||||
// Ignore duplicate-link race conditions.
|
||||
}
|
||||
}
|
||||
|
||||
private static function normalizeLocale(string $locale): ?string
|
||||
{
|
||||
$locale = strtolower(trim($locale));
|
||||
if ($locale === '') {
|
||||
return null;
|
||||
}
|
||||
if (str_contains($locale, '-')) {
|
||||
$locale = explode('-', $locale, 2)[0];
|
||||
}
|
||||
$allowed = defined('APP_LOCALES') ? APP_LOCALES : [];
|
||||
if ($allowed && !in_array($locale, $allowed, true)) {
|
||||
return null;
|
||||
}
|
||||
return $locale;
|
||||
}
|
||||
|
||||
private static function randomPassword(): string
|
||||
{
|
||||
return 'sso-' . bin2hex(random_bytes(24)) . '-A1!';
|
||||
}
|
||||
|
||||
private static function resolveInitialTheme(?string $theme): string
|
||||
{
|
||||
$theme = strtolower(trim((string) ($theme ?? '')));
|
||||
$themes = function_exists('appThemes') ? appThemes() : ['light' => 'Light'];
|
||||
if ($theme !== '' && isset($themes[$theme])) {
|
||||
return $theme;
|
||||
}
|
||||
return isset($themes['light']) ? 'light' : (string) array_key_first($themes);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user