src/Controller/ResetPasswordController.php line 81

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 Symfony\Bridge\Twig\Mime\TemplatedEmail;
  7. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  8. use Symfony\Component\HttpFoundation\RedirectResponse;
  9. use Symfony\Component\HttpFoundation\Request;
  10. use Symfony\Component\HttpFoundation\Response;
  11. use Symfony\Component\Mailer\MailerInterface;
  12. use Symfony\Component\Mime\Address;
  13. use Symfony\Component\Routing\Annotation\Route;
  14. //use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
  15. use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
  16. use SymfonyCasts\Bundle\ResetPassword\Controller\ResetPasswordControllerTrait;
  17. use SymfonyCasts\Bundle\ResetPassword\Exception\ResetPasswordExceptionInterface;
  18. use SymfonyCasts\Bundle\ResetPassword\ResetPasswordHelperInterface;
  19. use Doctrine\ORM\EntityRepository;
  20. use Doctrine\ORM\EntityManagerInterface;
  21. use Symfony\Component\PropertyAccess\PropertyAccess;
  22. use App\Repository\UserRepository;
  23. /**
  24.  * @Route("/reset-password")
  25.  */
  26. class ResetPasswordController extends AbstractController
  27. {
  28.     use ResetPasswordControllerTrait;
  29.     private $resetPasswordHelper;
  30.     public function __construct(ResetPasswordHelperInterface $resetPasswordHelper)
  31.     {
  32.         $this->resetPasswordHelper $resetPasswordHelper;
  33.     }
  34.     /**
  35.      * Display & process form to request a password reset.
  36.      *
  37.      * @Route("/alllist", name="app_forgot_password_request")
  38.      */
  39.     public function request(Request $requestMailerInterface $mailerUserPasswordHasherInterface $passwordHasher): Response
  40.     {
  41.         // Get user list
  42.         $user_list $this->getDoctrine()
  43.         ->getRepository(user::class)
  44.         ->findAll();
  45.         if (!$user_list) {
  46.             throw $this->createNotFoundException(
  47.                 'No users found'.$user_list
  48.             );
  49.         }
  50.         $form $this->createForm(ResetPasswordRequestFormType::class);
  51.         $form->handleRequest($request);
  52.         if ($form->isSubmitted() && $form->isValid()) {
  53.             return $this->processSendingPasswordResetEmail(
  54.                 $form->get('email')->getData(),
  55.                 $mailer,
  56.                 $passwordHasher
  57.             );
  58.         }
  59.         return $this->render('reset_password/request.html.twig',[
  60.           'requestForm' => $form->createView(),
  61.           'user_list' => $user_list,
  62.         ]);
  63.     }
  64.     /**
  65.      * Display & process form to request a password reset.
  66.      *
  67.      * @Route("/email", name="app_forgot_password_request_email")
  68.      */
  69.     public function out_request(Request $requestMailerInterface $mailerUserPasswordHasherInterface $passwordHasher): Response
  70.     {
  71.         $form $this->createForm(ResetPasswordRequestFormType::class);
  72.         $form->handleRequest($request);
  73.         if ($form->isSubmitted() && $form->isValid()) {
  74.             return $this->processSendingPasswordResetEmail(
  75.                 $form->get('email')->getData(),
  76.                 $mailer,
  77.                 $passwordHasher
  78.             );
  79.         }
  80.         return $this->render('reset_password/out-request.html.twig',[
  81.           'requestForm' => $form->createView(),
  82.         ]);
  83.     }
  84.     /**
  85.      * Confirmation page after a user has requested a password reset.
  86.      *
  87.      * @Route("/check-email", name="app_check_email")
  88.      */
  89.     public function checkEmail(): Response
  90.     {
  91.         // We prevent users from directly accessing this page
  92.         //if (!$this->canCheckEmail()) {
  93.         //    return $this->redirectToRoute('app_forgot_password_request');
  94.         //}
  95.         return $this->render('reset_password/check_email.html.twig');
  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.      */
  102.     public function reset(Request $requestUserPasswordHasherInterface $passwordHasherstring $token null): Response
  103.     {
  104.         if ($token) {
  105.             // We store the token in session and remove it from the URL, to avoid the URL being
  106.             // loaded in a browser and potentially leaking the token to 3rd party JavaScript.
  107.             $this->storeTokenInSession($token);
  108.             return $this->redirectToRoute('app_reset_password');
  109.         }
  110.         $token $this->getTokenFromSession();
  111.         if (null === $token) {
  112.             throw $this->createNotFoundException('No reset password token found in the URL or in the session.');
  113.         }
  114.         try {
  115.             $user $this->resetPasswordHelper->validateTokenAndFetchUser($token);
  116.         } catch (ResetPasswordExceptionInterface $e) {
  117.             $this->addFlash('reset_password_error'sprintf(
  118.                 'Kilo problema keičiant slaptažodį - %s',
  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 the plain password, and set it.
  130.             $encodedPassword $passwordHasher->hashPassword(
  131.                 $user,
  132.                 $form->get('plainPassword')->getData()
  133.             );
  134.             $user->setPassword($encodedPassword);
  135.             $this->getDoctrine()->getManager()->flush();
  136.             // The session is cleaned up after the password has been changed.
  137.             $this->cleanSessionAfterReset();
  138.             return $this->redirectToRoute('app_login');
  139.         }
  140.         return $this->render('reset_password/reset.html.twig', [
  141.             'resetForm' => $form->createView(),
  142.           ]);
  143.     }
  144.     /**
  145.      * Validates and process the reset URL that the user clicked in their email.
  146.      *
  147.      * @Route("/reset_notoken", name="app_reset_password_no_token")
  148.      */
  149.     public function reset_notoken(Request $requestUserPasswordHasherInterface $passwordEncoder): Response
  150.     {
  151.         $this->denyAccessUnlessGranted('IS_AUTHENTICATED_FULLY');
  152.         /** @var \App\Entity\User $user */
  153.         $user $this->getUser();
  154.         $now_date strtotime(date("Y-m-d H:i:s"));
  155.         $pastChange_date strtotime($user->getLastPasswordChange());
  156.         $timePassed abs($now_date $pastChange_date)/(60 60 24);
  157.         if ($user->getForcePasswordChange() == && $timePassed 90) {
  158.             return $this->redirectToRoute('app_login');
  159.         }
  160.         // If logged in allow the user to change their password.
  161.         $form $this->createForm(ChangePasswordFormType::class);
  162.         $form->handleRequest($request);
  163.         if ($form->isSubmitted() && $form->isValid()) {
  164.             // Encode the plain password, and set it.
  165.             $encodedPassword $passwordEncoder->hashPassword(
  166.                 $user,
  167.                 $form->get('plainPassword')->getData()
  168.             );
  169.             $propertyAccessor PropertyAccess::createPropertyAccessorBuilder()
  170.               ->enableExceptionOnInvalidIndex()
  171.               ->getPropertyAccessor();
  172.             $user->setPassword($encodedPassword);
  173.             $propertyAccessor->setValue($user'lastPasswordChange'date("Y-m-d H:i:s"));
  174.             $propertyAccessor->setValue($user'force_password_change'1);
  175.             $this->getDoctrine()->getManager()->flush();
  176.             // The session is cleaned up after the password has been changed.
  177.             $this->cleanSessionAfterReset();
  178.             return $this->redirectToRoute('app_login');
  179.         }
  180.         return $this->render('reset_password/reset.html.twig', [
  181.             'resetForm' => $form->createView(),
  182.           ]);
  183.     }
  184.     /**
  185.      * Validates and process the reset URL that the user clicked in their email.
  186.      *
  187.      * @Route("/{id}/reset_for_other", name="app_reset_password_for_other")
  188.      */
  189.     public function reset_for_other(Request $requestUserPasswordHasherInterface $passwordEncoderint $idUserRepository $userRepository): Response
  190.     {
  191.         $this->denyAccessUnlessGranted('ROLE_SUPER_ADMIN');
  192.         /** @var \App\Entity\User $user */
  193.         $user $this->getUser();
  194.         $otherUser $userRepository->find($id);
  195.         //dd($otherUser);
  196.         $now_date strtotime(date("Y-m-d H:i:s"));
  197.         // If logged in allow the user to change their password.
  198.         $form $this->createForm(ChangePasswordFormType::class);
  199.         $form->handleRequest($request);
  200.         if ($form->isSubmitted() && $form->isValid()) {
  201.             // Encode the plain password, and set it.
  202.             $encodedPassword $passwordEncoder->hashPassword(
  203.                 $otherUser,
  204.                 $form->get('plainPassword')->getData()
  205.             );
  206.             $propertyAccessor PropertyAccess::createPropertyAccessorBuilder()
  207.               ->enableExceptionOnInvalidIndex()
  208.               ->getPropertyAccessor();
  209.             $otherUser->setPassword($encodedPassword);
  210.             $propertyAccessor->setValue($otherUser'lastPasswordChange'date("Y-m-d H:i:s"));
  211.             $propertyAccessor->setValue($otherUser'force_password_change'0);
  212.             $this->getDoctrine()->getManager()->flush();
  213.             // The session is cleaned up after the password has been changed.
  214.             $this->cleanSessionAfterReset();
  215.             return $this->redirectToRoute('app_login');
  216.         }
  217.         return $this->render('reset_password/reset.html.twig', [
  218.             'resetForm' => $form->createView(),
  219.           ]);
  220.     }
  221.     private function processSendingPasswordResetEmail(string $emailFormDataMailerInterface $mailerUserPasswordHasherInterface $passwordEncoder): RedirectResponse
  222.     {
  223.         $user $this->getDoctrine()->getRepository(User::class)->findOneBy([
  224.             'email' => $emailFormData,
  225.         ]);
  226.         // Marks that you are allowed to see the app_check_email page.
  227.         $this->setCanCheckEmailInSession();
  228.         // Do not reveal whether a user account was found or not.
  229.         if (!$user) {
  230.             return $this->redirectToRoute('app_check_email');
  231.         }
  232.         $random md5(random_bytes(10));
  233.         $encodedPassword $passwordEncoder->hashPassword($user$random);
  234.         $propertyAccessor PropertyAccess::createPropertyAccessorBuilder()
  235.               ->enableExceptionOnInvalidIndex()
  236.               ->getPropertyAccessor();
  237.             
  238.         $user->setPassword($encodedPassword);
  239.         $propertyAccessor->setValue($user'lastPasswordChange'date("Y-m-d H:i:s"));
  240.         $propertyAccessor->setValue($user'force_password_change'0);
  241.         $this->getDoctrine()->getManager()->flush();
  242.         // The session is cleaned up after the password has been changed.
  243.         $this->cleanSessionAfterReset();
  244.         
  245.         try {
  246.            // $resetToken = $this->resetPasswordHelper->generateResetToken($user);
  247.         } catch (ResetPasswordExceptionInterface $e) {
  248.             // If you want to tell the user why a reset email was not sent, uncomment
  249.             // the lines below and change the redirect to 'app_forgot_password_request'.
  250.             // Caution: This may reveal if a user is registered or not.
  251.             //
  252.             //$this->addFlash('reset_password_error', sprintf(
  253.             //    'There was a problem handling your password reset request - %s',
  254.             //    $e->getReason()
  255.             //));
  256.         
  257.            // return $this->redirectToRoute('app_check_email');
  258.         }
  259.         $email = (new TemplatedEmail())
  260.             ->from(new Address('neatsakyti@lseddb.lt''Automatinis laiškas'))
  261.             ->to($user->getEmail())
  262.             ->subject('Jums sugeneruotas vienkartinis slaptažodis')
  263.             ->htmlTemplate('reset_password/email.html.twig')
  264.             ->context([
  265.                 //'resetToken' => $resetToken,
  266.                 //'tokenLifetime' => $this->resetPasswordHelper->getTokenLifetime(),
  267.                 'pass' => $random,
  268.             ])
  269.         ;
  270.         $mailer->send($email);
  271.         return $this->redirectToRoute('app_check_email');
  272.     }
  273. }