src/Controller/ResetPasswordController.php line 44

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\Entity\User;
  4. use App\Form\ChangePasswordFormType;
  5. use App\Form\PasswordChangeType;
  6. use App\Form\ResetPasswordRequestFormType;
  7. use Doctrine\ORM\EntityManager;
  8. use Doctrine\ORM\EntityManagerInterface;
  9. use Symfony\Bridge\Twig\Mime\TemplatedEmail;
  10. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  11. use Symfony\Component\HttpFoundation\RedirectResponse;
  12. use Symfony\Component\HttpFoundation\Request;
  13. use Symfony\Component\HttpFoundation\Response;
  14. use Symfony\Component\Mailer\MailerInterface;
  15. use Symfony\Component\Mime\Address;
  16. use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
  17. use Symfony\Component\Routing\Annotation\Route;
  18. use SymfonyCasts\Bundle\ResetPassword\Controller\ResetPasswordControllerTrait;
  19. use SymfonyCasts\Bundle\ResetPassword\Exception\ResetPasswordExceptionInterface;
  20. use SymfonyCasts\Bundle\ResetPassword\ResetPasswordHelperInterface;
  21. use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
  22. #[Route('/reset-password')]
  23. class ResetPasswordController extends AbstractController
  24. {
  25.     use ResetPasswordControllerTrait;
  26.     private $resetPasswordHelper;
  27.     private $entityManager;
  28.     public function __construct(ResetPasswordHelperInterface $resetPasswordHelperEntityManagerInterface $entityManager)
  29.     {
  30.         $this->resetPasswordHelper $resetPasswordHelper;
  31.         $this->entityManager $entityManager;
  32.     }
  33.     /**
  34.      * Display & process form to request a password reset.
  35.      */
  36.     #[Route(''name'app_forgot_password_request')]
  37.     public function request(Request $requestMailerInterface $mailer): Response
  38.     {
  39.         $form $this->createForm(ResetPasswordRequestFormType::class);
  40.         $form->handleRequest($request);
  41.         if ($form->isSubmitted() && $form->isValid()) {
  42.             return $this->processSendingPasswordResetEmail(
  43.                 $form->get('email')->getData(),
  44.                 $mailer
  45.             );
  46.         }
  47.         return $this->render('reset_password/request.html.twig', [
  48.             'requestForm' => $form->createView(),
  49.         ]);
  50.     }
  51.     #[Route('/passwort-aendern/{id}'name'passwort_change')]
  52.     public function passwordChange(Request $requestUser $userUserPasswordHasherInterface $passwordEncoderEntityManagerInterface $entityManager)
  53.     {
  54.         $users $user;
  55.         // dd($users);
  56.         $form $this->createForm(PasswordChangeType::class, $users);
  57.         $form->handleRequest($request);
  58.         if ($form->isSubmitted() && $form->isValid()) {
  59.             $users->setPassword(
  60.                 $passwordEncoder->hashPassword(
  61.                     $user,
  62.                     $form["plainPassword"]->getData()
  63.                 )
  64.             );
  65.             $entityManager->persist($users);
  66.             $entityManager->flush();
  67.             $this->addFlash(
  68.                 'success',
  69.                 'Das Passwort wurde geändert.'
  70.             );
  71.             if ($this->getUser()->getHighestRole() == 'ROLE_ADMIN') {
  72.                 return $this->redirectToRoute('view_all_skiclubs');
  73.             } else {
  74.                 return $this->redirectToRoute('view_user', ['id' => $user->getId()]);
  75.             }
  76.         }
  77.         return $this->render('reset_password/password_change.html.twig', [
  78.             'form' => $form->createView(),
  79.         ]);
  80.     }
  81.     /**
  82.      * Confirmation page after a user has requested a password reset.
  83.      */
  84.     #[Route('/check-email'name'app_check_email')]
  85.     public function checkEmail(): Response
  86.     {
  87.         // Generate a fake token if the user does not exist or someone hit this page directly.
  88.         // This prevents exposing whether or not a user was found with the given email address or not
  89.         if (null === ($resetToken $this->getTokenObjectFromSession())) {
  90.             return $this->redirectToRoute('app_forgot_password_request');
  91.             //$resetToken = $this->resetPasswordHelper->generateFakeResetToken();
  92.         }
  93.         return $this->render('reset_password/check_email.html.twig', [
  94.             'resetToken' => $resetToken,
  95.         ]);
  96.     }
  97.     /**
  98.      * Validates and process the reset URL that the user clicked in their email.
  99.      */
  100.     #[Route('/reset/{token}'name'app_reset_password')]
  101.     public function reset(Request $requestUserPasswordHasherInterface $userPasswordHasherstring $token null): Response
  102.     {
  103.         if ($token) {
  104.             // We store the token in session and remove it from the URL, to avoid the URL being
  105.             // loaded in a browser and potentially leaking the token to 3rd party JavaScript.
  106.             $this->storeTokenInSession($token);
  107.             return $this->redirectToRoute('app_reset_password');
  108.         }
  109.         $token $this->getTokenFromSession();
  110.         if (null === $token) {
  111.             throw $this->createNotFoundException('No reset password token found in the URL or in the session.');
  112.         }
  113.         try {
  114.             $user $this->resetPasswordHelper->validateTokenAndFetchUser($token);
  115.         } catch (ResetPasswordExceptionInterface $e) {
  116.             $this->addFlash('reset_password_error'sprintf(
  117.                 '%s - %s',
  118.                 ResetPasswordExceptionInterface::MESSAGE_PROBLEM_VALIDATE,
  119.                 $e->getReason()
  120.             ));
  121.             return $this->redirectToRoute('app_forgot_password_request');
  122.         }
  123.         // The token is valid; allow the user to change their password.
  124.         $form $this->createForm(ChangePasswordFormType::class);
  125.         $form->handleRequest($request);
  126.         if ($form->isSubmitted() && $form->isValid()) {
  127.             // A password reset token should be used only once, remove it.
  128.             $this->resetPasswordHelper->removeResetRequest($token);
  129.             // Encode(hash) the plain password, and set it.
  130.             $encodedPassword $userPasswordHasher->hashPassword(
  131.                 $user,
  132.                 $form->get('plainPassword')->getData()
  133.             );
  134.             $user->setPassword($encodedPassword);
  135.             $this->entityManager->flush();
  136.             // The session is cleaned up after the password has been changed.
  137.             $this->cleanSessionAfterReset();
  138.             $this->addFlash(
  139.                 'success',
  140.                 'Das Passwort wurde erfolgreich zurückgesetzt.'
  141.             );
  142.             return $this->redirectToRoute('index');
  143.         }
  144.         return $this->render('reset_password/reset.html.twig', [
  145.             'resetForm' => $form->createView(),
  146.         ]);
  147.     }
  148.     private function processSendingPasswordResetEmail(string $emailFormDataMailerInterface $mailer): RedirectResponse
  149.     {
  150.         $user $this->entityManager->getRepository(User::class)->findOneBy([
  151.             'email' => $emailFormData,
  152.         ]);
  153.         $this->addFlash(
  154.             'success',
  155.             'Sofern zur angegebenen E-Mail-Adresse ein Account registriert ist, wurde ein Link zum Zurücksetzen an Ihre E-Mail-Adresse gesendet.'
  156.         );
  157.         // Do not reveal whether a user account was found or not.
  158.         if (!$user) {
  159.             return $this->redirectToRoute('app_check_email');
  160.         }
  161.         try {
  162.             $resetToken $this->resetPasswordHelper->generateResetToken($user);
  163.         } catch (ResetPasswordExceptionInterface $e) {
  164.             // If you want to tell the user why a reset email was not sent, uncomment
  165.             // the lines below and change the redirect to 'app_forgot_password_request'.
  166.             // Caution: This may reveal if a user is registered or not.
  167.             //
  168.             // $this->addFlash('reset_password_error', sprintf(
  169.             //     '%s - %s',
  170.             //     ResetPasswordExceptionInterface::MESSAGE_PROBLEM_HANDLE,
  171.             //     $e->getReason()
  172.             // ));
  173.             return $this->redirectToRoute('app_check_email');
  174.         }
  175.         $email = (new TemplatedEmail())
  176.             ->from(new Address('no-reply@skiclub-manager.de''Skiclub'))
  177.             ->to($user->getEmail())
  178.             ->subject('Ihre Anfrage zum Passwort zurücksetzen')
  179.             ->htmlTemplate('reset_password/email.html.twig')
  180.             ->context([
  181.                 'resetToken' => $resetToken,
  182.             ]);
  183.         $mailer->send($email);
  184.         // Store the token object in session for retrieval in check-email route.
  185.         $this->setTokenObjectInSession($resetToken);
  186.         return $this->redirectToRoute('app_check_email');
  187.     }
  188. }