vendor/witalink/starter-bundle/src/Controller/SecurityController.php line 70

Open in your IDE?
  1. <?php
  2. namespace Witalink\StarterBundle\Controller;
  3. use App\Entity\User;
  4. use Exception;
  5. use LogicException;
  6. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  7. use Symfony\Component\EventDispatcher\EventDispatcherInterface;
  8. use Symfony\Component\HttpFoundation\RequestStack;
  9. use Symfony\Component\HttpFoundation\Response;
  10. use Symfony\Component\Routing\Annotation\Route;
  11. use Symfony\Component\Security\Csrf\TokenGenerator\TokenGeneratorInterface;
  12. use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
  13. use Symfony\Contracts\Translation\TranslatorInterface;
  14. use Witalink\StarterBundle\EventSubscriber\CustomEvents;
  15. use Witalink\StarterBundle\EventSubscriber\Event\UserEvent;
  16. use Witalink\StarterBundle\Form\PasswordType;
  17. use Witalink\StarterBundle\Form\RegisterType;
  18. class SecurityController extends AbstractController
  19. {
  20.     private $authenticationUtils;
  21.     private $request;
  22.     private $translator;
  23.     private $generator;
  24.     private $withAutoRegistration;
  25.     private $withRememberMe;
  26.     private $withTerms;
  27.     private $eventDispatcher;
  28.     public function __construct(
  29.         bool $withAutoRegistration,
  30.         bool $withRememberMe,
  31.         bool $withTerms,
  32.         AuthenticationUtils $authenticationUtils,
  33.         RequestStack $request_stack,
  34.         TranslatorInterface $translator,
  35.         TokenGeneratorInterface $generator,
  36.         EventDispatcherInterface $eventDispatcher
  37.     ) {
  38.         $this->withAutoRegistration $withAutoRegistration;
  39.         $this->withRememberMe $withRememberMe;
  40.         $this->withTerms $withTerms;
  41.         $this->authenticationUtils $authenticationUtils;
  42.         $this->request $request_stack->getCurrentRequest();
  43.         $this->translator $translator;
  44.         $this->generator $generator;
  45.         $this->eventDispatcher $eventDispatcher;
  46.     }
  47.     /**
  48.      * @Route("/login", name="app_login")
  49.      */
  50.     public function login(): Response
  51.     {
  52.         // get the login error if there is one
  53.         $error $this->authenticationUtils->getLastAuthenticationError();
  54.         // last username entered by the user
  55.         $lastUsername $this->authenticationUtils->getLastUsername();
  56.         return $this->render(
  57.             '@WitalinkStarter/security/login.html.twig',
  58.             [
  59.                 'last_username' => $lastUsername,
  60.                 'error' => $error,
  61.                 'withAutoRegistration' => $this->withAutoRegistration,
  62.                 'withRememberMe' => $this->withRememberMe,
  63.             ]
  64.         );
  65.     }
  66.     /**
  67.      * @Route("/logout", name="app_logout")
  68.      */
  69.     public function logout()
  70.     {
  71.         throw new LogicException('This method can be blank - it will be intercepted by the logout key on your firewall.');
  72.     }
  73.     /**
  74.      * @Route("/forgot", name="app_forgot_password")
  75.      */
  76.     public function forgotPassword()
  77.     {
  78.         if ($this->request->isMethod('POST')) {
  79.             $forgetPasswordEmail $this->request->request->get('forgetPasswordEmail');
  80.             $em $this->getDoctrine()->getManager();
  81.             /** @var User $user */
  82.             $user $em->getRepository(User::class)->findOneBy(['email' => $forgetPasswordEmail]);
  83.             if (null === $user) {
  84.                 $this->addFlash('danger'$this->translator->trans('user.email.absent', [], 'validators'));
  85.                 return $this->redirectToRoute('app_forgot_password');
  86.             }
  87.             $token $this->generator->generateToken();
  88.             try {
  89.                 $user->setToken($token);
  90.                 $em->flush();
  91.                 // we dispatch event to send the reset password email
  92.                 $this->eventDispatcher->dispatch(new UserEvent($user), CustomEvents::USER_FORGET_PASSWORD);
  93.                 $this->addFlash('success'$this->translator->trans('user.email.sent', [], 'validators'));
  94.             } catch (Exception $e) {
  95.                 $this->addFlash('danger'$e);
  96.             }
  97.             return $this->redirectToRoute('app_forgot_password');
  98.         }
  99.         return $this->render(
  100.             '@WitalinkStarter/security/forget_password_email.html.twig',
  101.             [
  102.                 'withAutoRegistration' => $this->withAutoRegistration,
  103.             ]
  104.         );
  105.     }
  106.     /**
  107.      * @Route("/register", name="app_register")
  108.      */
  109.     public function register(TokenGeneratorInterface $generator)
  110.     {
  111.         if (!$this->withAutoRegistration) {
  112.             return $this->redirectToRoute('app_login');
  113.         }
  114.         $user = new User();
  115.         $form $this->createForm(RegisterType::class, $user);
  116.         $form->handleRequest($this->request);
  117.         if ($form->isSubmitted() && $form->isValid() && $this->request->isMethod('POST')) {
  118.             $email $user->getEmail();
  119.             $em $this->getDoctrine()->getManager();
  120.             $result $em->getRepository(User::class)->findOneBy(['email' => $email]);
  121.             if ($result) {
  122.                 $this->addFlash('danger'"$email est déjà utilisé");
  123.             } else {
  124.                 try {
  125.                     $token $generator->generateToken();
  126.                     $user->setToken($token);
  127.                     $em->persist($user);
  128.                     $em->flush();
  129.                     // The user has been created, at this point, we dispatch events
  130.                     $this->eventDispatcher->dispatch(new UserEvent($form->getData()), CustomEvents::USER_REGISTRED);
  131.                     $this->addFlash('success'"Un email d'activation vous a été envoyé.");
  132.                 } catch (Exception $e) {
  133.                     $this->addFlash('danger'$e);
  134.                 }
  135.             }
  136.             return $this->redirectToRoute('app_register');
  137.         }
  138.         return $this->render(
  139.             '@WitalinkStarter/security/register.html.twig',
  140.             [
  141.                 'error' => $form->getErrors(),
  142.                 'form' => $form->createView(),
  143.                 'withTerms' => $this->withTerms,
  144.             ]
  145.         );
  146.     }
  147.     /**
  148.      * @Route("/reset", name="app_reset_password")
  149.      * @Route("/activate", name="app_activate")
  150.      */
  151.     public function resetPassword()
  152.     {
  153.         $isActivate = ($this->request->attributes->get('_route') == "app_activate") ? true false;
  154.         $token $this->request->query->get('token');
  155.         if (empty($token)) {
  156.             $this->addFlash('danger'"Le token ne doit pas être vide");
  157.             return $this->redirectToRoute('app_reset_password');
  158.         }
  159.         $em $this->getDoctrine()->getManager();
  160.         /** @var User $user */
  161.         $user $em->getRepository(User::class)->findOneBy(['token' => $token]);
  162.         if (null === $user) {
  163.             $this->addFlash('danger'$this->translator->trans('expired_activation_link'));
  164.             return $this->redirectToRoute('app_forgot_password');
  165.         }
  166.         $form $this->createForm(PasswordType::class, $user);
  167.         $form->handleRequest($this->request);
  168.         if ($form->isSubmitted() && $form->isValid()) {
  169.             $formData $this->request->request->get('password');
  170.             //dd($formData);
  171.             $passwd $formData['password']['first'];
  172.             $repPasswd $formData['password']['second'];
  173.             if ($passwd == $repPasswd) {
  174.                 $user->setPlainPassword($passwd);
  175.                 $user->setToken(null);
  176.                 $em->flush();
  177.                 $this->addFlash('success'$this->translator->trans('user.password.passed', [], 'validators'));
  178.                 $this->denyAccessUnlessGranted('IS_AUTHENTICATED_FULLY');
  179.             }
  180.         }
  181.         return $this->render(
  182.             '@WitalinkStarter/security/reset_password.html.twig',
  183.             [
  184.                 'isActivate' => $isActivate,
  185.                 'form' => $form->createView(),
  186.             ]
  187.         );
  188.     }
  189. }