src/Controller/SecurityController.php line 59

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\Entity\User;
  4. use App\Form\ForgotType;
  5. use App\Form\ForgotPassType;
  6. use App\Repository\UserRepository;
  7. use Symfony\Component\Mime\Address;
  8. use Doctrine\ORM\EntityManagerInterface;
  9. use Symfony\Bridge\Twig\Mime\TemplatedEmail;
  10. use Symfony\Component\HttpFoundation\Request;
  11. use Symfony\Component\Mailer\MailerInterface;
  12. use Symfony\Component\HttpFoundation\Response;
  13. use Symfony\Component\Routing\Annotation\Route;
  14. use Symfony\Component\HttpFoundation\JsonResponse;
  15. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  16. use Symfony\Component\Mailer\Exception\TransportExceptionInterface;
  17. use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
  18. use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
  19. use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
  20. class SecurityController extends AbstractController
  21. {
  22.     private $params;
  23.     public function __construct(ParameterBagInterface $params)
  24.     {
  25.         $this->params $params;
  26.     }
  27.     /**
  28.      * @Route("/login", name="app_login")
  29.      */
  30.     public function login(AuthenticationUtils $authenticationUtils): Response
  31.     {
  32.         if ($this->getUser()) {
  33.             return $this->redirectToRoute('app_home_page');
  34.         }
  35.         // get the login error if there is one
  36.         $error $authenticationUtils->getLastAuthenticationError();
  37.         // last username entered by the user
  38.         $lastUsername $authenticationUtils->getLastUsername();
  39.         return $this->render('security/login.html.twig', ['last_username' => $lastUsername'error' => $error]);
  40.     }
  41.     /**
  42.      * @Route("/logout", name="app_logout")
  43.      */
  44.     public function logout(): void
  45.     {
  46.         throw new \LogicException('This method can be blank - it will be intercepted by the logout key on your firewall.');
  47.     }
  48.     /**
  49.      * @Route("/forgot-password", name="app_forgot_password")
  50.      */
  51.     public function forgot(): Response
  52.     {
  53.         $form $this->createForm(ForgotType::class,[
  54.             'action' => $this->generateUrl('app_forgot_pass_submit'),
  55.             'method' => 'POST',
  56.             'id' => 'test'
  57.         ]);
  58.         
  59.         return $this->render('security/forgotPassword.html.twig', [
  60.             'form' => $form->createView(),
  61.         ]);
  62.     }
  63.     /**
  64.      * @Route("/forgot-password-submit", name="app_forgot_pass_submit", methods={"POST"})
  65.      */
  66.     public function forgotSubmit(Request $requestUserRepository $userRepositoryMailerInterface $mailer,EntityManagerInterface $entityManager)
  67.     {
  68.         $data $request->request->get('forgot');
  69.         $status "error";
  70.         $message "";
  71.         $title "Mot de passe oublié";
  72.         if ($data) {
  73.             $email $data["email"];
  74.             // vérifier si c'est un email valid en PHP
  75.             if (!filter_var($emailFILTER_VALIDATE_EMAIL)) {
  76.                 $message "Format email invalid";
  77.             } else {
  78.                 // récupération de l'utilisateur contenant l'email
  79.                 $user $userRepository->findOneBy(['email' => $email]);
  80.                 if ($user instanceof User) {
  81.                     $now = new \DateTime();
  82.                     // dd($now,$this->params);
  83.                     $string $this->params->get("encryption.salt.reset_password").$now->format("YmdHim")."_".$user->getId();
  84.                     $key urlencode(base64_encode($string));
  85.                     // Envoi mail si pas d'erreur
  86.                     $toAddresses = [new Address($user->getEmail())];
  87.                     $email = (new TemplatedEmail())
  88.                         ->to(...$toAddresses)
  89.                         ->subject('Mot de passe oublié')
  90.                         // path of the Twig template to render
  91.                         ->htmlTemplate('mailer/change_password.html.twig')
  92.                         // pass variables (name => value) to the template
  93.                         ->context([
  94.                             'now' => $now,
  95.                             'username' => $user->getFirstname(),
  96.                             'key' => $key
  97.                         ]);
  98.                         $user->setDateSendResetPassword($now);
  99.                         $entityManager->persist($user);
  100.                         $entityManager->flush();
  101.                     try {
  102.                         $mailer->send($email);
  103.                         // mise à jour date reset password
  104.                         $user->setDateSendResetPassword($now);
  105.                         $entityManager->persist($user);
  106.                         $entityManager->flush();                     
  107.                         $status "success";
  108.                         $message "Veuillez vérifier votre email pour modifier votre mot de passe";
  109.                     } catch (TransportExceptionInterface $e) {                        
  110.                         $status "error";
  111.                         $message "Envoi mail echoué, verifiez votre connexion";
  112.                             // throw new Exception($e, 1);
  113.                     }
  114.                     
  115.                 } else {
  116.                     $message "Email utilisateur non trouvé dans la base";
  117.                 }
  118.             }
  119.             
  120.         } else {
  121.             $message "Aucune données posté par la méthode";
  122.         }
  123.         // return new JsonResponse(
  124.         //     [
  125.         //         'title' => $title,
  126.         //         'message' => $message,
  127.         //         'status' => $status,
  128.         //     ],
  129.         //     200,
  130.         //     ['Content-Type' => 'application/json']
  131.         // );
  132.          return $this->render('mailer/page.html.twig',[
  133.             'title' => $title,
  134.             'message' => $message,
  135.             'status' => $status
  136.          ]);
  137.     }
  138.     /**
  139.      * @Route("/forgot-send-url/{key}", name="app_forgot_send_url")
  140.      */
  141.     public function forgotSendUrl(String $keyUserRepository $userRepository)
  142.     {
  143.         // decodé l'URL
  144.         $string base64_decode(urldecode($key));
  145.         // enlever le SALT de l(URL)
  146.         $string str_ireplace($this->params->get("encryption.salt.reset_password"), ""$string);
  147.         // récupérer la date et l'ID de l'utilisateur
  148.         $string explode("_"$string);
  149.         $dateUrl $string[0];
  150.         $user_id = (int)$string[1];
  151.         $user $userRepository->find($user_id);
  152.         if($user instanceof User && !empty($user->getDateSendResetPassword())) {
  153.             $dateUrlUser $user->getDateSendResetPassword();
  154.             $dateUrlUser $dateUrlUser->format("YmdHim");
  155.             if($dateUrl == $dateUrlUser){
  156.                 $form $this->createForm(ForgotPassType::class, $user, [
  157.                     'action' => $this->generateUrl('app_forgot_send_url_submit'),
  158.                     'method' => 'POST'
  159.                 ]);
  160.         
  161.                 return $this->render('security/forgotPassForm.html.twig', [
  162.                     'form' => $form->createView(),
  163.                     'id' => $user->getId(),
  164.                 ]);
  165.             }
  166.             else{
  167.                 throw $this->createNotFoundException('Lien expiré teou inexistant');
  168.             }
  169.             
  170.         }
  171.         else{
  172.             throw $this->createNotFoundException('Lien expiré ou inexistant');
  173.         }
  174.         
  175.     }
  176.     /**
  177.      * @Route("/forgot-send-url-submit", name="app_forgot_send_url_submit", methods={"POST"})
  178.      */
  179.     public function forgotSendUrlSubmit(Request $requestUserRepository $userRepositoryMailerInterface $mailerUserPasswordEncoderInterface $passwordEncoder,EntityManagerInterface $entityManager)
  180.     {
  181.         $data $request->request->get('forgot_pass');
  182.         $user_id = (int)$request->request->get('user_id');
  183.         $status "error";
  184.         $message "";
  185.         if ($data) {
  186.             $user $userRepository->find($user_id);
  187.             if($user instanceof User){
  188.                 $email $user->getEmail();
  189.                 // vérifier si c'est un email valid en PHP
  190.                 if (!filter_var($emailFILTER_VALIDATE_EMAIL)) {
  191.                     $message "Format email invalid";
  192.                 } else {
  193.                     // récupération de l'utilisateur contenant l'email
  194.                     $user $userRepository->findOneBy(['email' => $email]);
  195.                     if ($user instanceof User) {
  196.                         $string1 $data["password"]["first"];
  197.                         $string2 $data["password"]["second"];
  198.                         // On vérifie si c'est le même mot de passe
  199.                         if ($string1 == $string2) {
  200.                             // Envoi mail si pas d'erreur
  201.                             $toAddresses = [new Address($user->getEmail())];
  202.                             $email = (new TemplatedEmail())
  203.                                 ->to(...$toAddresses)
  204.                                 ->subject('Mot de passe oublié')
  205.                                 // path of the Twig template to render
  206.                                 ->htmlTemplate('mailer/send_password.html.twig')
  207.                                 // pass variables (name => value) to the template
  208.                                 ->context([
  209.                                     'now' => new \DateTime(),
  210.                                     'username' => $user->getFirstname(),
  211.                                     'random_string' => $string1
  212.                                 ]);
  213.                             try {
  214.                                 $mailer->send($email);
  215.                             } catch (TransportExceptionInterface $e) {
  216.                                 // throw new Exception($e, 1);
  217.                             }
  218.                             // encode the plain password
  219.                             $user->setPassword(
  220.                                 $passwordEncoder->encodePassword(
  221.                                     $user,
  222.                                     $string1
  223.                                 )
  224.                             );
  225.                             // mot de passe oublié permettant de désactiver l'URL dans le mail
  226.                             $user->setDateSendResetPassword(null);
  227.                             $entityManager->persist($user);
  228.                             $entityManager->flush();
  229.                             $status "success";
  230.                             $message "Enregistrement effectué avec succès, veuillez vérifier votre email";
  231.                         } else {
  232.                             $message "Mot de passe incorrecte";
  233.                         }
  234.                     } else {
  235.                         $message "Email utilisateur non trouvé dans la base";
  236.                     }
  237.                 }
  238.             }
  239.             else{
  240.                 $message "Utilisateur inexistant ou non reconnu par l'application";
  241.             }
  242.             
  243.         } else {
  244.             $message "Aucune données posté par la méthode";
  245.         }
  246.         return $this->redirectToRoute('app_login');
  247.     }
  248. }