src/Controller/ResetPasswordController.php line 53

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 App\Repository\ContentBlockRepository;
  7. use App\Repository\ContestRepository;
  8. use App\Service\MailHelper;
  9. use Doctrine\ORM\EntityManagerInterface;
  10. use Symfony\Bridge\Twig\Mime\TemplatedEmail;
  11. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  12. use Symfony\Component\HttpFoundation\RedirectResponse;
  13. use Symfony\Component\HttpFoundation\Request;
  14. use Symfony\Component\HttpFoundation\Response;
  15. use Symfony\Component\Mailer\MailerInterface;
  16. use Symfony\Component\Mime\Address;
  17. use Symfony\Component\Mime\Email;
  18. use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
  19. use Symfony\Component\Routing\Annotation\Route;
  20. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  21. use Symfony\Contracts\Translation\TranslatorInterface;
  22. use SymfonyCasts\Bundle\ResetPassword\Controller\ResetPasswordControllerTrait;
  23. use SymfonyCasts\Bundle\ResetPassword\Exception\ResetPasswordExceptionInterface;
  24. use SymfonyCasts\Bundle\ResetPassword\ResetPasswordHelperInterface;
  25. /**
  26.  * @Route("/reset-password")
  27.  */
  28. class ResetPasswordController extends AbstractController
  29. {
  30.     use ResetPasswordControllerTrait;
  31.     private ResetPasswordHelperInterface $resetPasswordHelper;
  32.     private EntityManagerInterface $entityManager;
  33.     private MailHelper $mailHelper;
  34.     private ContentBlockRepository $contentBlockRepository;
  35.     public function __construct(ResetPasswordHelperInterface $resetPasswordHelperEntityManagerInterface $entityManagerMailHelper $mailHelperContentBlockRepository $contentBlockRepository)
  36.     {
  37.         $this->resetPasswordHelper $resetPasswordHelper;
  38.         $this->entityManager $entityManager;
  39.         $this->mailHelper $mailHelper;
  40.         $this->contentBlockRepository $contentBlockRepository;
  41.     }
  42.     /**
  43.      * Display & process form to request a password reset.
  44.      *
  45.      * @Route("", name="app_forgot_password_request")
  46.      */
  47.     public function request(Request $requestMailerInterface $mailerTranslatorInterface $translator): Response
  48.     {
  49.         $form $this->createForm(ResetPasswordRequestFormType::class);
  50.         $form->handleRequest($request);
  51.         if ($form->isSubmitted() && $form->isValid()) {
  52.             return $this->processSendingPasswordResetEmail(
  53.                 $form->get('email')->getData(),
  54.                 $mailer,
  55.                 $translator
  56.             );
  57.         }
  58.         return $this->render('reset_password/request.html.twig', [
  59.             'requestForm' => $form->createView(),
  60.         ]);
  61.     }
  62.     /**
  63.      * Confirmation page after a user has requested a password reset.
  64.      *
  65.      * @Route("/check-email", name="app_check_email")
  66.      */
  67.     public function checkEmail(): Response
  68.     {
  69.         // Generate a fake token if the user does not exist or someone hit this page directly.
  70.         // This prevents exposing whether or not a user was found with the given email address or not
  71.         if (null === ($resetToken $this->getTokenObjectFromSession())) {
  72.             $resetToken $this->resetPasswordHelper->generateFakeResetToken();
  73.         }
  74.         return $this->render('reset_password/check_email.html.twig', [
  75.             'resetToken' => $resetToken,
  76.         ]);
  77.     }
  78.     /**
  79.      * Validates and process the reset URL that the user clicked in their email.
  80.      *
  81.      * @Route("/reset/{token}", name="app_reset_password")
  82.      */
  83.     public function reset(Request $requestUserPasswordHasherInterface $userPasswordHasherTranslatorInterface $translatorstring $token null): Response
  84.     {
  85.         if ($token) {
  86.             // We store the token in session and remove it from the URL, to avoid the URL being
  87.             // loaded in a browser and potentially leaking the token to 3rd party JavaScript.
  88.             $this->storeTokenInSession($token);
  89.             return $this->redirectToRoute('app_reset_password');
  90.         }
  91.         $token $this->getTokenFromSession();
  92.         if (null === $token) {
  93.             throw $this->createNotFoundException('No reset password token found in the URL or in the session.');
  94.         }
  95.         try {
  96.             $user $this->resetPasswordHelper->validateTokenAndFetchUser($token);
  97.         } catch (ResetPasswordExceptionInterface $e) {
  98.             $this->addFlash('reset_password_error'sprintf(
  99.                 '%s - %s',
  100.                 $translator->trans(ResetPasswordExceptionInterface::MESSAGE_PROBLEM_VALIDATE, [], 'ResetPasswordBundle'),
  101.                 $translator->trans($e->getReason(), [], 'ResetPasswordBundle')
  102.             ));
  103.             return $this->redirectToRoute('app_forgot_password_request');
  104.         }
  105.         // The token is valid; allow the user to change their password.
  106.         $form $this->createForm(ChangePasswordFormType::class);
  107.         $form->handleRequest($request);
  108.         $formErrors = [];
  109.         if ($form->isSubmitted()) {
  110.             if ($form->isValid()) {
  111.                 // A password reset token should be used only once, remove it.
  112.                 $this->resetPasswordHelper->removeResetRequest($token);
  113.                 // Encode(hash) the plain password, and set it.
  114.                 $encodedPassword $userPasswordHasher->hashPassword(
  115.                     $user,
  116.                     $form->get('plainPassword')->getData()
  117.                 );
  118.                 $user->setPassword($encodedPassword);
  119.                 $this->entityManager->flush();
  120.                 // The session is cleaned up after the password has been changed.
  121.                 $this->cleanSessionAfterReset();
  122.                 return $this->redirectToRoute('app_login');
  123.             } else {
  124.                 foreach ($form as $fieldName => $field) {
  125.                     $fieldErrors $form[$fieldName]->getErrors();
  126.                     if (sizeof($fieldErrors) > 0) {
  127.                         $formErrors[$fieldName] = $fieldErrors[0]->getMessage();
  128.                     }
  129.                 }
  130.             }
  131.         }
  132.         return $this->render('reset_password/reset.html.twig', [
  133.             'resetForm' => $form->createView(),
  134.             'formErrors' => $formErrors
  135.         ]);
  136.     }
  137.     private function processSendingPasswordResetEmail(string $emailFormDataMailerInterface $mailerTranslatorInterface $translator): RedirectResponse
  138.     {
  139.         $user $this->entityManager->getRepository(User::class)->findOneBy([
  140.             'email' => $emailFormData,
  141.         ]);
  142.         // Do not reveal whether a user account was found or not.
  143.         if (!$user) {
  144.             return $this->redirectToRoute('app_check_email');
  145.         }
  146.         try {
  147.             $resetToken $this->resetPasswordHelper->generateResetToken($user);
  148.         } catch (ResetPasswordExceptionInterface $e) {
  149.             // If you want to tell the user why a reset email was not sent, uncomment
  150.             // the lines below and change the redirect to 'app_forgot_password_request'.
  151.             // Caution: This may reveal if a user is registered or not.
  152.             //
  153.             // $this->addFlash('reset_password_error', sprintf(
  154.             //     '%s - %s',
  155.             //     $translator->trans(ResetPasswordExceptionInterface::MESSAGE_PROBLEM_HANDLE, [], 'ResetPasswordBundle'),
  156.             //     $translator->trans($e->getReason(), [], 'ResetPasswordBundle')
  157.             // ));
  158.             return $this->redirectToRoute('app_check_email');
  159.         }
  160.         $resetUrl $this->generateUrl('app_reset_password', ['token' => $resetToken->getToken()], UrlGeneratorInterface::ABSOLUTE_URL);
  161.         $expireInfo $translator->trans($resetToken->getExpirationMessageKey(), $resetToken->getExpirationMessageData(), 'ResetPasswordBundle');
  162. //        dump($resetToken->getExpirationMessageKey());
  163. //        dump($resetToken->getExpirationMessageData());
  164. //        dump($expireInfo);
  165. //        dd($resetUrl);
  166. //        $email = (new TemplatedEmail())
  167. //            ->from(new Address('noreply@dmkzwo.de', 'Wettbewerb HdfH'))
  168. //            ->to($user->getEmail())
  169. //            ->subject('Your password reset request')
  170. //            ->htmlTemplate('reset_password/email.html.twig')
  171. //            ->context([
  172. //                'resetToken' => $resetToken,
  173. //            ]);
  174.         $mailText str_replace(
  175.             ['##reset_link##''##expires_in##'],
  176.             [$resetUrl$expireInfo],
  177.             $this->contentBlockRepository->findByTitle('MAIL_RESET_PASSWORD')
  178.         );
  179.         $this->mailHelper->sendEmail($user->getEmail(), 'Hdfh: Passwort zurücksetzen'$mailText'MAIL_RESET_PASSWORD');
  180. //        $email = (new Email())
  181. //            ->from(new Address('noreply@dmkzwo.de', 'Wettbewerb HdfH'))
  182. //            ->to($user->getEmail())
  183. //            ->subject('Your password reset request')
  184. //            ->text()
  185. //            ->htmlTemplate('reset_password/email.html.twig')
  186. //            ->context([
  187. //                'resetToken' => $resetToken,
  188. //            ]);
  189. //
  190. //        $mailer->send($email);
  191.         // Store the token object in session for retrieval in check-email route.
  192.         $this->setTokenObjectInSession($resetToken);
  193. //        $this->addFlash('success', 'Eine E-Mail wurde an Ihre Adresse geschickt.');
  194.         return $this->redirectToRoute('app_check_email');
  195.     }
  196. }