91 lines
2.8 KiB
PHP
91 lines
2.8 KiB
PHP
<?php
|
|
// auth/ldap.php
|
|
|
|
/**
|
|
* LDAP-authenticatie voor Samba AD.
|
|
* Retourneert gebruikersinfo bij succes of false bij mislukking.
|
|
*/
|
|
function ldap_authenticate($username, $password)
|
|
{
|
|
$config = require __DIR__ . '/../config/config.php';
|
|
$ldap_conf = $config['ldap'];
|
|
|
|
if (empty($username) || empty($password)) {
|
|
return false;
|
|
}
|
|
|
|
// Verbinden met Samba AD LDAP
|
|
$ldapconn = ldap_connect($ldap_conf['server'], $ldap_conf['port']);
|
|
if (!$ldapconn) {
|
|
error_log("LDAP: geen verbinding met {$ldap_conf['server']}");
|
|
return false;
|
|
}
|
|
|
|
ldap_set_option($ldapconn, LDAP_OPT_PROTOCOL_VERSION, 3);
|
|
ldap_set_option($ldapconn, LDAP_OPT_REFERRALS, 0);
|
|
|
|
// StartTLS indien geconfigureerd
|
|
if (!empty($ldap_conf['use_tls']) && $ldap_conf['use_tls']) {
|
|
if (!ldap_start_tls($ldapconn)) {
|
|
error_log("LDAP: TLS-verbinding mislukt");
|
|
ldap_close($ldapconn);
|
|
return false;
|
|
}
|
|
}
|
|
|
|
// Probeer eerst directe bind via userPrincipalName (AD-stijl)
|
|
$userPrincipalName = (str_contains($username, '@')) ? $username : "{$username}@de-roo.local";
|
|
$bind = @ldap_bind($ldapconn, $userPrincipalName, $password);
|
|
|
|
// Als directe bind lukt → zoek user info
|
|
if ($bind) {
|
|
$filter = "(sAMAccountName={$username})";
|
|
} else {
|
|
// Fallback: bind met admin en zoek de DN van gebruiker
|
|
if (!@ldap_bind($ldapconn, $ldap_conf['admin_user'], $ldap_conf['admin_pass'])) {
|
|
ldap_unbind($ldapconn);
|
|
return false;
|
|
}
|
|
|
|
$filter = "(|(sAMAccountName={$username})(userPrincipalName={$userPrincipalName}))";
|
|
}
|
|
|
|
$attrs = ['sAMAccountName', 'givenName', 'sn', 'mail', 'userPrincipalName', 'displayName', 'dn'];
|
|
$result = ldap_search($ldapconn, $ldap_conf['base_dn'], $filter, $attrs);
|
|
|
|
if (!$result) {
|
|
ldap_unbind($ldapconn);
|
|
return false;
|
|
}
|
|
|
|
$entries = ldap_get_entries($ldapconn, $result);
|
|
if ($entries['count'] === 0) {
|
|
ldap_unbind($ldapconn);
|
|
return false;
|
|
}
|
|
|
|
$entry = $entries[0];
|
|
|
|
// Als we nog niet met de user zelf gebind zijn, doe dat nu
|
|
if (!$bind) {
|
|
$user_dn = $entry['dn'];
|
|
if (!@ldap_bind($ldapconn, $user_dn, $password)) {
|
|
ldap_unbind($ldapconn);
|
|
return false;
|
|
}
|
|
}
|
|
|
|
// Gebruikersinfo samenstellen
|
|
$userData = [
|
|
'username' => $entry['samaccountname'][0] ?? $username,
|
|
'givenName' => $entry['givenname'][0] ?? '',
|
|
'sn' => $entry['sn'][0] ?? '',
|
|
'email' => $entry['mail'][0] ?? '',
|
|
'displayName' => $entry['displayname'][0] ?? ($entry['givenname'][0] ?? '') . ' ' . ($entry['sn'][0] ?? ''),
|
|
'userPrincipalName' => $entry['userprincipalname'][0] ?? $userPrincipalName
|
|
];
|
|
|
|
ldap_unbind($ldapconn);
|
|
return $userData;
|
|
}
|