src/Controller/SecurityController.php line 69

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\Form\ChangePasswordType;
  4. use App\Service\Mail\MailHandler;
  5. use App\Share\Entity\PasswordLink;
  6. use App\Share\Entity\UserPasswordLink;
  7. use App\Share\Repository\UserPasswordLinkRepository;
  8. use App\Share\Repository\UserRepository;
  9. use App\Traits\UtilsTrait;
  10. use Psr\Log\LoggerInterface;
  11. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  12. use Symfony\Component\HttpFoundation\Request;
  13. use Symfony\Component\HttpFoundation\Response;
  14. use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
  15. use Symfony\Component\Routing\Annotation\Route;
  16. use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
  17. class SecurityController extends AbstractController
  18. {
  19.     use UtilsTrait;
  20.     /**
  21.      * @var MailHandler
  22.      */
  23.     private $mailHandler;
  24.     /**
  25.      * @var LoggerInterface
  26.      */
  27.     private $logger;
  28.     /**
  29.      * @var UserPasswordHasherInterface
  30.      */
  31.     private $encoder;
  32.     public function __construct(
  33.         MailHandler $mailHandler,
  34.         LoggerInterface $logger,
  35.         UserPasswordHasherInterface $encoder
  36.     )
  37.     {
  38.         $this->mailHandler $mailHandler;
  39.         $this->logger $logger;
  40.         $this->encoder $encoder;
  41.     }
  42.     /**
  43.      * @Route("/connexion", name="app_login")
  44.      */
  45.     public function login(AuthenticationUtils $authenticationUtils): Response
  46.     {
  47.         if($this->isGranted("IS_AUTHENTICATED_REMEMBERED"))
  48.         {
  49.             return $this->redirectToRoute("admin_dashboard");
  50.         }
  51.         $error $authenticationUtils->getLastAuthenticationError();
  52.         $lastUsername $authenticationUtils->getLastUsername();
  53.         return $this->render('security/login.html.twig', ['last_username' => $lastUsername'error' => $error]);
  54.     }
  55.     /**
  56.      * @Route("/mot-de-passe-oublie", name="forgot_password")
  57.      */
  58.     public function forgotPassword(
  59.         Request  $request,
  60.         UserRepository $userRepository,
  61.         UserPasswordLinkRepository $passwordLinkRepository
  62.     ): Response
  63.     {
  64.         $error null;
  65.         if($request->isMethod('POST'))
  66.         {
  67.             $email $request->request->get('email',null);
  68.             if(!$email)
  69.             {
  70.                 $error "Veuillez rensigner votre email !";
  71.             }
  72.             try {
  73.                 $user =   $userRepository->findOneBy([
  74.                     'email'=>$email,
  75.                     'enabled'=>true,
  76.                 ]);
  77.                 $error "Impossible de trouver le profil demandé !";
  78.                 if ($user) {
  79.                     $token $this->generateToken();
  80.                     $resetPasswordLink $this->generateResetPassworkLinkTokenUrl($request$token);
  81.                     $passwordLinkRepository->deleteOldLinks($user);
  82.                     $passwordLink = new UserPasswordLink();
  83.                     $passwordLink->setAppUser($user);
  84.                     $passwordLink->setToken($token);
  85.                     $passwordLink->setEndAt($this->createExpireTokenDate());
  86.                     $error null;
  87.                     $em $this->getDoctrine()->getManager();
  88.                     $em->persist($passwordLink);
  89.                     $em->flush();
  90.                     $mailSuccess $this->mailHandler->sendResetPasswordLink([
  91.                         'user' => $user,
  92.                         'url' => $resetPasswordLink,
  93.                         'to' => $user->getEmail(),
  94.                         'fullname' => $user->getFullName(),
  95.                     ]);
  96.                     if (!== $mailSuccess) {
  97.                         $this->addFlash('warning'"Une erreur s'est produite lors de l'envoi du mail");
  98.                     } elseif (=== $mailSuccess) {
  99.                         $this->addFlash('success','Vous allez recevoir un mail pour modifier votre mot de passe');
  100.                     }
  101.                     return $this->redirectToRoute('app_login');
  102.                 }
  103.             }
  104.             catch (\Exception $e){
  105.                 $error "Erreur lors de la recherche de votre profil !";
  106.                 $this->logger->critical(sprintf("security_controller_forgot_password.CRITICAL: %s",$e->getMessage()));
  107.             }
  108.         }
  109.         return $this->render('security/forgot_password.html.twig',
  110.             [
  111.             'error'=>$error,
  112.             ]
  113.         );
  114.     }
  115.     /**
  116.      * @Route("/reset-mot-de-passe/{token}", name="admin_reset_password")
  117.      */
  118.     public function AdminResetPassword(Request $request$token,UserPasswordLinkRepository $userPasswordLinkRepository)
  119.     {
  120.         if(!$token){
  121.             $this->addFlash("error","Votre token est invalide !");
  122.             return  $this->redirectToRoute('forgot_password');
  123.         }
  124.         $userPasswordLink $userPasswordLinkRepository->findOneBy(['token'=>$token]);
  125.         if(!$userPasswordLink){
  126.             $this->addFlash("error","Votre token est invalide !");
  127.             return  $this->redirectToRoute('forgot_password');
  128.         }
  129.         if($this->isTokenExpired($userPasswordLink->getEndAt()))
  130.         {
  131.             $this->addFlash('error',"Votre token est expiré !");
  132.             return  $this->redirectToRoute('forgot_password');
  133.         }
  134.         $user $userPasswordLink->getAppUser();
  135.         if(!$user)
  136.         {
  137.             $this->addFlash('error',"Une erreur est survenue lors de la récuparation de votre profil !");
  138.             return  $this->redirectToRoute('forgot_password');
  139.         }
  140.         $form $this->createForm(ChangePasswordType::class,$user);
  141.         $form->handleRequest($request);
  142.         if($request->isMethod('POST') && $form->isValid()){
  143.             if($user->getPlainPassword()){
  144.                 $passwordEncoded $this->encoder->hashPassword($user,$user->getPlainPassword());
  145.                 $user->setPassword($passwordEncoded);
  146.             }
  147.             $userPasswordLinkRepository->deleteOldLinks($user);
  148.             $em $this->getDoctrine()->getManager();
  149.             $em->flush($user);
  150.             $this->addFlash('success',"Votre profil a été mis à jour !");
  151.             return $this->redirectToRoute('app_login');
  152.         }
  153.         if($form->getErrors(true) && count($form->getErrors(true)) > 0)
  154.         {
  155.             $errorMessage $form->getErrors(true)->getChildren('password')->getMessage();
  156.             $this->addFlash('error',$errorMessage);
  157.         }
  158.         return $this->render('security/reset_password.html.twig',[
  159.             'form'=>$form->createView(),
  160.             'token'=>$token,
  161.         ]);
  162.     }
  163.     /**
  164.      * @Route("/deconnexion", name="app_logout")
  165.      */
  166.     public function logout()
  167.     {
  168.         return $this->redirectToRoute('app_login');
  169.     }
  170. }