src/Controller/SecurityController.php line 123

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\Entity\User;
  4. use App\Manager\UserManager;
  5. use App\Form\ResetPasswordType;
  6. use App\Repository\UserRepository;
  7. use App\Form\ForgottenPasswordType;
  8. use Symfony\Component\Form\FormError;
  9. use Symfony\Component\HttpFoundation\Request;
  10. use Symfony\Component\Mailer\MailerInterface;
  11. use Symfony\Component\HttpFoundation\Response;
  12. use Symfony\Component\Routing\Annotation\Route;
  13. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  14. use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
  15. use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
  16. use Symfony\Component\Security\Csrf\TokenGenerator\TokenGeneratorInterface;
  17. use Symfony\Component\Security\Core\User\UserInterface;
  18. class SecurityController extends AbstractController
  19. {
  20.     /**
  21.      * @Route("/login", name="security_login")
  22.      */
  23.     public function login(AuthenticationUtils $authenticationUtils): Response
  24.     {
  25.         // Get the login error if there is one
  26.         $error $authenticationUtils->getLastAuthenticationError();
  27.         // Last username entered by the user
  28.         $lastUsername $authenticationUtils->getLastUsername();
  29.         return $this->render('security/login.html.twig', [
  30.             'last_username' => $lastUsername,
  31.             'error'         => $error,
  32.         ]);
  33.     }
  34.     /**
  35.      * @Route("/reset_password", name="security_reset_password")
  36.      *
  37.      * @param Request                      $request
  38.      * @param UserRepository               $userRepo
  39.      * @param UserPasswordEncoderInterface $encoder
  40.      * @param UserManager                  $userManager
  41.      *
  42.      * @return Response
  43.      * @throws \Exception
  44.      */
  45.     public function resetPassword(Request $requestUserRepository $userRepoUserPasswordEncoderInterface $encoderUserManager $userManager)
  46.     {
  47.         $isTokenValid false;
  48.         $tokenToCheck $request->query->get('token');
  49.         if(!$tokenToCheck)
  50.         {
  51.             return $this->redirectToRoute('security_login');
  52.         }
  53.         $userTarget   $userRepo->findOneByToken($tokenToCheck);
  54.         
  55.         $form $this->createForm(ResetPasswordType::class, $userTarget);
  56.         $form->handleRequest($request);
  57.         // If token match a User
  58.         if ($userTarget != null) {
  59.             // Check if token is expired
  60.             $dateNow = new \Datetime('now');
  61.             $dateNow->setTimezone(new \DateTimezone('Europe/Paris'));
  62.             $tokenDate $userTarget->getTokenCreatedAt();
  63.             $tokenDate->add(new \DateInterval('P7D'));
  64.             if ($dateNow $tokenDate) {
  65.                 // Define token Status
  66.                 $isTokenValid true;
  67.                 if ($form->isSubmitted() && $form->isValid()) {
  68.                     $newPassword $form->get('password')->getData();
  69.                     $userTarget->setPassword($encoder->encodePassword($userTarget$newPassword));
  70.                     $userTarget->setTokenResetPassword(null);
  71.                     $userTarget->setTokenCreatedAt(null);
  72.                     $userManager->update($userTarget);
  73.                     $this->addFlash(
  74.                         'success',
  75.                         'Mot de passe mis à jour avec succès.'
  76.                     );
  77.                     return $this->redirectToRoute('security_login');
  78.                 }
  79.             } else {
  80.                 return $this->redirectToRoute('security_forgotten_password', [
  81.                     'tokenExpired' => true
  82.                 ]);
  83.             }
  84.         }
  85.         return $this->render('security/reset_password.html.twig', [
  86.             'form'           => $form->createView(),
  87.             'token_is_valid' => $isTokenValid,
  88.         ]);
  89.     }
  90.     /**
  91.      * @Route("/forgotten_password", name="security_forgotten_password")
  92.      *
  93.      * @param Request                 $request
  94.      * @param UserManager             $userManager
  95.      * @param UserRepository          $userRepo
  96.      * @param TokenGeneratorInterface $tokenGenerator
  97.      * @param \Swift_Mailer           $mailer
  98.      *
  99.      * @return Response
  100.      * @throws \Exception
  101.      */
  102.     public function forgottenPassword(Request $requestUserManager $userManagerUserRepository $userRepoTokenGeneratorInterface $tokenGenerator, \Swift_Mailer $mailer)
  103.     {
  104.         $tokenExpired false;
  105.         if ($request->query->get('tokenExpired')){
  106.             $tokenExpired $request->query->get('tokenExpired');
  107.         }
  108.         $submitted false;
  109.         $userExist false;
  110.         $form $this->createForm(ForgottenPasswordType::class);
  111.         $form->handleRequest($request);
  112.         if ($form->isSubmitted() && $form->isValid()) {
  113.             $submitted true;
  114.             $email $form->get('email')->getData();
  115.             $user $userRepo->findOneBy(['email' => $email]);
  116.             if ($user) {
  117.                 $userExist true;
  118.                 $date = (new \DateTime('now'))
  119.                     ->setTimezone(new \DateTimeZone('Europe/Paris'));
  120.                 // Generate a random token
  121.                 $token $tokenGenerator->generateToken();
  122.                 // Associate token to User
  123.                 $user->setTokenResetPassword($token);
  124.                 $user->setTokenCreatedAt($date);
  125.                 // Save token
  126.                 $userManager->update($user);
  127.                 // Send email to User
  128.                 $sendEmail = (new \Swift_Message())
  129.                     ->setFrom(['no-reply@specific-polymers.fr' => 'Specific Polymers'])
  130.                     ->setTo($user->getEmail())
  131.                     ->setSubject('Specific Polymers - Récupération de votre mot de passe')
  132.                     ->setBody(
  133.                         $this->renderView(
  134.                             'mail/reset_password_mail.html.twig',
  135.                             [
  136.                                 'user_target' => $user,
  137.                             ]
  138.                         ),
  139.                         'text/html'
  140.                     );
  141.                 $mailer->send($sendEmail);
  142.             }
  143.         }
  144.         return $this->render(
  145.             'security/forgotten_password.html.twig',
  146.             [
  147.                 'form'         => $form->createView(),
  148.                 'submitted'    => $submitted,
  149.                 'tokenExpired' => $tokenExpired,
  150.                 'userExist'    => $userExist
  151.             ]
  152.         );
  153.     }
  154.     /**
  155.      * @Route("/logout", name="security_logout")
  156.      */
  157.     public function logout()
  158.     {
  159.         
  160.     }
  161. }