@@ -0,0 +1,57 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\Services\DirectorySyncRejected;
|
||||
use App\Services\SyncDirectoryUsers;
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\Cache;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Throwable;
|
||||
|
||||
class SyncActiveDirectory extends Command
|
||||
{
|
||||
protected $signature = 'ad:sync {--dry-run : Preview changes without saving users}
|
||||
{--deactivate-missing : Disable managed users absent from the snapshot}';
|
||||
|
||||
protected $description = 'Synchronize local user records from Active Directory';
|
||||
|
||||
public function handle(SyncDirectoryUsers $sync): int
|
||||
{
|
||||
$context = [
|
||||
'dry_run' => (bool) $this->option('dry-run'),
|
||||
'deactivate_missing' => (bool) $this->option('deactivate-missing'),
|
||||
];
|
||||
|
||||
try {
|
||||
$lock = Cache::lock('ad:sync', 3600);
|
||||
if (! $lock->get()) {
|
||||
throw new DirectorySyncRejected('A directory sync is already running.');
|
||||
}
|
||||
try {
|
||||
$counts = $sync->run($context['dry_run'], $context['deactivate_missing']);
|
||||
} finally {
|
||||
$lock->release();
|
||||
}
|
||||
} catch (DirectorySyncRejected $exception) {
|
||||
Log::warning('Active Directory sync rejected.', $context + ['reason' => $exception->getMessage()]);
|
||||
$this->error($exception->getMessage());
|
||||
|
||||
return self::FAILURE;
|
||||
} catch (Throwable $exception) {
|
||||
Log::error('Active Directory sync failed.', $context + ['exception_type' => $exception::class]);
|
||||
$this->error('Sync stopped due to a directory or database error.');
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
|
||||
Log::info('Active Directory sync completed.', $context + $counts);
|
||||
$summary = [];
|
||||
foreach ($counts as $key => $value) {
|
||||
$summary[] = "$key=$value";
|
||||
}
|
||||
$this->info(($context['dry_run'] ? 'Dry run: ' : '').implode(' ', $summary));
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user