Commit c534a9c6 authored by Jean-Philippe Metivier's avatar Jean-Philippe Metivier
Browse files

Clean

parent 86ea1799
Loading
Loading
Loading
Loading
+150 −209
Original line number Diff line number Diff line
@@ -3,8 +3,14 @@
namespace UnicaenUtilisateur\Service\User;

use Doctrine\ORM\EntityRepository;
use Doctrine\ORM\Exception\NotSupported;
use Doctrine\ORM\Exception\ORMException;
use Exception;
use InvalidArgumentException;
use Laminas\Authentication\AuthenticationService;
use Laminas\Crypt\Password\Bcrypt;
use Laminas\Mvc\Controller\AbstractActionController;
use Laminas\View\Renderer\PhpRenderer;
use Ramsey\Uuid\Uuid;
use UnicaenApp\Entity\Ldap\People;
use UnicaenApp\Service\EntityManagerAwareTrait;
@@ -19,9 +25,6 @@ use UnicaenUtilisateur\Exception\RuntimeException;
use UnicaenUtilisateur\Service\RechercheIndividu\RechercheIndividuResultatInterface;
use UnicaenUtilisateur\Service\RechercheIndividu\RechercheIndividuServiceInterface;
use UnicaenUtilisateur\Service\Role\RoleServiceAwareTrait;
use Laminas\Authentication\AuthenticationService;
use Laminas\Crypt\Password\Bcrypt;
use Laminas\Mvc\Controller\AbstractActionController;

class UserService implements RechercheIndividuServiceInterface
{
@@ -32,6 +35,10 @@ class UserService implements RechercheIndividuServiceInterface

    private ?string $userEntityClass = null;
    private ?array $authentificationConfig = null;
    private ?int $passwordCost = null;
    private ?PhpRenderer $renderer = null;
    private ?string $appname = null;
    private ?AuthenticationService $authenticationService = null;

    public function getAuthentificationConfig(): ?array
    {
@@ -43,18 +50,16 @@ class UserService implements RechercheIndividuServiceInterface
        $this->authentificationConfig = $authentificationConfig;
    }

    private ?AuthenticationService $authenticationService;

    private $renderer;
    public function setRenderer($renderer) { $this->renderer = $renderer;}
    private ?string $appname = null;
    public function setAppname($appname) { $this->appname = $appname;}
    public function setRenderer(?PhpRenderer $renderer): void
    {
        $this->renderer = $renderer;
    }

    public function setAppname(?string $appname): void
    {
        $this->appname = $appname;
    }

    /**
     * @param string $userEntityClass
     * @return void
     */
    public function setUserEntityClass(string $userEntityClass): void
    {
        if (!class_exists($userEntityClass) || !in_array(UserInterface::class, class_implements($userEntityClass))) {
@@ -63,29 +68,17 @@ class UserService implements RechercheIndividuServiceInterface
        $this->userEntityClass = $userEntityClass;
    }

    /**
     * @return string
     */
    public function getEntityClass(): ?string
    {
        return $this->userEntityClass;
    }

    /**
     * Retourne une nouvelle instance de l'entité lié au service
     *
     * @return UserInterface
     */
    public function getEntityInstance(): UserInterface
    {
        return new $this->userEntityClass;
    }

    /**
     * @param AuthenticationService $authenticationService
     * @return void
     */
    public function setAuthenticationService(AuthenticationService $authenticationService)
    public function setAuthenticationService(AuthenticationService $authenticationService): void
    {
        $this->authenticationService = $authenticationService;
    }
@@ -95,56 +88,78 @@ class UserService implements RechercheIndividuServiceInterface
        return $this->authenticationService;
    }

    public function getRepo(): EntityRepository
    {
        try {
            return $this->getEntityManager()->getRepository($this->userEntityClass);
        } catch (NotSupported $e) {
            throw new RuntimeException("Une erreur s'est produite lors de la récupération du repository [".$this->userEntityClass."]",0,$e);
        }
    }

    /** Gestion des entités  ******************************************************************************************/

    /**
     * @return EntityRepository
     */
    public function getRepo()
    public function create(UserInterface $user): UserInterface
    {
        return $this->getEntityManager()->getRepository($this->userEntityClass);
        try {
            $this->getEntityManager()->persist($user);
            $this->getEntityManager()->flush($user);
        } catch (ORMException $e) {
            throw new RuntimeException("Un problème est survenu lors de la création de l'utilisateur.", null, $e);
        }
        return $user;
    }

