154 lines
6.1 KiB
PHP
154 lines
6.1 KiB
PHP
<?php
|
|
|
|
namespace App\Services;
|
|
|
|
use App\Models\User;
|
|
use Illuminate\Support\Facades\DB;
|
|
use Illuminate\Support\Str;
|
|
|
|
class SyncDirectoryUsers
|
|
{
|
|
public function __construct(private ActiveDirectory $directory) {}
|
|
|
|
/**
|
|
* @return array{
|
|
* counts: array{created: int, updated: int, unchanged: int, deactivated: int, reactivated: int},
|
|
* changes: list<array{action: string, user_id: ?int, ad_guid: ?string, disabled: bool, changed_fields: list<string>, reason: ?string}>
|
|
* }
|
|
*/
|
|
public function run(bool $dryRun, bool $deactivateMissing): array
|
|
{
|
|
$entries = $this->snapshot();
|
|
$source = $this->source();
|
|
|
|
return DB::transaction(function () use ($entries, $source, $dryRun, $deactivateMissing): array {
|
|
$counts = ['created' => 0, 'updated' => 0, 'unchanged' => 0, 'deactivated' => 0, 'reactivated' => 0];
|
|
$changes = [];
|
|
|
|
foreach ($entries as $guid => $entry) {
|
|
$user = User::where('ad_guid', $guid)->lockForUpdate()->first();
|
|
if ($user && $user->ad_source !== $source) {
|
|
throw new DirectorySyncRejected('GUID belongs to another directory scope.');
|
|
}
|
|
|
|
$owners = User::whereRaw('LOWER(email) = ?', [$entry['email']])->lockForUpdate()->get(['id']);
|
|
if ($owners->contains(fn (User $owner): bool => $owner->id !== $user?->id)) {
|
|
throw new DirectorySyncRejected('Local email collision.');
|
|
}
|
|
|
|
$user ??= new User;
|
|
$user->forceFill(['ad_guid' => $guid, 'ad_source' => $source, 'name' => $entry['name']]);
|
|
if ($user->email !== $entry['email']) {
|
|
$user->forceFill(['email' => $entry['email'], 'email_verified_at' => null]);
|
|
}
|
|
|
|
if (! $user->exists) {
|
|
$action = 'created';
|
|
$user->ad_disabled_at = $entry['enabled'] ? null : now();
|
|
} elseif (! $entry['enabled'] && $user->ad_disabled_at === null) {
|
|
$action = 'deactivated';
|
|
$this->disable($user);
|
|
} elseif ($entry['enabled'] && $user->ad_disabled_at !== null) {
|
|
$action = 'reactivated';
|
|
$user->ad_disabled_at = null;
|
|
} elseif ($user->isDirty()) {
|
|
$action = 'updated';
|
|
} else {
|
|
$action = 'unchanged';
|
|
}
|
|
|
|
$counts[$action]++;
|
|
if ($action !== 'unchanged') {
|
|
$reason = match (true) {
|
|
! $entry['enabled'] && in_array($action, ['created', 'deactivated'], true) => 'directory_disabled',
|
|
$action === 'reactivated' => 'directory_enabled',
|
|
default => null,
|
|
};
|
|
$changes[] = [$user, $action, $reason];
|
|
}
|
|
}
|
|
|
|
if ($deactivateMissing) {
|
|
$missing = User::where('ad_source', $source)->whereNotNull('ad_guid')
|
|
->whereNull('ad_disabled_at')->lockForUpdate()->get();
|
|
foreach ($missing as $user) {
|
|
if (! isset($entries[$user->ad_guid])) {
|
|
$counts['deactivated']++;
|
|
$this->disable($user);
|
|
$changes[] = [$user, 'deactivated', 'missing_from_snapshot'];
|
|
}
|
|
}
|
|
}
|
|
|
|
if ($counts['deactivated'] > config('ad-sync.max-deactivations')) {
|
|
throw new DirectorySyncRejected('Deactivation limit exceeded.');
|
|
}
|
|
|
|
$audit = [];
|
|
foreach ($changes as [$user, $action, $reason]) {
|
|
$fields = array_values(array_intersect(['name', 'email', 'email_verified_at', 'ad_disabled_at'], array_keys($user->getDirty())));
|
|
if (! $dryRun) {
|
|
if (! $user->exists) {
|
|
$user->password = Str::random(64);
|
|
}
|
|
$user->save();
|
|
}
|
|
|
|
$audit[] = [
|
|
'action' => $action,
|
|
'user_id' => $user->exists ? $user->id : null,
|
|
'ad_guid' => $user->ad_guid,
|
|
'disabled' => $user->ad_disabled_at !== null,
|
|
'changed_fields' => $fields,
|
|
'reason' => $reason,
|
|
];
|
|
}
|
|
|
|
return ['counts' => $counts, 'changes' => $audit];
|
|
}, attempts: 3);
|
|
}
|
|
|
|
private function disable(User $user): void
|
|
{
|
|
$user->forceFill(['ad_disabled_at' => now(), 'remember_token' => null]);
|
|
}
|
|
|
|
private function source(): string
|
|
{
|
|
$connection = config('ldap.default');
|
|
$base = ActiveDirectory::baseDn();
|
|
|
|
return hash('sha256', strtolower("{$connection}:$base"));
|
|
}
|
|
|
|
/** @return array<string, array{email: string, name: string, enabled: bool}> */
|
|
private function snapshot(): array
|
|
{
|
|
$entries = [];
|
|
$emails = [];
|
|
foreach ($this->directory->users() as $entry) {
|
|
$guid = strtolower((string) $entry['guid']);
|
|
$email = strtolower(trim($entry['email']));
|
|
$name = trim($entry['name']);
|
|
if (! Str::isUuid($guid) || $guid === '00000000-0000-0000-0000-000000000000'
|
|
|| strlen($email) > 255 || ! filter_var($email, FILTER_VALIDATE_EMAIL)
|
|
|| $name === '' || mb_strlen($name) > 255) {
|
|
throw new DirectorySyncRejected('Invalid GUID, email or name in directory snapshot.');
|
|
}
|
|
|
|
if (isset($entries[$guid]) || isset($emails[$email])) {
|
|
throw new DirectorySyncRejected('Duplicate GUID or email in directory snapshot.');
|
|
}
|
|
|
|
$emails[$email] = true;
|
|
$entries[$guid] = ['email' => $email, 'name' => $name, 'enabled' => $entry['enabled']];
|
|
}
|
|
|
|
if ($entries === []) {
|
|
throw new DirectorySyncRejected('Directory snapshot is empty.');
|
|
}
|
|
|
|
return $entries;
|
|
}
|
|
}
|