src/Controller/SecurityController.php line 150

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\Entity\Token;
  4. use App\Entity\User\Consumer;
  5. use App\Entity\User\Admin;
  6. use App\Entity\User\Identity;
  7. use App\Entity\User\Referent;
  8. use App\Entity\User\User;
  9. use App\Form\RequestResetPasswordType;
  10. use App\Form\User\ResetPasswordType;
  11. use App\Manager\TokenManager;
  12. use App\Message\Email\SendInitializationAccountByEmailMessage;
  13. use App\Repository\MediaObject\MediaObjectRepository;
  14. use App\Service\SendInBlue;
  15. use Doctrine\ORM\EntityManagerInterface;
  16. use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
  17. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  18. use Symfony\Component\HttpFoundation\JsonResponse;
  19. use Symfony\Component\HttpFoundation\RedirectResponse;
  20. use Symfony\Component\HttpFoundation\Request;
  21. use Symfony\Component\HttpFoundation\Response;
  22. use Symfony\Component\Messenger\MessageBusInterface;
  23. use Symfony\Component\Routing\Annotation\Route;
  24. use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
  25. use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
  26. class SecurityController extends AbstractController
  27. {
  28.     /**
  29.      * @Route("/security", name="security")
  30.      */
  31.     public function index()
  32.     {
  33.         return $this->render('security/index.html.twig', [
  34.             'controller_name' => 'SecurityController',
  35.         ]);
  36.     }
  37.     /**
  38.      * @Route("/login", name="app_login")
  39.      * @throws \Exception
  40.      */
  41.     public function login(AuthenticationUtils $authenticationUtilsRequest $request): Response
  42.     {
  43.         // get the login error if there is one
  44.         $error $authenticationUtils->getLastAuthenticationError();
  45.         // last username entered by the user
  46.         $lastUsername $authenticationUtils->getLastUsername();
  47.         if ($_ENV['RESTRICTION_ACCESS'] && $_ENV['CHECK_MAINTENANCE_PAGE_ON']) {
  48.             $allowedIp = [];
  49.             $clientIp $request->getClientIp();
  50.             if (isset($_ENV['ALLOWED_IP']) && $_ENV['ALLOWED_IP']) {
  51.                 $allowedIp explode(','$_ENV['ALLOWED_IP']);
  52.             }
  53.             if (in_array($clientIp$allowedIp)) {
  54.                 return $this->render('security/login.html.twig', ['last_username' => $lastUsername'error' => $error'csrf_token' => 'authenticate']);
  55.             }
  56.             return $this->render('error/maintenance.html.twig');
  57.         }
  58.         return $this->render('security/login.html.twig', ['last_username' => $lastUsername'error' => $error'csrf_token' => 'authenticate']);
  59.     }
  60.     /**
  61.      * @Route("/client_login", name="app_client_login")
  62.      */
  63.     public function clientlogin(AuthenticationUtils $authenticationUtilsMediaObjectRepository $mediaObjectRepository): Response
  64.     {
  65.         // get the login error if there is one
  66.         $error $authenticationUtils->getLastAuthenticationError();
  67.         // last username entered by the user
  68.         $lastUsername $authenticationUtils->getLastUsername();
  69.         $logo $mediaObjectRepository->findOneLikeByName(strtolower($_ENV['APP_PROJET']));
  70.         return $this->render('security/client_login.html.twig', [
  71.             'last_username' => $lastUsername,
  72.             'error' => $error,
  73.             'csrf_token' => 'authenticate',
  74.             'logo_path' => $logo $logo->getFilePath() : null
  75.         ]);
  76.     }
  77.     /**
  78.      * @Route("/api/public/request-reset-password", name="app_request_reset_password")
  79.      * @param Request $request
  80.      *
  81.      * @return JsonResponse
  82.      */
  83.     public function requestResetPassword(Request      $requestEntityManagerInterface $entityManagerSendInBlue $sendInBlue,
  84.                                          TokenManager $tokenManagerMessageBusInterface $bus)
  85.     {
  86.         $data json_decode($request->getContent(), true);
  87.         $form $this->createForm(RequestResetPasswordType::class, $data);
  88.         $form->submit($data);
  89.         $email $data['email'];
  90.         if ($form->isValid() && $user $entityManager->getRepository(Consumer::class)->findOneBy(['email' => $email])) {
  91.             if (!$user->isOptinProcess()) {
  92.                 $url $_ENV['PRE_INSCRIPTION_MILLERET'];
  93.                 $templateId $_ENV['PRE_INSCRIPTION_MILLERET_TEMPLATE_ID'];
  94.                 $token_initialization $entityManager->getRepository(Token::class)->findOneBy(['user' => $user'name' => Token::NAME_INITIALIZATION_PASSWORD]);
  95.                 $token $tokenManager->requestInitializationForgottenPassword($token_initialization);
  96.                 $identity $entityManager->getRepository(Identity::class)->findOneBy(['id' => $user->getIdentity()->getId()]);
  97.                 $url $url $token->getId();
  98.                 $bus->dispatch(new SendInitializationAccountByEmailMessage(
  99.                         $user->getId(),
  100.                         $email,
  101.                         $identity->getGender(),
  102.                         $identity->getFirstName(),
  103.                         $identity->getLastName(),
  104.                         $templateId,
  105.                         $url)
  106.                 );
  107.             } else {
  108.                 if ($entityManager->getRepository(Token::class)->countActiveToken($userToken::NAME_FORGOTTEN_PASSWORD) >= Token::MAX_REQUEST_FORGOTTEN_PASSWORD) {
  109.                     return new JsonResponse(['error' => 'limit'], 200);
  110.                 }
  111.                 $token $tokenManager->requestResetPassword($user);
  112.                 $sendInBlue->sendTemplate($data['templateId'], [
  113.                     'to' => [
  114.                         ["email" => $email]
  115.                     ],
  116.                     'templateParameters' =>
  117.                         [
  118.                             'URL' => $data['url'] . $token->getId(),
  119.                             'SURNAME' => $token->getUser()->getIdentity()->getFormatedGender() . ' ' $token->getUser()->getIdentity()->getLastName() . ' ' $token->getUser()->getIdentity()->getFirstName()
  120.                         ],
  121.                 ]);
  122.             }
  123.         }
  124.         return new JsonResponse(null204);
  125.     }
  126.     /**
  127.      * @Route("/forget_password", name="app_forgotten_password")
  128.      */
  129.     public function forgottenPassword(Request                $requestMediaObjectRepository $mediaObjectRepository,
  130.                                       EntityManagerInterface $entityManagerTokenManager $tokenManager,
  131.                                       SendInBlue             $sendInBlue)
  132.     {
  133.         $error "";
  134.         $success false;
  135.         $request->request->add([
  136.             'templateId' => $_ENV['TEMPLATE_RESET_PASSWORD_ADMIN'],
  137.             'url' => $request->getSchemeAndHttpHost() . '/reset_password/',
  138.         ]);
  139.         $form $this->createForm(RequestResetPasswordType::class, $request->request->all());
  140.         $form->submit($request->request->all());
  141.         if ($form->isValid()) {
  142.             $success true;
  143.             $userForgotPassword $entityManager->getRepository(Referent::class)->findOneBy(['email' => $form->getData()['email']]);
  144.             if (!$userForgotPassword) {
  145.                 $userForgotPassword $entityManager->getRepository(Admin::class)->findOneBy(['email' => $form->getData()['email'], 'active' => true]);
  146.             }
  147.             if ($userForgotPassword) {
  148.                 if ($entityManager->getRepository(Token::class)->countActiveToken($userForgotPasswordToken::NAME_FORGOTTEN_PASSWORD) >= Token::MAX_REQUEST_FORGOTTEN_PASSWORD) {
  149.                     return new JsonResponse(['error' => 'limit'], 200);
  150.                 }
  151.                 $token $tokenManager->requestResetPassword($userForgotPassword);
  152.                 $sendInBlue->sendTemplate($form->getData()['templateId'], [
  153.                     'to' => [
  154.                         ["email" => $userForgotPassword->getEmail()]
  155.                     ],
  156.                     'templateParameters' =>
  157.                         [
  158.                             'URL' => $form->getData()['url'] . $token->getId(),
  159.                             'SURNAME' => ''
  160.                         ],
  161.                 ]);
  162.             }
  163.         } else if (isset($form->getData()['email'])) {
  164.             $error "Veuillez renseignez une adresse mail valide";
  165.         }
  166.         $logo $mediaObjectRepository->findOneLikeByName(strtolower($_ENV['APP_PROJET']));
  167.         return $this->render('security/forgotten_password.html.twig', [
  168.             'logo_path' => $logo $logo->getFilePath() : null,
  169.             'error' => $error,
  170.             'success' => $success,
  171.         ]);
  172.     }
  173.     /**
  174.      * @Route("/reset_password/{token}", name="app_client_reset_password")
  175.      * @ParamConverter("token", class="App:Token", options={"id"= "token"})
  176.      */
  177.     public function resetPassword(Token                        $tokenRequest $requestMediaObjectRepository $mediaObjectRepository,
  178.                                   UserPasswordHasherInterface $passwordEncoderTokenManager $tokenManager,
  179.                                   EntityManagerInterface       $entityManager)
  180.     {
  181.         $form $this->createForm(ResetPasswordType::class);
  182.         $form->handleRequest($request);
  183.         $redirectionPage 'security/reset_password.html.twig';
  184.         $success false;
  185.         $loginRoute $token->getReferent() ? 'app_client_login' 'app_login';
  186.         $user $token->getReferent() ?? $token->getUser();
  187.         if ($tokenManager->checkValidityToken($token) && $user) {
  188.             if ($form->isSubmitted() && $form->isValid()) {
  189.                 $encodedPassword $passwordEncoder->hashPassword($user$form->getData()['plainPassword']);
  190.                 $user->setPassword($encodedPassword);
  191.                 // We reset the token so that the user can reset his password once
  192.                 $token
  193.                     ->setUser(null)
  194.                     ->setReferent(null);
  195.                 $entityManager->flush();
  196.                 $success true;
  197.             }
  198.         } else {
  199.             $redirectionPage 'security/expired_token.html.twig';
  200.         }
  201.         $logo $mediaObjectRepository->findOneLikeByName(strtolower($_ENV['APP_PROJET']));
  202.         return $this->render($redirectionPage, [
  203.             'logo_path' => $logo $logo->getFilePath() : null,
  204.             'login_route' => $loginRoute,
  205.             'form' => $form->createView(),
  206.             'token' => $token->getId(),
  207.             'success' => $success
  208.         ]);
  209.     }
  210.     /**
  211.      * @Route("/logout", name="app_logout")
  212.      */
  213.     public function logout()
  214.     {
  215.         throw new \LogicException('This method can be blank - it will be intercepted by the logout key on your firewall.');
  216.     }
  217. }