    /**
     * @param mixed $id
     * @return UserInterface|null
     * @param UserInterface $utilisateur
     * @return UserInterface
     */
    public function find($id)
    public function update(UserInterface $utilisateur): UserInterface
    {
        try {
            $this->getEntityManager()->flush($utilisateur);
        } catch (ORMException $e) {
            throw new RuntimeException("Un problème est survenu lors de la mise à jour de l'utilisateur " . $utilisateur->getUsername() . ".", null, $e);
        }
        return $utilisateur;
    }

    public function delete(UserInterface $utilisateur): UserInterface
    {
        try {
            $this->getEntityManager()->remove($utilisateur);
            $this->getEntityManager()->flush();
        } catch (ORMException $e) {
            throw new RuntimeException("Un problème est survenu lors de la suppression de l'utilisateur " . $utilisateur->getUsername() . ".", null, $e);
        }
        return $utilisateur;
    }

    /** Requetage *****************************************************************************************************/

    public function find(mixed $id): ?UserInterface
    {
        return $this->getRepo()->find($id);
    }

    /**
     * @return UserInterface[]
     */
    public function findAll(array $orderBy = ['displayName' => 'ASC'])
    /** @return UserInterface[] */
    public function findAll(array $orderBy = ['displayName' => 'ASC']): array
    {
        return $this->getRepo()->findBy([], $orderBy);
    }

    /**
     * @param string $username
     * @return UserInterface|null
     */
    public function findByUsername($username)
    public function findByUsername(string $username): ?UserInterface
    {
        return $this->getRepo()->findOneBy(['username' => $username]);
    }

    /**
     * @param $id
     * @return UserInterface
     */
    public function findById($id)
    public function findById(mixed $id): ?UserInterface
    {
        return $this->find($id);
    }

    /**
     * @param string $texte
     * @return UserInterface[]
     */
    public function findByTerm(string $texte)
    /** @return UserInterface[] * */
    public function findByTerm(string $term): array
    {
        $qb = $this->getRepo()->createQueryBuilder("u");
        $qb->andWhere(
@@ -153,7 +168,7 @@ class UserService implements RechercheIndividuServiceInterface
                "LOWER(u.username) LIKE :term"
            )
        )
            ->setParameter("term", '%' . strtolower($texte) . '%')
            ->setParameter("term", '%' . strtolower($term) . '%')
            ->orderBy("u.displayName");

