src/Controller/ResetPasswordController.php line 59

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\Entity\User;
  4. use App\Form\ChangePasswordFormType;
  5. use App\Form\ResetPasswordRequestFormType;
  6. use Exception;
  7. use Psr\Log\LoggerInterface;
  8. use Symfony\Bridge\Twig\Mime\TemplatedEmail;
  9. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  10. use Symfony\Component\HttpFoundation\RedirectResponse;
  11. use Symfony\Component\HttpFoundation\Request;
  12. use Symfony\Component\HttpFoundation\Response;
  13. use Symfony\Component\Mailer\MailerInterface;
  14. use Symfony\Component\Mime\Address;
  15. use Symfony\Component\Routing\Annotation\Route;
  16. use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
  17. use SymfonyCasts\Bundle\ResetPassword\Controller\ResetPasswordControllerTrait;
  18. use SymfonyCasts\Bundle\ResetPassword\Exception\ResetPasswordExceptionInterface;
  19. use SymfonyCasts\Bundle\ResetPassword\ResetPasswordHelperInterface;
  20. use SymfonyCasts\Bundle\ResetPassword\ResetPasswordHelper;
  21. /**
  22.  * @Route("/reset-password")
  23.  */
  24. class ResetPasswordController extends AbstractController
  25. {
  26.     use ResetPasswordControllerTrait;
  27.     private $resetPasswordHelper;
  28.     private $logger;
  29.     public function __construct(ResetPasswordHelperInterface $resetPasswordHelperLoggerInterface $logger)
  30.     {
  31.         $this->resetPasswordHelper $resetPasswordHelper;
  32.         $this->logger $logger;
  33.     }
  34.     /**
  35.      * Display & process form to request a password reset.
  36.      *
  37.      * @Route("", name="app_forgot_password_request")
  38.      */
  39.     public function request(Request $requestMailerInterface $mailer): Response
  40.     {
  41.         $this->logger->info('Starting request processing');
  42.         $form $this->createForm(ResetPasswordRequestFormType::class);
  43.         $form->handleRequest($request);
  44.         if ($form->isSubmitted() && $form->isValid()) {
  45.             $this->logger->info('form submitted with ' print_r($form->get('username')->getData(), true));
  46.             return $this->processSendingPasswordResetEmail(
  47.                 $form->get('username')->getData(),
  48.                 $mailer
  49.             );
  50.         }
  51.         return $this->render('reset_password/request.html.twig', [
  52.             'requestForm' => $form->createView(),
  53.         ]);
  54.     }
  55.     /**
  56.      * Confirmation page after a user has requested a password reset.
  57.      *
  58.      * @Route("/check-email", name="app_check_email")
  59.      */
  60.     public function checkEmail(): Response
  61.     {
  62.         // We prevent users from directly accessing this page
  63.         if (!$this->canCheckEmail()) {
  64.             return $this->redirectToRoute('app_forgot_password_request');
  65.         }
  66.         return $this->render('reset_password/check_email.html.twig', [
  67.             'tokenLifetime' => $this->resetPasswordHelper->getTokenLifetime(),
  68.         ]);
  69.     }
  70.     /**
  71.      * Validates and process the reset URL that the user clicked in their email.
  72.      *
  73.      * @Route("/reset/{token}", name="app_reset_password")
  74.      */
  75.     public function reset(Request $requestUserPasswordEncoderInterface $passwordEncoderstring $token null): Response
  76.     {
  77.         if ($token) {
  78.             // We store the token in session and remove it from the URL, to avoid the URL being
  79.             // loaded in a browser and potentially leaking the token to 3rd party JavaScript.
  80.             $this->storeTokenInSession($token);
  81.             return $this->redirectToRoute('app_reset_password');
  82.         }
  83.         $token $this->getTokenFromSession();
  84.         if (null === $token) {
  85.             throw $this->createNotFoundException('No reset password token found in the URL or in the session.');
  86.         }
  87.         try {
  88.             $user $this->resetPasswordHelper->validateTokenAndFetchUser($token);
  89.         } catch (ResetPasswordExceptionInterface $e) {
  90.             $this->addFlash('reset_password_error'sprintf(
  91.                 'There was a problem validating your reset request - %s',
  92.                 $e->getReason()
  93.             ));
  94.             return $this->redirectToRoute('app_forgot_password_request');
  95.         }
  96.         // The token is valid; allow the user to change their password.
  97.         $form $this->createForm(ChangePasswordFormType::class);
  98.         $form->handleRequest($request);
  99.         if ($form->isSubmitted() && $form->isValid()) {
  100.             // A password reset token should be used only once, remove it.
  101.             $this->resetPasswordHelper->removeResetRequest($token);
  102.             // Encode the plain password, and set it.
  103.             $encodedPassword $passwordEncoder->encodePassword(
  104.                 $user,
  105.                 $form->get('plainPassword')->getData()
  106.             );
  107.             $user->setPassword($encodedPassword);
  108.             $this->getDoctrine()->getManager()->flush();
  109.             // The session is cleaned up after the password has been changed.
  110.             $this->cleanSessionAfterReset();
  111.             return $this->redirectToRoute('home');
  112.         }
  113.         return $this->render('reset_password/reset.html.twig', [
  114.             'resetForm' => $form->createView(),
  115.         ]);
  116.     }
  117.     private function processSendingPasswordResetEmail(string $emailFormDataMailerInterface $mailer$noRedirect false)
  118.     {
  119.         $this->logger->info("Started Send email Process");
  120.         $user $this->getDoctrine()->getRepository(User::class)->findOneBy([
  121.             'username' => $emailFormData,
  122.         ]);
  123.         // Marks that you are allowed to see the app_check_email page.
  124.         $this->setCanCheckEmailInSession();
  125.         // Do not reveal whether a user account was found or not.
  126.         if (!$user) {
  127.             $this->logger->info("Unable to find user" $emailFormData);
  128.             return $this->redirectToRoute('app_check_email');
  129.         }
  130.         $this->logger->info("Found User " $emailFormData);
  131.         try {
  132.             $this->logger->info("Generating Reset Token");
  133.             $resetToken $this->resetPasswordHelper->generateResetToken($user);
  134.             $this->logger->info("Reset token generated : " $resetToken->getToken());
  135.         } catch (ResetPasswordExceptionInterface $e) {
  136.             // If you want to tell the user why a reset email was not sent, uncomment
  137.             // the lines below and change the redirect to 'app_forgot_password_request'.
  138.             // Caution: This may reveal if a user is registered or not.
  139.             //
  140.             $this->logger->info("Unable to generate reset Token");
  141.             $this->addFlash('reset_password_error'sprintf(
  142.                 'There was a problem handling your password reset request - %s',
  143.                 $e->getReason()
  144.             ));
  145.             return $this->redirectToRoute('app_check_email');
  146.         }
  147.         $resetPasswordFromEmail =  $this->getParameter('reset_password_from_email');
  148.         $resetPasswordFromName =  $this->getParameter('reset_password_from_name');
  149.         $this->logger->info("setting Email template Data");
  150.         $this->logger->info("Email From address: " $resetPasswordFromEmail);
  151.         $this->logger->info("Email From name: " $resetPasswordFromName);
  152.         try{
  153.             $lifetime $this->resetPasswordHelper->getTokenLifetime()/3600;
  154.         }catch(Exception $e){
  155.             $lifetime  8;
  156.         }
  157.         
  158.         $email = (new TemplatedEmail())
  159.             ->from(new Address($resetPasswordFromEmail$resetPasswordFromName))
  160.             ->to($user->getUsername())
  161.             ->subject('Your password reset request')
  162.             ->htmlTemplate('reset_password/email.html.twig')
  163.             ->context([
  164.                 'resetToken' => $resetToken,
  165.                 'tokenLifetime' => $lifetime,
  166.             ]);
  167.         if ($noRedirect) {
  168.             return $mailer->send($email);
  169.         } else {
  170.             $mailer->send($email);
  171.         }
  172.         return $this->redirectToRoute('app_check_email');
  173.     }
  174.     /**
  175.      * Send password reset email
  176.      *
  177.      * @Route("/user/reset_password/", name="app_forgot_password_manual_request")
  178.      */
  179.     public function manualReset(Request $requestMailerInterface $mailer): Response
  180.     {
  181.         $this->logger->info('Starting request processing');
  182.         $userName =  $request->get('username');
  183.         if (!$userName) {
  184.             $this->addFlash('error''Please submit a valid username');
  185.         }
  186.         $user $this->getDoctrine()->getRepository(User::class)->findOneBy([
  187.             'username' => $userName,
  188.         ]);
  189.         if (!$user) {
  190.             $this->addFlash('error''Please submit a valid user');
  191.         }
  192.         $this->processSendingPasswordResetEmail($userName$mailertrue);
  193.         $msg sprintf('Password Reset Email sent to %s'$userName);
  194.         $this->addFlash('success'$msg);
  195.         return $this->redirectToRoute('user_list');
  196.     }
  197. }