updates for active directory
tests / ci (push) Canceled after 0s

This commit is contained in:
Mark Gregory
2026-11-11 16:19:50 +00:00
parent 65d58f19dc
commit c15221c98f
14 changed files with 592 additions and 2 deletions
+83
View File
@@ -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,
];
}
}