src/Controller/Back/UserController.php line 291

Open in your IDE?
  1. <?php
  2. namespace App\Controller\Back;
  3. use App\Adapter\AdminViewAdapter;
  4. use App\Entity\User;
  5. use App\Factories\UserFactory;
  6. use App\Form\CustomExportForm;
  7. use App\Form\RegistrationModifyFormType;
  8. use App\Form\User\AdminUserType;
  9. use App\Form\User\UserEditType;
  10. use App\Form\User\UserMdpEditType;
  11. use App\Logger\UserLoggerHistory;
  12. use App\Repository\UserRepository;
  13. use App\Utils\CsvUserCreator;
  14. use App\Utils\DateCalculator;
  15. use App\Utils\Mailer;
  16. use Doctrine\ORM\EntityManagerInterface;
  17. use OpenApi\Annotations as OA;
  18. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  19. use Symfony\Component\HttpFoundation\JsonResponse;
  20. use Symfony\Component\HttpFoundation\Request;
  21. use Symfony\Component\HttpFoundation\Response;
  22. use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
  23. use Symfony\Component\Routing\Annotation\Route;
  24. use Symfony\Component\Security\Core\Exception\AccessDeniedException;
  25. use Symfony\Component\Serializer\SerializerInterface;
  26. use Symfony\Contracts\Translation\TranslatorInterface;
  27. /**
  28.  * @Route("/admin/user")
  29.  *
  30.  * @OA\Tag(name="Admin BO - User")
  31.  */
  32. class UserController extends AbstractController
  33. {
  34.     private UserRepository $userRepo;
  35.     private EntityManagerInterface $em;
  36.     private SerializerInterface $serializer;
  37.     private UserLoggerHistory $userLoggerHistory;
  38.     private DateCalculator $dateCalculator;
  39.     private UserFactory $userFactory;
  40.     private TranslatorInterface $translator;
  41.     public function __construct(
  42.         UserRepository $userRepository,
  43.         EntityManagerInterface $entityManager,
  44.         SerializerInterface $serializer,
  45.         UserLoggerHistory $userLoggerHistory,
  46.         DateCalculator $dateCalculator,
  47.         UserFactory $userFactory,
  48.         TranslatorInterface $translator
  49.     ) {
  50.         $this->userRepo $userRepository;
  51.         $this->em $entityManager;
  52.         $this->serializer $serializer;
  53.         $this->userLoggerHistory $userLoggerHistory;
  54.         $this->dateCalculator $dateCalculator;
  55.         $this->userFactory $userFactory;
  56.         $this->translator $translator;
  57.     }
  58.     /**
  59.      * Administrators list.
  60.      *
  61.      * @Route(
  62.      *      "/listeAdmin",
  63.      *      name="liste_user",
  64.      *      methods={"GET"}
  65.      * )
  66.      */
  67.     public function admins(): Response
  68.     {
  69.         $admins array_map(function (User $admin) {
  70.             $admin = new AdminViewAdapter($admin);
  71.             $admin->setActions(
  72.                 [
  73.                     'isActive' => === array_search('ROLE_INACTIF'$admin->getRoles()),
  74.                     'edit' => $this->generateUrl('user_edit', [
  75.                         'id' => (string) $admin->getId(),
  76.                     ]),
  77.                     'password' => $this->generateUrl('user_send_password_mail', [
  78.                         'id' => (string) $admin->getId(),
  79.                     ]),
  80.                     'delete' => $this->generateUrl('user_delete', [
  81.                         'id' => (string) $admin->getId(),
  82.                     ]),
  83.                 ]
  84.             );
  85.             return $admin;
  86.         }, $this->userRepo->findAllAdmins());
  87.         return $this->render(
  88.             'user/admin/administrateurs.html.twig',
  89.             ['administrateurs' => $this->serializer->serialize($admins'json')]
  90.         );
  91.     }
  92.     /**
  93.      * Send another email to admin.
  94.      *
  95.      * @Route(
  96.      *      "/{id}/mail",
  97.      *      name="user_send_password_mail",
  98.      *      methods={"GET"}
  99.      * )
  100.      */
  101.     public function resendMailAdminPassword(
  102.         User $user,
  103.         Mailer $mailer
  104.     ): Response {
  105.         $user->setEmailAuthCode(bin2hex(random_bytes(16)));
  106.         $this->em->persist($user);
  107.         $this->em->flush();
  108.         try {
  109.             $mailer->sendAdminCreationMail($user);
  110.         } catch (\Exception $e) {
  111.             $this->addFlash('danger''danger.' $e->getMessage());
  112.             return $this->redirectToRoute('liste_user');
  113.         }
  114.         $this->userLoggerHistory->logAdmin(
  115.             $user,
  116.             $this->getUser(),
  117.             'resend mail password'
  118.         );
  119.         $this->addFlash('success''success.resendPassword');
  120.         return $this->redirectToRoute('liste_user');
  121.     }
  122.     /**
  123.      * Create a user.
  124.      *
  125.      * @Route(
  126.      *      "/create",
  127.      *      name="user_create",
  128.      *      methods={"GET", "POST"}
  129.      * )
  130.      */
  131.     public function create(
  132.         Request $request,
  133.         Mailer $mailer
  134.     ): Response {
  135.         $user $this->userFactory->createAdminUser();
  136.         $user->setEmailAuthCode(bin2hex(random_bytes(16)));
  137.         $user->setDoubleauth(0);
  138.         $form $this->createForm(
  139.             AdminUserType::class,
  140.             $user,
  141.             ['type' => 'create']
  142.         );
  143.         $form->handleRequest($request);
  144.         if ($form->isSubmitted() && $form->isValid()) {
  145.             $user->setPassword('todefine');
  146.             $user->setIsActive(false);
  147.             $this->em->persist($user);
  148.             $this->em->flush();
  149.             $this->userLoggerHistory->logAdmin(
  150.                 $user,
  151.                 $this->getUser(),
  152.                 'Création'
  153.             );
  154.             $mailer->sendAdminCreationMail($user);
  155.             $this->addFlash('success''success.adminRegistered');
  156.             return $this->redirectToRoute('liste_user');
  157.         }
  158.         return $this->render(
  159.             'user/admin/create.html.twig',
  160.             ['form' => $form->createView()]
  161.         );
  162.     }
  163.     /**
  164.      * Create a user.
  165.      *
  166.      * @Route(
  167.      *      "/edit/{id}",
  168.      *      name="user_edit",
  169.      *      methods={"GET", "POST"}
  170.      * )
  171.      */
  172.     public function edit(
  173.         Request $request,
  174.         User $user
  175.     ): Response {
  176.         $this->userLoggerHistory->addHistory([
  177.             'roles',
  178.             'getemail',
  179.             'doubleauth',
  180.         ]);
  181.         $this->userLoggerHistory->setOldReference($user);
  182.         $type 'edit';
  183.         $form $this->createForm(UserEditType::class, $user, [
  184.             'type' => $type,
  185.         ]);
  186.         $form->get('doubleauth')->setData($user->getDoubleauth());
  187.         $form->handleRequest($request);
  188.         if ($form->isSubmitted() && $form->isValid()) {
  189.             // Valid user modification
  190.             $user->setDeletedAt(null);
  191.             $user->setDoubleauth($form->get('doubleauth')->getData());
  192.             $this->em->flush();
  193.             $this->userLoggerHistory->setNewReference($user);
  194.             /** @var User $modifier */
  195.             $modifier $this->getUser();
  196.             $this->userLoggerHistory->persistDiff(
  197.                 $modifier,
  198.                 $user
  199.             );
  200.             // for now
  201.             return $this->redirectToRoute('liste_user');
  202.         }
  203.         return $this->render(
  204.             'user/admin/edit.html.twig',
  205.             [
  206.                 'form' => $form->createView(),
  207.                 'user' => $user,
  208.             ]
  209.         );
  210.     }
  211.     /**
  212.      * Delete a user.
  213.      *
  214.      * @Route(
  215.      *      "/delete/{id}",
  216.      *      name="user_delete",
  217.      *      methods={"GET"}
  218.      * )
  219.      */
  220.     public function delete(User $user): Response
  221.     {
  222.         if (null === $this->getUser()) {
  223.             return $this->redirectToRoute('liste_user');
  224.         }
  225.         $user->setUsername(null);
  226.         $user->setDeletedAt($this->dateCalculator->getDatetimeNow());
  227.         $user->setRoles(['ROLE_INACTIF']);
  228.         // TODO Set role inactif
  229.         // Historique actions user
  230.         $this->userLoggerHistory->logAdmin(
  231.             $user,
  232.             $this->getUser(),
  233.             'Suppression'
  234.         );
  235.         return $this->redirectToRoute('liste_user');
  236.     }
  237.     /**
  238.      * User account details.
  239.      *
  240.      * @Route(
  241.      *      "/mon_compte",
  242.      *      name="user_my_account",
  243.      *      methods={"GET", "POST"}
  244.      * )
  245.      */
  246.     public function monCompte(Request $request): Response
  247.     {
  248.         /** @var User $user */
  249.         $user $this->getUser();
  250.         $this->userLoggerHistory->setOldReference($user);
  251.         $form $this->createForm(
  252.             RegistrationModifyFormType::class,
  253.             $this->getUser()
  254.         );
  255.         $form->handleRequest($request);
  256.         if ($form->isSubmitted() && $form->isValid()) {
  257.             $this->userLoggerHistory->setNewReference($user);
  258.             $this->userLoggerHistory->persistDiff($user$user);
  259.             return $this->redirectToRoute('user_my_account');
  260.         }
  261.         return $this->render(
  262.             'user/admin/moncompte.html.twig',
  263.             ['form' => $form->createView()]
  264.         );
  265.     }
  266.     /**
  267.      * Change password.
  268.      *
  269.      * @Route(
  270.      *      "/change_password/{id}",
  271.      *      name="user_change_password",
  272.      *      methods={"GET", "POST"}
  273.      * )
  274.      */
  275.     public function changePassword(
  276.         Request $request,
  277.         User $user,
  278.         UserPasswordHasherInterface $passwordHasher
  279.     ): Response {
  280.         /** @var User $userSymfony */
  281.         $userSymfony $this->getUser();
  282.         if (
  283.             !$this->isGranted('ROLE_ADMIN')
  284.             && $user->getId() !== $userSymfony->getId()
  285.         ) {
  286.             throw new AccessDeniedException();
  287.         }
  288.         $form $this->createForm(UserMdpEditType::class, $user);
  289.         $form->handleRequest($request);
  290.         if ($form->isSubmitted() && $form->isValid()) {
  291.             $mdp $form->get('password')->getData();
  292.             if (null !== $mdp) {
  293.                 $hashedPassword $passwordHasher->hashPassword(
  294.                     $user,
  295.                     $mdp
  296.                 );
  297.                 $user->setPassword($hashedPassword);
  298.                 $this->em->flush();
  299.             }
  300.             // Historique actions user
  301.             /** @var User $modifier */
  302.             $modifier $this->getUser();
  303.             $this->userLoggerHistory->logHistoryModification(
  304.                 $user,
  305.                 $modifier,
  306.                 'password'
  307.             );
  308.             return $this->redirectToRoute('logout');
  309.         }
  310.         return $this->render(
  311.             'user/admin/monpassword.html.twig',
  312.             ['form' => $form->createView()]
  313.         );
  314.     }
  315.     /**
  316.      * Create CSV for Admin with custom header.
  317.      *
  318.      * @Route(
  319.      *      "/exportPersoAdmin",
  320.      *      name="export_perso_admin",
  321.      *      methods={"GET", "POST"}
  322.      * )
  323.      */
  324.     public function exportPersoAdmin(
  325.         Request $request,
  326.         CsvUserCreator $csvUserCreator
  327.     ): Response {
  328.         $choices = [
  329.             'Login' => 'Username',
  330.             'Email' => 'Email',
  331.             'Profil' => 'Roles',
  332.         ];
  333.         $form $this->createForm(CustomExportForm::class, null, [
  334.             'choices' => $choices,
  335.         ]);
  336.         $form->handleRequest($request);
  337.         if ($form->isSubmitted() && $form->isValid()) {
  338.             $exportCSV $request->query->get('exportCuCSV');
  339.             if ($exportCSV) {
  340.                 $admins $this->userRepo->findAllNotCustomer();
  341.                 $csvUserCreator->setFileName('administrateurs');
  342.                 $csvUserCreator->setHeaders(
  343.                     $form->get('choices')->getData(),
  344.                     array_flip($choices)
  345.                 );
  346.                 $csvUserCreator->setData($admins);
  347.                 return $csvUserCreator->downloadCSV();
  348.             }
  349.         }
  350.         return $this->render(
  351.             'user/admin/exportAdmin.html.twig',
  352.             ['form' => $form->createView()]
  353.         );
  354.     }
  355.     /**
  356.      * Allows you to send custom email to a list of users.
  357.      *
  358.      * @Route(
  359.      *      "/send-custom-email",
  360.      *      name="send_custom_email",
  361.      *      methods={"POST"}
  362.      * )
  363.      */
  364.     public function sendCustomEmailToUsers(
  365.         Request $request,
  366.         Mailer $mailer
  367.     ): JsonResponse {
  368.         $recipients $request->get('recipients');
  369.         $subject $request->get('subject');
  370.         $body $request->get('body');
  371.         $lignes explode("\n"$body);
  372.         try {
  373.             $mailer->sendCustomEmail($recipients$subject$lignes);
  374.         } catch (\Exception $e) {
  375.             return new JsonResponse([
  376.                 'status' => 'error',
  377.                 'message' => $this->translator->trans(
  378.                     'danger.error',
  379.                     [],
  380.                     'flashes'
  381.                 ) . ' : ' $e->getMessage(),
  382.             ]);
  383.         }
  384.         return new JsonResponse([
  385.             'status' => 'success',
  386.             'message' => $this->translator->trans(
  387.                 'success.emailSent',
  388.                 [],
  389.                 'flashes'
  390.             ),
  391.         ]);
  392.     }
  393. }