src/Controller/SecurityController.php line 124

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\Entity\FrontUser;
  4. use App\Entity\Page;
  5. use App\Form\ForgotPasswordType;
  6. use App\Form\FrontUser\FrontUserType;
  7. use App\Form\Model\ForgotPassword;
  8. use App\Form\Model\ResetPassword;
  9. use App\Form\ResetPasswordType;
  10. use App\Repository\FrontUserRepository;
  11. use App\Service\MailService;
  12. use App\Utils\FormHelper;
  13. use Doctrine\DBAL\Exception\UniqueConstraintViolationException;
  14. use Doctrine\ORM\NonUniqueResultException;
  15. use Doctrine\Persistence\ManagerRegistry;
  16. use Exception;
  17. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  18. use Symfony\Component\HttpFoundation\JsonResponse;
  19. use Symfony\Component\HttpFoundation\RedirectResponse;
  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\Http\Authentication\AuthenticationUtils;
  25. use Twig\Error\LoaderError;
  26. use Twig\Error\RuntimeError;
  27. use Twig\Error\SyntaxError;
  28. #[Route('')]
  29. class SecurityController extends AbstractController
  30. {
  31.     /**
  32.      * SecurityController constructor.
  33.      */
  34.     public function __construct(
  35.         protected MailService                        $mailer,
  36.         private readonly UserPasswordHasherInterface $passwordEncoder,
  37.         protected ManagerRegistry                    $registry,
  38.         private readonly MailService $mailService
  39.     ) {
  40.     }
  41.     /**
  42.      * @throws SyntaxError
  43.      * @throws RuntimeError
  44.      * @throws LoaderError
  45.      */
  46.     #[Route("/registration"name"front_registration"methods: ["POST"], priority10)]
  47.     public function registration(Request $requestFrontUserRepository $frontUserRepository): JsonResponse
  48.     {
  49.         $token $request->request->get("front_user")["token"];
  50.         if ($this->isCsrfTokenValid("front_user_form"$token)) {
  51.             $frontUser  = new FrontUser();
  52.             $form       $this->createForm(FrontUserType::class, $frontUser);
  53.             if ('POST' == $request->getMethod()) {
  54.                 $form->handleRequest($request);
  55.                 if ($form->isSubmitted() && $form->isValid()) {
  56.                     $hashedPassword $this->passwordEncoder->hashPassword(
  57.                         $frontUser,
  58.                         $frontUser->getPlainPassword()
  59.                     );
  60.                     $frontUser->setRoles(["ROLE_USER"]);
  61.                     $frontUser->setPassword($hashedPassword);
  62.                     $frontUserRepository->add($frontUser);
  63.                     $link $this->generateUrl('back_frontUser_edit', [
  64.                         "id" => $frontUser->getId(),
  65.                     ]);
  66.                     $this->mailService->accountCreationNotification($link);
  67.                     return $this->json([
  68.                         "success"   => true,
  69.                     ], Response::HTTP_CREATED);
  70.                 }
  71.                 return $this->json([
  72.                     "success"   => false,
  73.                     "errors"    => FormHelper::getErrorMessages($form)
  74.                 ], Response::HTTP_UNPROCESSABLE_ENTITY);
  75.             }
  76.             return $this->json([
  77.                 "success"   => false,
  78.                 "message"   => "Method Not Allowed."
  79.             ], Response::HTTP_METHOD_NOT_ALLOWED);
  80.         }
  81.         return $this->json([
  82.             "success"   => false,
  83.             "message"   => "Access Forbidden."
  84.         ], Response::HTTP_FORBIDDEN);
  85.     }
  86.     #[Route("/connexion"name"front_security_login"priority10)]
  87.     public function login(AuthenticationUtils $authenticationUtils): Response
  88.     {
  89.         $error          $authenticationUtils->getLastAuthenticationError();
  90.         $lastUsername   $authenticationUtils->getLastUsername();
  91.         $page $this->registry->getRepository(Page::class)->findOneSingleByType("login");
  92.         return $this->render('front/layout/login.html.twig', [
  93.             'last_username' => $lastUsername,
  94.             'error'         => $error,
  95.             'page'          => $page
  96.         ]);
  97.     }
  98.     /**
  99.      * @throws NonUniqueResultException
  100.      * @throws LoaderError
  101.      * @throws RuntimeError
  102.      * @throws SyntaxError
  103.      */
  104.     #[Route('/mot-de-passe/oublie'name'front_security_forgot_password'priority10)]
  105.     public function forgotPassword(Request $request): Response
  106.     {
  107.         $error      null;
  108.         $success    null;
  109.         $forgotPassword = new ForgotPassword();
  110.         $form $this->createForm(ForgotPasswordType::class, $forgotPassword);
  111.         if ('POST' == $request->getMethod()) {
  112.             $form->handleRequest($request);
  113.             if ($form->isSubmitted() && $form->isValid()) {
  114.                 $mail $forgotPassword->getEmail();
  115.                 /** @var FrontUserRepository $repository */
  116.                 $repository $this->registry->getRepository(FrontUser::class);
  117.                 /** @var FrontUser $user */
  118.                 $user $repository->findOneByMail($mail);
  119.                 $success false;
  120.                 if (null !== $user) {
  121.                     $user->generateResetPasswordHash();
  122.                     $em $this->registry->getManager();
  123.                     $em->persist($user);
  124.                     $em->flush();
  125.                     $this->mailer->resetFrontPassword($user);
  126.                     $success true;
  127.                 }
  128.             }
  129.             $error FormHelper::getErrorMessages($form);
  130.             if (isset($error['forgot_password[email]'])) {
  131.                 $error $error['forgot_password[email]'][0];
  132.             }
  133.         }
  134.         $form FormHelper::getData($form);
  135.         $page $this->registry->getRepository(Page::class)->findOneSingleByType("forgot-password");
  136.         return $this->render('front/layout/forgot-password.html.twig', [
  137.             'form'      => $form['forgot_password']['children'],
  138.             'error'     => $error ?? null,
  139.             'page'      => $page,
  140.             'success'   => $success ?? null
  141.         ]);
  142.     }
  143.     #[Route('/mot-de-passe/reinitialisation/{resetPasswordHash}'name'front_security_reset_password'priority10)]
  144.     public function resetPassword(Request $requestFrontUser $user): Response
  145.     {
  146.         $error null;
  147.         $resetPassword = new ResetPassword();
  148.         $form $this->createForm(ResetPasswordType::class, $resetPassword);
  149.         if ('POST' == $request->getMethod()) {
  150.             $form->handleRequest($request);
  151.             if ($form->isSubmitted() && $form->isValid()) {
  152.                 $em $this->registry->getManager();
  153.                 $user->setPassword($this->passwordEncoder->hashPassword($user$resetPassword->getPassword()));
  154.                 $user->setResetPasswordHash(null);
  155.                 $em->persist($user);
  156.                 $em->flush();
  157.                 return new RedirectResponse($this->generateUrl('front_security_login'));
  158.             }
  159.             $error FormHelper::getErrorMessages($form);
  160.             if (isset($error['reset_password[password]']['reset_password[password][first]'])) {
  161.                 $error $error['reset_password[password]']['reset_password[password][first]'][0];
  162.             } elseif (isset($error['reset_password[password]']['reset_password[password][second]'])) {
  163.                 $error $error['reset_password[password]']['reset_password[password][second]'][0];
  164.             }
  165.         }
  166.         $form FormHelper::getData($form);
  167.         $page $this->registry->getRepository(Page::class)->findOneSingleByType("reset-password");
  168.         return $this->render('front/layout/reset-password.html.twig', [
  169.             'form'  => $form['reset_password']['children'],
  170.             'error' => $error ?? null,
  171.             'hash'  => $user->getResetPasswordHash(),
  172.             'page'  => $page
  173.         ]);
  174.     }
  175.     #[Route('/confirm-mail/{confirmEmailHash}'name'front_security_confirmEmail')]
  176.     public function confirmEmail(FrontUser $user): Response
  177.     {
  178.         $em $this->registry->getManager();
  179.         $user->setConfirmEmail(true);
  180.         $user->setConfirmEmailHash();
  181.         $em->persist($user);
  182.         $em->flush();
  183.         return new RedirectResponse($this->generateUrl('front_security_login'));
  184.     }
  185.     /**
  186.      * @throws \Exception
  187.      */
  188.     #[Route('/logout'name'front_security_logout')]
  189.     public function logout(): never
  190.     {
  191.         throw new Exception('This should never be reached!');
  192.     }
  193. }