87 lines
3.3 KiB
PHP
87 lines
3.3 KiB
PHP
<?php
|
|
|
|
namespace Modules\ActiveDirectory\Services;
|
|
|
|
use LdapRecord\LdapInterface;
|
|
use LdapRecord\Models\ActiveDirectory\User;
|
|
use Modules\ActiveDirectory\Constants\AccountControl;
|
|
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 & AccountControl::ACCOUNTDISABLE) === 0,
|
|
'account_control' => $flags,
|
|
'account_flags' => AccountControl::flags($flags),
|
|
];
|
|
}
|
|
}
|