        $utilisateurs = $qb->getQuery()->getResult();
@@ -161,12 +176,8 @@ class UserService implements RechercheIndividuServiceInterface
        return $utilisateurs;
    }

    /**
     * @param string $texte
     * @param string $roleId
     * @return UserInterface[]
     */
    public function findByTermAndRole(string $texte, string $roleId)
    /** @return UserInterface[] */
    public function findByTermAndRole(string $texte, string $roleId): array
    {
        $texte = strtolower($texte);
        $qb = $this->getRepo()->createQueryBuilder("u")
@@ -182,24 +193,7 @@ class UserService implements RechercheIndividuServiceInterface
        return $utilisateurs;
    }

    /**
     * @param RechercheIndividuResultatInterface $individu
     * @param string $source
     * @return UserInterface
     */
    public function importFromRechercheIndividuResultatInterface(RechercheIndividuResultatInterface $individu, $source)
    {
        $attribut = $this->getAuthentificationConfig()['local']['ldap']['username'];

        $utilisateur = $this->getEntityInstance();
        $utilisateur->setDisplayName($individu->getDisplayname());
        $utilisateur->setUsername($individu->getUsername($attribut));
        $utilisateur->setEmail($individu->getEmail());
        $utilisateur->setPassword($source);
        $utilisateur->setState(1);

        return $utilisateur;
    }

    public function getRequestedUser(AbstractActionController $controller, string $paramName = 'utilisateur'): ?UserInterface
    {
@@ -210,30 +204,54 @@ class UserService implements RechercheIndividuServiceInterface
        return $user;
    }

    /**
     * @param UserInterface $user
     * @return UserInterface
     */
    public function create(UserInterface $user)
    /** @return UserInterface[] */
    public function findByRole(RoleInterface $role): array
    {
        try {
            $this->getEntityManager()->persist($user);
            $this->getEntityManager()->flush($user);
        } catch (ORMException $e) {
            throw new RuntimeException("Un problème est survenu lors de la création de l'utilisateur.", null, $e);
        $qb = $this->getRepo()->createQueryBuilder('u')
            ->addSelect('r')->join('u.roles', 'r')
            ->andWhere('r.roleId = :role')
            ->setParameter('role', $role->getRoleId());

        return $qb->getQuery()->getResult();
    }
        return $user;

    /** @return AbstractUser[] */
    public function getUtilisateursByTermAndRoleId(string $term, string $roleCode): array
    {
        $qb = $this->getRepo()->createQueryBuilder('u')
            ->addSelect('r')->join('u.roles', 'r')
            ->andWhere('r.roleId like :role')->setParameter('role', '%' . $roleCode . '%')
            ->andWhere('LOWER(u.displayName) like :term')->setParameter('term', '%' . strtolower($term) . '%');

        return $qb->getQuery()->getResult();
    }

    /**
     * @param UserInterface $user
     * @return UserInterface
     */
    public function createLocal(UserInterface $user)
    /** FACADE  *******************************************************************************************************/

    public function importFromRechercheIndividuResultatInterface(RechercheIndividuResultatInterface $individu, string $source): UserInterface
    {
        $attribut = $this->getAuthentificationConfig()['local']['ldap']['username'];

        $utilisateur = $this->getEntityInstance();
        $utilisateur->setDisplayName($individu->getDisplayname());
        $utilisateur->setUsername($individu->getUsername($attribut));
        $utilisateur->setEmail($individu->getEmail());
        $utilisateur->setPassword($source);
        $utilisateur->setState(1);

        return $utilisateur;
    }

    public function createLocal(UserInterface $user): UserInterface
    {
        $user->setState(1);
        $user->setPassword('db');
        try {
            $token = Uuid::uuid4()->toString();
        } catch (Exception $e) {
            throw new RuntimeException("Une erreur s'est produite lors de la génération du token.", null, $e);

        }
        $user->setPasswordResetToken($token);
        $this->create($user);

@@ -242,8 +260,7 @@ class UserService implements RechercheIndividuServiceInterface
        /** @see UtilisateurController::changerMotDePasseAction() */
        $url = $this->renderer->url('unicaen-utilisateur/changer-mot-de-passe', ['user' => $user->getId(), 'token' => $user->getPasswordResetToken()], ['force_canonical' => true], true);
        $subject = "Initialisation de votre compte pour l'application" . $appname;
        $body="";
        $body.="<p>Bonjour ".$user->getDisplayName().",</p>";
        $body  = "<p>Bonjour " . $user->getDisplayName() . ",</p>";
        $body .= "<p>Pour initialiser votre mot de passe pour l'application " . $appname . " veuillez suivre le lien suivant <a href='" . $url . "'>" . $url . "</a>.</p>";
        $body .= "<p>Vous aurez besoin de votre identifiant qui est <strong>" . $user->getUsername() . "</strong></p>";
        $this->getMailService()->sendMail($user->getEmail(), $subject, $body);
@@ -251,13 +268,11 @@ class UserService implements RechercheIndividuServiceInterface
        return $user;
    }

    /**
     * @param int|null $passwordCost
     */
    public function setPasswordCost(?int $passwordCost): void
    {
        $this->passwordCost = $passwordCost;
    }

    public function changerPassword(User $user, $data): User
    {
        $password = $data['password1'];
@@ -273,25 +288,7 @@ class UserService implements RechercheIndividuServiceInterface
        return $user;
    }

    /**
     * @param UserInterface $utilisateur
     * @return UserInterface
     */
    public function update(UserInterface $utilisateur)
    {
        try {
            $this->getEntityManager()->flush($utilisateur);
        } catch (ORMException $e) {
            throw new RuntimeException("Un problème est survenu lors de la mise à jour de l'utilisateur " . $utilisateur->getUsername() . ".", null, $e);
        }
        return $utilisateur;
    }

    /**
     * @param UserInterface $utilisateur
     * @return UserInterface
     */
    public function changeStatus(UserInterface $utilisateur)
    public function changeStatus(UserInterface $utilisateur): UserInterface
    {
        $status = $utilisateur->getState();
        $utilisateur->setState($status == 1 ? 0 : 1);
@@ -305,12 +302,7 @@ class UserService implements RechercheIndividuServiceInterface
        return $utilisateur;
    }

    /**
     * @param UserInterface $utilisateur
     * @param RoleInterface $role
     * @return UserInterface
     */
    public function addRole(UserInterface $utilisateur, RoleInterface $role)
    public function addRole(UserInterface $utilisateur, RoleInterface $role): UserInterface
    {
        $utilisateur->addRole($role);

@@ -323,12 +315,7 @@ class UserService implements RechercheIndividuServiceInterface
        return $utilisateur;
    }

    /**
     * @param UserInterface $utilisateur
     * @param RoleInterface $role
     * @return UserInterface
     */
    public function removeRole(UserInterface $utilisateur, RoleInterface $role)
    public function removeRole(UserInterface $utilisateur, RoleInterface $role): UserInterface
    {
        $utilisateur->removeRole($role);

@@ -341,33 +328,6 @@ class UserService implements RechercheIndividuServiceInterface
        return $utilisateur;
    }

    /**
     * @param UserInterface $utilisateur
     */
    public function delete(UserInterface $utilisateur)
    {
        try {
            $this->getEntityManager()->remove($utilisateur);
            $this->getEntityManager()->flush();
        } catch (ORMException $e) {
            throw new RuntimeException("Un problème est survenu lors de la suppression de l'utilisateur " . $utilisateur->getUsername() . ".", null, $e);
        }
    }

    /**
     * @param RoleInterface $role
     * @return UserInterface[]
     */
    public function findByRole(RoleInterface $role)
    {
        $qb = $this->getRepo()->createQueryBuilder('u')
            ->addSelect('r')->join('u.roles', 'r')
            ->andWhere('r.roleId = :role')
            ->setParameter('role', $role->getRoleId());

        return $qb->getQuery()->getResult();
    }

    public function getConnectedUser(): ?UserInterface
    {
        $identity = $this->authenticationService->getIdentity();
@@ -376,16 +336,11 @@ class UserService implements RechercheIndividuServiceInterface
            if (isset($identity['ldap'])) {
                /** @var People $userIdentity */
                $userIdentity = $identity['ldap'];
                switch ($this->getAuthentificationConfig()['local']['ldap']['username']) {
                    case 'uid' :
                        $username = $userIdentity->getUid();
                        break;
                    case 'supannaliaslogin' :
                        $username = $userIdentity->getSupannAliasLogin();
                        break;
                    default :
                        throw new RuntimeException("La clef de config [unicaen-auth][loca][ldap][username] n'est pas défini ou à une valeur non attendue.");
                }
                $username = match ($this->getAuthentificationConfig()['local']['ldap']['username']) {
                    'uid' => $userIdentity->getUid(),
                    'supannaliaslogin' => $userIdentity->getSupannAliasLogin(),
                    default => throw new RuntimeException("La clef de config [unicaen-auth][loca][ldap][username] n'est pas défini ou à une valeur non attendue."),
                };

                $user = $this->findByUsername($username);

@@ -413,24 +368,19 @@ class UserService implements RechercheIndividuServiceInterface
    public function getConnectedRole()
    {
        $dbRole = $this->serviceUserContext->getSelectedIdentityRole();

        return $dbRole;
    }

    /**
     * @param $string
     * @return array
     */
    public function getUtilisateursByRoleIdAsOptions($string)
     /** @return UserInterface[] **/
    public function getUtilisateursByRoleIdAsOptions(?string $roleId = null): array
    {
        $role = $this->roleService->findByRoleId($string);
        $role = $this->roleService->findByRoleId($roleId);
        $users = $this->findByRole($role);

        $array = [];
        foreach ($users as $user) {
            $array[$user->getId()] = $user->getDisplayName();
        }

        return $array;
    }

@@ -438,7 +388,7 @@ class UserService implements RechercheIndividuServiceInterface
     * @param UserInterface[] $users
     * @return array
     */
    public function formatUserJSON($users)
    public function formatUserJSON(array $users): array
    {
        $result = [];

@@ -470,15 +420,6 @@ class UserService implements RechercheIndividuServiceInterface
        return $maximum;
    }

    /** @return AbstractUser[] */
    public function getUtilisateursByTermAndRoleId(string $term, string $roleCode) : array
    {
        $qb = $this->getRepo()->createQueryBuilder('u')
            ->addSelect('r')->join('u.roles', 'r')
            ->andWhere('r.roleId like :role')->setParameter('role', '%'.$roleCode.'%')
            ->andWhere('LOWER(u.displayName) like :term')->setParameter('term', '%'.strtolower($term).'%');

        return $qb->getQuery()->getResult();
    }
}