@@ -0,0 +1,83 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use LdapRecord\LdapInterface;
|
||||
use LdapRecord\Models\ActiveDirectory\User;
|
||||
use RuntimeException;
|
||||
|
||||
class ActiveDirectory
|
||||
{
|
||||
private const ATTRIBUTES = ['objectguid', 'mail', 'displayname', 'cn', 'useraccountcontrol'];
|
||||
|
||||
public static function baseDn(): string
|
||||
{
|
||||
$connection = config('ldap.default');
|
||||
|
||||
return trim((string) (config('ad-sync.base-dn') ?: config("ldap.connections.{$connection}.base_dn")));
|
||||
}
|
||||
|
||||
/** @return list<array{guid: ?string, email: string, name: string, enabled: bool}> */
|
||||
public function users(): array
|
||||
{
|
||||
$baseDn = self::baseDn();
|
||||
if ($baseDn === '') {
|
||||
throw new RuntimeException('An LDAP search base is required.');
|
||||
}
|
||||
|
||||
return User::resolveConnection(config('ldap.default'))->run(function (LdapInterface $ldap) use ($baseDn): array {
|
||||
$entries = [];
|
||||
$cookie = '';
|
||||
|
||||
do {
|
||||
$result = $ldap->search($baseDn, '(&(objectCategory=person)(objectClass=user))', self::ATTRIBUTES, controls: [[
|
||||
'oid' => LDAP_CONTROL_PAGEDRESULTS,
|
||||
'iscritical' => true,
|
||||
'value' => ['size' => 500, 'cookie' => $cookie],
|
||||
]]);
|
||||
|
||||
try {
|
||||
$response = $ldap->parseResult($result);
|
||||
$next = $response ? ($response->controls[LDAP_CONTROL_PAGEDRESULTS]['value']['cookie'] ?? null) : null;
|
||||
if (! $response || $response->failed() || $response->referrals || ! is_string($next)) {
|
||||
throw new RuntimeException('LDAP returned an incomplete page.');
|
||||
}
|
||||
|
||||
$page = $ldap->getEntries($result);
|
||||
$count = $page['count'] ?? null;
|
||||
if (! is_int($count) || $count !== count($page) - 1 || ($count === 0 && $next !== '')) {
|
||||
throw new RuntimeException('LDAP returned invalid page entries.');
|
||||
}
|
||||
|
||||
for ($index = 0; $index < $count; $index++) {
|
||||
$entries[] = $this->entry((new User)->setRawAttributes($page[$index]));
|
||||
}
|
||||
|
||||
$cookie = $next;
|
||||
} finally {
|
||||
$ldap->freeResult($result);
|
||||
}
|
||||
} while ($cookie !== '');
|
||||
|
||||
return $entries;
|
||||
});
|
||||
}
|
||||
|
||||
/** @return array{guid: ?string, email: string, name: string, enabled: bool} */
|
||||
private function entry(User $user): array
|
||||
{
|
||||
$flags = filter_var($user->getFirstAttribute('useraccountcontrol'), FILTER_VALIDATE_INT, [
|
||||
'options' => ['min_range' => 0],
|
||||
]);
|
||||
if ($flags === false) {
|
||||
throw new RuntimeException('Missing or invalid userAccountControl.');
|
||||
}
|
||||
|
||||
return [
|
||||
'guid' => $user->getConvertedGuid(),
|
||||
'email' => (string) $user->getFirstAttribute('mail'),
|
||||
'name' => (string) ($user->getFirstAttribute('displayname') ?: $user->getFirstAttribute('cn')),
|
||||
'enabled' => ($flags & 2) === 0,
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use RuntimeException;
|
||||
|
||||
class DirectorySyncRejected extends RuntimeException {}
|
||||
@@ -0,0 +1,131 @@
|
||||
<?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{created: int, updated: int, unchanged: int, deactivated: int, reactivated: int} */
|
||||
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) {
|
||||
$counts['created']++;
|
||||
$user->ad_disabled_at = $entry['enabled'] ? null : now();
|
||||
} elseif (! $entry['enabled'] && $user->ad_disabled_at === null) {
|
||||
$counts['deactivated']++;
|
||||
$this->disable($user);
|
||||
} elseif ($entry['enabled'] && $user->ad_disabled_at !== null) {
|
||||
$counts['reactivated']++;
|
||||
$user->ad_disabled_at = null;
|
||||
} elseif ($user->isDirty()) {
|
||||
$counts['updated']++;
|
||||
} else {
|
||||
$counts['unchanged']++;
|
||||
}
|
||||
|
||||
if ($user->isDirty()) {
|
||||
$changes[] = $user;
|
||||
}
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if ($counts['deactivated'] > config('ad-sync.max-deactivations')) {
|
||||
throw new DirectorySyncRejected('Deactivation limit exceeded.');
|
||||
}
|
||||
|
||||
if (! $dryRun) {
|
||||
foreach ($changes as $user) {
|
||||
if (! $user->exists) {
|
||||
$user->password = Str::random(64);
|
||||
}
|
||||
$user->save();
|
||||
}
|
||||
}
|
||||
|
||||
return $counts;
|
||||
}, 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;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user