<?php
namespace App\Infraestructure\Security;
use App\Domain\Entity\SonataUserUser;
use App\Infraestructure\Persistence\Doctrine\Repository\SonataUserUserRepository;
use Symfony\Component\Ldap\Entry;
use Symfony\Component\Ldap\Exception\ConnectionException;
use Symfony\Component\Ldap\LdapInterface;
use Symfony\Component\Ldap\Security\LdapUserProvider;
use Symfony\Component\Security\Core\Exception\UnsupportedUserException;
use Symfony\Component\Security\Core\Exception\UserNotFoundException;
use Symfony\Component\Security\Core\User\UserInterface;
class LdapNewUserProvider extends LdapUserProvider
{
public function __construct(
LdapInterface $ldap,
private SonataUserUserRepository $sonataUserUserRepository,
string $baseDn,
string $searchDn = null,
string $searchPassword = '',
string $defaultRoles,
string $uidKey = null,
string $filter = null,
string $passwordAttribute = null,
array $extraFields = []
) {
parent::__construct(
$ldap,
$baseDn,
$searchDn,
$searchPassword,
unserialize($defaultRoles),
$uidKey,
$filter,
$passwordAttribute,
$extraFields
);
}
public function refreshUser(UserInterface $user)
{
if (!$this->supportsClass(get_class($user))) {
throw new UnsupportedUserException(sprintf('Instances of "%s" are not supported.', get_debug_type($user)));
}
$reloadUser = $this->sonataUserUserRepository->findOneByUsername($user->getUsername());
return $reloadUser;
}
public function supportsClass(string $class)
{
return SonataUserUser::class === $class;
}
protected function loadUser(string $identifier, Entry $entry)
{
$usuario = $this->sonataUserUserRepository->findOneByUsername($identifier);
if (!$usuario) {
try {
$ldapEntry = $this->loadLdapUser($identifier);
$usuario = new SonataUserUser();
$usuario->setUsername($identifier);
$usuario->setEmail($ldapEntry->getAttribute('mail')[0] ?? '');
$usuario->setRoles($this->defaultRoles);
$usuario->setEnabled(true);
$usuario->setPassword(md5(time()));
$this->sonataUserUserRepository->save($usuario);
} catch (ConnectionException $e) {
throw new UserNotFoundException(sprintf('User "%s" not found in LDAP.', $identifier));
}
}
return $usuario;
}
private function loadLdapUser(string $identifier): Entry
{
$query = $this->ldap->query($this->baseDn, sprintf('(%s=%s)', $this->uidKey, $identifier));
$results = $query->execute();
if (count($results) === 0) {
throw new UserNotFoundException(sprintf('User "%s" not found in LDAP.', $identifier));
}
return $results[0];
}
}//class