src/Controller/SecurityController.php line 79

Open in your IDE?
  1. <?php
  2. /**
  3.  * @author Thomas HERISSON (contact@scaledev.fr)
  4.  * @copyright 2021 - ScaleDEV SAS, 12 RUE CHARLES MORET, 10120 ST ANDRE LES VERGERS
  5.  * @license commercial
  6.  */
  7. declare(strict_types=1);
  8. namespace App\Controller;
  9. use DateTime;
  10. use App\Repository\UserRepository;
  11. use App\Message\PasswordLostMessage;
  12. use Doctrine\ORM\EntityManagerInterface;
  13. use Symfony\Component\HttpFoundation\Request;
  14. use Symfony\Component\HttpFoundation\Response;
  15. use Symfony\Component\Routing\Annotation\Route;
  16. use Symfony\Component\HttpFoundation\JsonResponse;
  17. use Symfony\Component\Messenger\MessageBusInterface;
  18. use Symfony\Contracts\Translation\TranslatorInterface;
  19. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  20. use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
  21. use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
  22. use Symfony\Component\Security\Core\Security;
  23. class SecurityController extends AbstractController
  24. {
  25.     private EntityManagerInterface $em;
  26.     private UserRepository $userRepo;
  27.     private TranslatorInterface $tr;
  28.     public function __construct(EntityManagerInterface $emUserRepository $userRepoTranslatorInterface $tr)
  29.     {
  30.         $this->em $em;
  31.         $this->userRepo $userRepo;
  32.         $this->tr $tr;
  33.     }
  34.     /**
  35.      * @param AuthenticationUtils $authenticationUtils
  36.      * @return Response
  37.      * @Route("/login", name="app_login", host="%app.default_host%")
  38.      */
  39.     public function login(AuthenticationUtils $authenticationUtils): Response
  40.     {
  41.         if ($this->getUser()) {
  42.             return $this->redirectToRoute('app_dashboard');
  43.         }
  44.         $error $authenticationUtils->getLastAuthenticationError();
  45.         $lastUsername $authenticationUtils->getLastUsername();
  46.         return $this->render(
  47.             'security/login.html.twig',
  48.             [
  49.                 'last_username' => $lastUsername,
  50.                 'error' => $error
  51.             ]
  52.         );
  53.     }
  54.     /**
  55.      * @Route("/logout", name="app_logout")
  56.      */
  57.     public function logout()
  58.     {
  59.         // nothing to do here :)
  60.     }
  61.     /**
  62.      * @param AuthenticationUtils $authenticationUtils
  63.      * @param Request $request
  64.      * @param MessageBusInterface $messageBus
  65.      * @return Response
  66.      * @Route("/password-lost", name="app_password_lost", host="%app.default_host%")
  67.      */
  68.     public function passwordLost(
  69.         AuthenticationUtils $authenticationUtils,
  70.         Request $request,
  71.         MessageBusInterface $messageBus
  72.     ): Response {
  73.         $lastUsername $authenticationUtils->getLastUsername();
  74.         if ($request->isMethod('post')) {
  75.             $user $this->userRepo->findOneBy(['email' => $request->get('email')]);
  76.             if ($user && $user->getPassword()) {
  77.                 $messageBus->dispatch(new PasswordLostMessage($user));
  78.                 $this->addFlash(
  79.                     'success',
  80.                     $this->tr->trans('You will receive an email within a few minutes to reset your password.')
  81.                 );
  82.             } else {
  83.                 $this->addFlash('danger'$this->tr->trans('You cannot reset your password.'));
  84.             }
  85.             return $this->redirectToRoute('app_login');
  86.         }
  87.         return $this->render(
  88.             'security/password_lost.html.twig',
  89.             [
  90.                 'last_username' => $lastUsername
  91.             ]
  92.         );
  93.     }
  94.     /**
  95.      * @param Request $request
  96.      * @param UserPasswordHasherInterface $passwordHasher
  97.      * @param string $email
  98.      * @param string $token
  99.      * @return Response
  100.      * @Route("/password-renew/{email}/{token}", name="app_password_renew", host="%app.default_host%")
  101.      */
  102.     public function passwordRenew(
  103.         Request $request,
  104.         UserPasswordHasherInterface $passwordHasher,
  105.         string $email,
  106.         string $token
  107.     ): Response {
  108.         if (!$email || !$token) {
  109.             $this->addFlash('danger'$this->tr->trans('You can\'t access to this page'));
  110.             return $this->redirectToRoute('app_login');
  111.         }
  112.         $user $this->userRepo->findOneBy(['email' => urldecode($email)]);
  113.         if (
  114.             !$user
  115.             || $token != $user->getToken()
  116.             || $user->getTokenValidity() < new DateTime()
  117.         ) {
  118.             $this->addFlash('danger'$this->tr->trans('Unknown or expired password renewal request'));
  119.             return $this->redirectToRoute('app_login');
  120.         }
  121.         if ($request->isMethod('post')) {
  122.             if ($request->get('password') != $request->get('password_confirm')) {
  123.                 $this->addFlash('danger'$this->tr->trans('Passwords don\'t match'));
  124.             } else {
  125.                 $user->setPassword(
  126.                     $passwordHasher->hashPassword(
  127.                         $user,
  128.                         $request->get('password')
  129.                     )
  130.                 );
  131.                 $user->setToken(null);
  132.                 $user->setTokenValidity(null);
  133.                 $this->em->persist($user);
  134.                 $this->em->flush();
  135.                 $this->addFlash('success'$this->tr->trans('Your password has been changed. Please log in.'));
  136.                 return $this->redirectToRoute('app_login');
  137.             }
  138.         }
  139.         return $this->render('security/password_renew.html.twig');
  140.     }
  141.     /**
  142.      * @param Security $security
  143.      * @param Request $request
  144.      * @return Response
  145.      * @Route("/logged_in_check", name="logged_in_check", methods={"GET","POST"})
  146.      */
  147.     public function loggedInCheck(Security $securityRequest $request): Response
  148.     {
  149.         if ($request->isMethod('get')) {
  150.             return $this->redirectToRoute('app_dashboard');
  151.         }
  152.         return new JsonResponse(['result' => $security->isGranted('IS_AUTHENTICATED_REMEMBERED')]);
  153.     }
  154. }