LdapBridge.php in Lightweight Directory Access Protocol (LDAP) 8.4
File
ldap_servers/src/LdapBridge.php
View source
<?php
declare (strict_types=1);
namespace Drupal\ldap_servers;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\ldap_servers\Entity\Server;
use Drupal\ldap_servers\Helper\CredentialsStorage;
use Psr\Log\LoggerInterface;
use Symfony\Component\Ldap\Exception\ConnectionException;
use Symfony\Component\Ldap\Exception\LdapException;
use Symfony\Component\Ldap\Ldap;
use Symfony\Component\Ldap\LdapInterface;
class LdapBridge implements LdapBridgeInterface {
protected $bindMethod;
protected $bindDn;
protected $bindPw;
protected $ldap;
protected $logger;
protected $entityManager;
public function __construct(LoggerInterface $logger, EntityTypeManagerInterface $entity_type_manager) {
$this->logger = $logger;
$this->entityManager = $entity_type_manager
->getStorage('ldap_server');
}
public function setServerById(string $sid) : void {
$server = $this->entityManager
->load($sid);
if ($server) {
$this
->setServer($server);
}
}
public function setServer(Server $server) : void {
$parameters = [
'host' => $server
->get('address'),
'port' => $server
->get('port'),
'encryption' => $server
->get('encryption'),
'options' => [
'timeout' => $server
->getTimeout(),
'network_timeout' => $server
->getTimeout(),
],
];
$this->bindMethod = $server
->get('bind_method');
$this->bindDn = $server
->get('binddn');
$this->bindPw = $server
->get('bindpw');
$this->ldap = Ldap::create('ext_ldap', $parameters);
}
public function bind() : bool {
if ($this->bindMethod === 'anon' || $this->bindMethod === 'anon_user' && !CredentialsStorage::validateCredentials()) {
$userDn = NULL;
$password = NULL;
}
else {
$userDn = $this->bindDn;
$password = $this->bindPw;
if (CredentialsStorage::validateCredentials()) {
$userDn = CredentialsStorage::getUserDn();
$password = CredentialsStorage::getPassword();
}
if (empty($password) || empty($userDn)) {
$this->logger
->notice('LDAP bind failure due to missing credentials for user userdn=%userdn', [
'%userdn' => $userDn,
]);
return FALSE;
}
}
try {
$this->ldap
->bind($userDn, $password);
} catch (ConnectionException $e) {
$this->logger
->notice('LDAP connection failure: %message.', [
'%message' => $e
->getMessage(),
]);
return FALSE;
} catch (LdapException $e) {
$this->logger
->notice('LDAP bind failure: %message.', [
'%message' => $e
->getMessage(),
]);
return FALSE;
}
return TRUE;
}
public function get() : LdapInterface {
return $this->ldap;
}
}