src/Controller/ResetPasswordController.php line 111

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\Entity\SiteAdmin;
  4. use App\Entity\User;
  5. use App\Form\ChangePasswordFormType;
  6. use App\Form\ResetPasswordRequestFormType;
  7. use Doctrine\ORM\EntityManagerInterface;
  8. use Symfony\Bridge\Twig\Mime\TemplatedEmail;
  9. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  10. use Symfony\Component\DependencyInjection\ContainerInterface;
  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 Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
  19. use Symfony\Component\String\Slugger\AsciiSlugger;
  20. use SymfonyCasts\Bundle\ResetPassword\Controller\ResetPasswordControllerTrait;
  21. use SymfonyCasts\Bundle\ResetPassword\Exception\ResetPasswordExceptionInterface;
  22. use SymfonyCasts\Bundle\ResetPassword\ResetPasswordHelperInterface;
  23. /**
  24.  * @Route("/reset-password")
  25.  */
  26. class ResetPasswordController extends AbstractController
  27. {
  28.     use ResetPasswordControllerTrait;
  29.     private $resetPasswordHelper;
  30.     private $mycontainer;
  31.     private $translationFolder;
  32.     private $em;
  33.     private $uploadDirectory;
  34.     private $siteInfo;
  35.     private $locale;
  36.     private $translator;
  37.     private $encoder;
  38.     private $cacheTranslationFolder;
  39.     private $slugger;
  40.     private $valid_ext;
  41.     public function __construct(ResetPasswordHelperInterface $resetPasswordHelperContainerInterface $cEntityManagerInterface $emUserPasswordEncoderInterface $encoder)
  42.     {
  43.         $this->resetPasswordHelper $resetPasswordHelper;
  44.         $this->mycontainer $c;
  45.         $this->encoder $encoder;
  46.         $this->em $em;
  47.         $this->translationFolder __DIR__.'/../../translations/';
  48.         $this->uploadDirectory $c->get("kernel")->getProjectDir()."/public/uploads";
  49.         $this->cacheTranslationFolder __DIR__.'/../../var/cache/prod/translations';
  50.         $this->translator $c->get('translator');
  51.         $this->slugger = new AsciiSlugger();
  52.         $this->valid_ext = array('png','jpeg','jpg','PNG','JPG','JPEG');
  53.         $info = ['country'=>'',
  54.             'languages'=>[],
  55.         ];
  56.         $site $this->em->getRepository(SiteAdmin::class)->findOneBy([]);
  57.         if($site !== null){
  58.             $info = [
  59.                 'country'=>$site->getCountry(),
  60.                 'languages'=>$site->getLanguages()
  61.             ];
  62.         }
  63.         $this->siteInfo $info;
  64.         $lang $this->mycontainer->get('request_stack')->getCurrentRequest()->cookies->get('lang');
  65.         if(in_array($lang,$info['languages'])) {
  66.             $this->translator->setLocale($lang);
  67.             $this->locale $lang;
  68.         }
  69.         else{
  70.             $this->mycontainer->get('request_stack')->getCurrentRequest()->cookies->set('lang','first');
  71.             $this->translator->setLocale('first');
  72.         }
  73.     }
  74.     /**
  75.      * Display & process form to request a password reset.
  76.      * @param Request $request
  77.      * @param MailerInterface $mailer
  78.      * @return Response
  79.      */
  80.     public function request(Request $requestMailerInterface $mailer): Response
  81.     {
  82.         $form $this->createForm(ResetPasswordRequestFormType::class);
  83.         $form->handleRequest($request);
  84.         if($request->getMethod()=="POST"){
  85.             $email $request->request->get("email");
  86.             $submittedToken $request->request->get('csrf');
  87.             if (!$this->isCsrfTokenValid('csrf'$submittedToken))
  88.             {
  89.                 $this->addFlash('reset_password_error',$this->mycontainer->get('translator')->trans('invalid_csrf'));
  90.                 $this->redirectToRoute('app_forgot_password_request');
  91.             }
  92.             if($email === null){
  93.                 return $this->render('reset_password/request.html.twig'$this->siteInfo);
  94.             }
  95.             return $this->processSendingPasswordResetEmail(
  96.                 $email,
  97.                 $mailer
  98.             );
  99.         }
  100.         return $this->render('reset_password/request.html.twig'$this->siteInfo);
  101.     }
  102.     /**
  103.      * Confirmation page after a user has requested a password reset.
  104.      */
  105.     public function checkEmail(): Response
  106.     {
  107.         // Generate a fake token if the user does not exist or someone hit this page directly.
  108.         // This prevents exposing whether or not a user was found with the given email address or not
  109.         if (null === ($resetToken $this->getTokenObjectFromSession())) {
  110.             $resetToken $this->resetPasswordHelper->generateFakeResetToken();
  111.         }
  112.         $dd abs((new \DateTime())->getTimestamp() - $resetToken->getExpiresAt()->getTimestamp()) / 60;
  113.         $this->siteInfo['resetToken']=$resetToken;
  114.         $this->siteInfo['time']=$dd;
  115.         return $this->render('reset_password/check_email.html.twig'$this->siteInfo);
  116.     }
  117.     /**
  118.      * Validates and process the reset URL that the user clicked in their email.
  119.      * @param Request $request
  120.      * @param UserPasswordHasherInterface $userPasswordHasher
  121.      * @param EntityManagerInterface $entityManager
  122.      * @param string|null $token
  123.      * @return Response
  124.      */
  125.     public function reset(Request $requestUserPasswordHasherInterface $userPasswordHasherstring $token null): Response
  126.     {
  127.         if ($token) {
  128.             // We store the token in session and remove it from the URL, to avoid the URL being
  129.             // loaded in a browser and potentially leaking the token to 3rd party JavaScript.
  130.             $this->storeTokenInSession($token);
  131.             return $this->redirectToRoute('app_reset_password_simple');
  132.         }
  133.         $token $this->getTokenFromSession();
  134.         if (null === $token) {
  135.             throw $this->createNotFoundException('No reset password token found in the URL or in the session.');
  136.         }
  137.         try {
  138.             $user $this->resetPasswordHelper->validateTokenAndFetchUser($token);
  139.         } catch (ResetPasswordExceptionInterface $e) {
  140.             $this->addFlash('reset_password_error'$this->translator->trans('reset_password_msg_error_link'));
  141.             return $this->redirectToRoute('app_forgot_password_request');
  142.         }
  143.         // The token is valid; allow the user to change their password.
  144.         if ($request->getMethod()=="POST") {
  145.             $password $request->request->get("password");
  146.             $rpassword $request->request->get("confirm-password");
  147.             if(strlen($password) < || strlen($rpassword) < 6)
  148.             {
  149.                 $this->addFlash('reset_password_form'$this->translator->trans('invalid_password'));
  150.                 return $this->redirectToRoute('app_reset_password_simple');
  151.             }
  152.             if($password !== $rpassword){
  153.                 $this->addFlash('reset_password_form'$this->translator->trans('password_mismatch'));
  154.                 return $this->redirectToRoute('app_reset_password_simple');
  155.             }
  156.             if(!$this->mycontainer->get('user_manager')->passwordStrength($password)){
  157.                 $this->addFlash('reset_password_form'$this->translator->trans('invalid_password'));
  158.                 return $this->redirectToRoute('app_reset_password_simple');
  159.             }
  160.             // A password reset token should be used only once, remove it.
  161.             $this->resetPasswordHelper->removeResetRequest($token);
  162.             // Encode(hash) the plain password, and set it.
  163.             $encodedPassword $userPasswordHasher->hashPassword(
  164.                 $user,
  165.                 $password
  166.             );
  167.             $user->setPassword($encodedPassword);
  168.             $this->em->flush();
  169.             // The session is cleaned up after the password has been changed.
  170.             $this->cleanSessionAfterReset();
  171.             $this->addFlash('notice'$this->translator->trans('password_updated'));
  172.             return $this->redirectToRoute('index');
  173.         }
  174.         return $this->render('reset_password/reset.html.twig'$this->siteInfo);
  175.     }
  176.     private function processSendingPasswordResetEmail(string $emailFormDataMailerInterface $mailer): RedirectResponse
  177.     {
  178.         $user $this->em->getRepository(User::class)->findOneBy([
  179.             'email' => $emailFormData,
  180.         ]);
  181.         // Do not reveal whether a user account was found or not.
  182.         if (!$user) {
  183.             return $this->redirectToRoute('app_check_email');
  184.         }
  185.         try {
  186.             $resetToken $this->resetPasswordHelper->generateResetToken($user);
  187.         } catch (ResetPasswordExceptionInterface $e) {
  188.             // If you want to tell the user why a reset email was not sent, uncomment
  189.             // the lines below and change the redirect to 'app_forgot_password_request'.
  190.             // Caution: This may reveal if a user is registered or not.
  191.             //
  192.             // $this->addFlash('reset_password_error', sprintf(
  193.             //     'There was a problem handling your password reset request - %s',
  194.             //     $e->getReason()
  195.             // ));
  196.             return $this->redirectToRoute('app_check_email');
  197.         }
  198.         $this->mycontainer->get('mail_manager')->resetPassword($user->getEmail(),$resetToken);
  199.         // Store the token object in session for retrieval in check-email route.
  200.         $this->setTokenObjectInSession($resetToken);
  201.         return $this->redirectToRoute('app_check_email');
  202.     }
  203. }