src/Controller/ResetPasswordController.php line 47

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\Entity\User;
  4. use App\Form\ChangePasswordFormType;
  5. use App\Form\PasswordResetType;
  6. use App\Form\ResetPasswordRequestFormType;
  7. use App\Service\EmailService;
  8. use App\Service\SettingsService;
  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\Routing\Annotation\Route;
  15. use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
  16. use SymfonyCasts\Bundle\ResetPassword\Controller\ResetPasswordControllerTrait;
  17. use SymfonyCasts\Bundle\ResetPassword\Exception\ResetPasswordExceptionInterface;
  18. use SymfonyCasts\Bundle\ResetPassword\ResetPasswordHelperInterface;
  19. /**
  20.  * @Route("/odzyskaj-haslo")
  21.  */
  22. class ResetPasswordController extends AbstractController
  23. {
  24.     use ResetPasswordControllerTrait;
  25.     private $resetPasswordHelper;
  26.     private $passwordEncoder;
  27.     private $email;
  28.     private $setting;
  29.     public function __construct(ResetPasswordHelperInterface $resetPasswordHelperSettingsService $settingsServiceUserPasswordEncoderInterface $passwordEncoderEmailService $emailService)
  30.     {
  31.         $this->resetPasswordHelper $resetPasswordHelper;
  32.         $this->passwordEncoder $passwordEncoder;
  33.         $this->email $emailService;
  34.         $this->setting $settingsService;
  35.     }
  36.     /**
  37.      * Display & process form to request a password reset.
  38.      *
  39.      * @Route("", name="app_forgot_password_request")
  40.      */
  41.     public function request(Request $requestMailerInterface $mailer): Response
  42.     {
  43.         $form $this->createForm(ResetPasswordRequestFormType::class);
  44.         $form->handleRequest($request);
  45.         if ($form->isSubmitted() && $form->isValid()) {
  46.             return $this->processSendingPasswordResetEmail(
  47.                 $form->get('email')->getData(),
  48.                 $mailer
  49.             );
  50.         }
  51.         return $this->render('panel/resetPassword/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('panel/resetPassword/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('panel/resetPassword/reset.html.twig', [
  114.             'resetForm' => $form->createView(),
  115.         ]);
  116.     }
  117.     private function processSendingPasswordResetEmail(string $emailFormDataMailerInterface $mailer): RedirectResponse
  118.     {
  119.         $user $this->getDoctrine()->getRepository(User::class)->findOneBy([
  120.             'email' => $emailFormData,
  121.         ]);
  122.         // Marks that you are allowed to see the app_check_email page.
  123.         $this->setCanCheckEmailInSession();
  124.         // Do not reveal whether a user account was found or not.
  125.         if (!$user) {
  126.             return $this->redirectToRoute('app_check_email');
  127.         }
  128.         try {
  129.             $resetToken $this->resetPasswordHelper->generateResetToken($user);
  130.         } catch (ResetPasswordExceptionInterface $e) {
  131.             // If you want to tell the user why a reset email was not sent, uncomment
  132.             // the lines below and change the redirect to 'app_forgot_password_request'.
  133.             // Caution: This may reveal if a user is registered or not.
  134.             //
  135.             $this->addFlash('reset_password_error'sprintf(
  136.                 'There was a problem handling your password reset request - %s',
  137.                 $e->getReason()
  138.             ));
  139.             return $this->redirectToRoute('app_check_email');
  140.         }
  141.         $dateLifetime = new \DateTime($this->resetPasswordHelper->getTokenLifetime());
  142.         $return $this->email->post([
  143.             'to' => $user->getEmail(),
  144.             'to_label' => $user->getUserData()->getName().' '.$user->getUserData()->getLastName(),
  145.             'subject' => 'Odzyskiwanie hasła',
  146.             'message' => 'Otrzymaliśmy prośbę o zmianę Twojego hasła. Jeśli to Ty wysłałeś tą prośbę kliknij w poniższy link:<br>
  147. <a href="'.$this->generateUrl('app_reset_password', ['token' => $resetToken->getToken()], false).'">Odzyskaj haslo</a>.<br>
  148.     <p style="color: grey;"><small>(link wygaśnie po '.$dateLifetime->format('g').' godzinach)</small></p><br><br>
  149.     Jeśli link nie działa skopiuj poniższy adres do okna przeglądarki:<br>
  150.     <small>'.$this->generateUrl('app_reset_password', ['token' => $resetToken->getToken()], false).'</small>
  151.     </p>',
  152.         ]);
  153.         return $this->redirectToRoute('app_check_email');
  154.     }
  155.     /**
  156.      * @Route("/zmien", name="app_password_reset")
  157.      */
  158.     public function passwordReset(Request $requestUserPasswordEncoderInterface $passwordEncoderstring $token null): Response
  159.     {
  160.         $user $this->getUser();
  161.         $form $this->createForm(PasswordResetType::class);
  162.         $form->handleRequest($request);
  163.         if ($form->isSubmitted()) {
  164.             if ($form->get('plainPassword')->getData()) {
  165.                 // Sprawdzam czy stare hasło jest prawidłowe, jeżeli tak, daje możliwwość zmiany hasła
  166.                 if (true === $this->passwordEncoder->isPasswordValid($user$form->get('oldPassword')->getData())) {
  167.                     $encodedPassword $passwordEncoder->encodePassword(
  168.                         $user,
  169.                         $form->get('plainPassword')->getData()
  170.                     );
  171.                     $user->setPassword($encodedPassword);
  172.                     $this->getDoctrine()->getManager()->flush();
  173.                     $this->addFlash('success''Hasło zostało zmienione.');
  174.                     return $this->redirectToRoute('app_password_reset');
  175.                 } else {
  176.                     $this->addFlash('danger''Wpisz poprawni obecne hasło');
  177.                     return $this->redirectToRoute('app_password_reset');
  178.                 }
  179.             } else {
  180.                 $this->addFlash('danger''Podane hasła muszą być identyczne');
  181.                 return $this->redirectToRoute('app_password_reset');
  182.             }
  183.         }
  184.         return $this->render('panel/resetPassword/passwordReset.html.twig', [
  185.             'resetForm' => $form->createView(),
  186.         ]);
  187.     }
  188. }