src/Controller/AuthController.php line 422

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\Entity\User;
  4. use App\Form\RegisterType;
  5. use App\Form\ResetPasswordType;
  6. use App\Service\UserService;
  7. use Bluesquare\ValidatorBundle\Validator;
  8. use Doctrine\ORM\EntityManagerInterface;
  9. use EWZ\Bundle\RecaptchaBundle\Form\Type\EWZRecaptchaV3Type;
  10. use EWZ\Bundle\RecaptchaBundle\Validator\Constraints\IsTrueV3;
  11. use KnpU\OAuth2ClientBundle\Client\ClientRegistry;
  12. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  13. use Symfony\Component\Config\Definition\Exception\Exception;
  14. use Symfony\Component\Form\Extension\Core\Type\EmailType;
  15. use Symfony\Component\Form\Extension\Core\Type\PasswordType;
  16. use Symfony\Component\HttpFoundation\RedirectResponse;
  17. use Symfony\Component\HttpFoundation\Request;
  18. use Symfony\Component\HttpFoundation\Response;
  19. use Symfony\Component\HttpFoundation\Session\Session;
  20. use Symfony\Component\Mailer\MailerInterface;
  21. use Symfony\Component\Routing\Annotation\Route;
  22. use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
  23. use Symfony\Component\Security\Core\Exception\CustomUserMessageAuthenticationException;
  24. use Symfony\Component\Security\Core\Security;
  25. use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
  26. use Symfony\Component\Validator\Constraints\Email;
  27. use Symfony\Component\Validator\Constraints\NotBlank;
  28. class AuthController extends AbstractController
  29. {
  30.     protected function loginAs(User $user)
  31.     {
  32.         $token = new UsernamePasswordToken($usernull'main'$user->getRoles());
  33.         $this->get('security.token_storage')->setToken($token);
  34.         $this->get('session')->set('_security_main'serialize($token));
  35.     }
  36.     /**
  37.      * @Route("/auth/redirect", name="auth.redirect")
  38.      */
  39.     public function redirectUser(Request $request): RedirectResponse
  40.     {
  41.         // TODO: redirect by role (if you want)
  42.         $user $this->getUser();
  43.         if ($user instanceof User) {
  44.             $session $request->getSession();
  45.             $price_id $session->get('price_id');
  46.             if ($request->getSession()->get('article_id') && $request->getSession()->get('article_slug')) {
  47.                 $article_id $request->getSession()->get('article_id');
  48.                 $article_slug $request->getSession()->get('article_slug');
  49.                 return $this->redirectToRoute('article.view', ['id' => $article_id'slug' => $article_slug]);
  50.             }
  51.             if ($price_id) {
  52.                 return $this->redirectToRoute('products.details', ['price_id' => $price_id]);
  53.             }
  54.             return $this->redirectToRoute('account');
  55.         }
  56.         return $this->redirectToRoute('auth.login');
  57.     }
  58.     /**
  59.      * @Route("/auth/login", name="auth.login")
  60.      */
  61.     public function login(Request $requestAuthenticationUtils $authenticationUtilsValidator $validator): Response
  62.     {
  63.         $builder $this->createFormBuilder()
  64.             ->add('email'EmailType::class, [
  65.                 'constraints' => [
  66.                     new NotBlank(),
  67.                     new Email(),
  68.                 ],
  69.                 'attr' => [
  70.                     'class' => 'auth-form-input',
  71.                 ],
  72.             ])
  73.             ->add('password'PasswordType::class, [
  74.                 'constraints' => [
  75.                     new NotBlank(),
  76.                 ],
  77.                 'attr' => [
  78.                     'class' => 'auth-form-input',
  79.                 ],
  80.             ])
  81.             ->add('recaptcha'EWZRecaptchaV3Type::class, [
  82.                 'action_name' => 'auth_register',
  83.                 'mapped' => false,
  84.                 'constraints' => [
  85.                     new IsTrueV3(),
  86.                 ],
  87.             ])
  88.         ;
  89.         $loginForm $builder->getForm();
  90.         $loginForm->handleRequest($request);
  91.         $error $authenticationUtils->getLastAuthenticationError();
  92.         $lastEmail $authenticationUtils->getLastUsername();
  93.         if ($request->get('article_id') && $request->get('article_slug')) {
  94.             $session $request->getSession();
  95.             $article_id $request->get('article_id');
  96.             $article_slug $request->get('article_slug');
  97.             $session->set('article_id'$article_id);
  98.             $session->set('article_slug'$article_slug);
  99.         }
  100.         return $this->render('auth/login.html.twig', [
  101.             'last_email' => $lastEmail,
  102.             'error' => $error,
  103.             'login_form' => $loginForm->createView(),
  104.             'validator' => $validator,
  105.         ]);
  106.     }
  107.     /**
  108.      * @Route("/auth/register", name="auth.register")
  109.      */
  110.     public function register(Request $requestEntityManagerInterface $managerUserService $userServiceValidator $validator,MailerInterface $symfonyMailer)
  111.     {
  112.         $validator->context('auth.register');
  113.         $sender $this->getParameter('mailer_from_address');
  114.         $user = new User();
  115.         $form $this->createForm(RegisterType::class, $user);
  116.         $builder $this->createFormBuilder($user)
  117.             ->add('email'EmailType::class, [
  118.                 'constraints' => [
  119.                     new NotBlank(),
  120.                     new Email(),
  121.                 ],
  122.             ])
  123.             ->add('password'PasswordType::class, [
  124.                 'constraints' => [
  125.                     new NotBlank(),
  126.                 ],
  127.             ])
  128.             ->add('recaptcha'EWZRecaptchaV3Type::class, [
  129.                 'action_name' => 'auth_register',
  130.                 'mapped' => false,
  131.                 'constraints' => [
  132.                     new IsTrueV3(),
  133.                 ],
  134.             ])
  135.         ;
  136.         $registerForm $builder->getForm();
  137.         $registerForm->handleRequest($request);
  138.         if ($registerForm->isSubmitted() && $registerForm->isValid()) {
  139.             $email $user->getEmail();
  140.             $password $user->getPassword();
  141.             $user $userService->createUser($email$password);
  142.             $userService->sendActivationEmail($user$sender$symfonyMailer);
  143.             $session $request->getSession();
  144.             $price_id $session->get('price_id');
  145.             if ($price_id && $user->getActivatedAt()) {
  146.                 return $this->redirectToRoute('products.details', ['price_id' => $price_id]);
  147.             }
  148.             $article_id $session->get('article_id');
  149.             $article_slug $session->get('article_slug');
  150.             if ($article_id && $article_slug && $user->getActivatedAt()) {
  151.                 return $this->redirectToRoute('article.view', ['id' => $article_id'slug' => $article_slug]);
  152.             }
  153.             return $this->redirectToRoute('auth.login');
  154.         }
  155.         // form A&C
  156.         $form->handleRequest($request);
  157.         if ($form->isSubmitted() && $form->isValid()) {
  158.             $email $user->getEmail();
  159.             if ($this->hasNumbers($form->getData()->getFirstname()) && $this->hasNumbers($form->getData()->getLastname())) {
  160.                 $this->addFlash('error''les données ne sont pas valides');
  161.                 return $this->render('auth/register.html.twig', [
  162.                     'validator' => $validator,
  163.                     'register_form' => $registerForm->createView(), 'form' => $form->createView(),
  164.                 ]);
  165.             } else {
  166.                 $user $userService->createUser_new($form->getData());
  167.                 $userService->sendActivationEmail($user$sender$symfonyMailer);
  168.                 return $this->render('_partials/register/register-confirm.html.twig', [
  169.                     'form' => $form->createView(), 'email' => $email'lastName' => $user->getLastname() , 'firstName' =>$user->getFirstname()
  170.                 ]);
  171.             }
  172.         }
  173.         return $this->render('auth/register.html.twig', [
  174.             'validator' => $validator,
  175.             'register_form' => $registerForm->createView(), 'form' => $form->createView(),
  176.         ]);
  177.     }
  178.     /**
  179.      * @Route("/auth/activate/{hash}", name="auth.activate_account")
  180.      */
  181.     public function activateAccount(Request $requestUserService $userService$hashSession $session)
  182.     {
  183.         $user $userService->checkValidationToken($hash);
  184.         if (!$user) {
  185.             return $this->redirectUser($request);
  186.         }
  187.         $this->loginAs($user);
  188.         return $this->render('auth/activation.html.twig');
  189.     }
  190.     /**
  191.      * @Route("/auth/activate_account/{hash}", name="auth.activate_account_new")
  192.      */
  193.     public function activateAccount_refonte(Request $requestUserService $userService$hashSession $session): RedirectResponse
  194.     {
  195.         $user $userService->checkValidationToken($hash);
  196.         if ($user instanceof User) {
  197.             $this->loginAs($user);
  198.             $session->set('firstLogin''true');
  199.             return $this->redirectToRoute('homepage');
  200.         }
  201.         return $this->redirectUser($request);
  202.     }
  203.     /**
  204.      * @Route("/auth/forgot-password", name="auth.forgot_password")
  205.      */
  206.     public function forgotPassword(Request $requestEntityManagerInterface $managerUserService $userServiceValidator $validator MailerInterface $symfonyMailer)
  207.     {
  208.         $sender $this->getParameter('mailer_from_address');
  209.         $validator->context('auth.forgot_password');
  210.         $builder $this->createFormBuilder()
  211.             ->add('email'EmailType::class, [
  212.                 'constraints' => [
  213.                     new NotBlank(),
  214.                     new Email(),
  215.                 ],
  216.             ])
  217.             ->add('recaptcha'EWZRecaptchaV3Type::class, [
  218.                 'action_name' => 'forgot_password',
  219.                 'mapped' => false,
  220.                 'constraints' => [
  221.                     new IsTrueV3(),
  222.                 ],
  223.             ]);
  224.         $form $builder->getForm();
  225.         $builder2 $this->createFormBuilder()
  226.             ->add('email'EmailType::class, [
  227.                 'constraints' => [
  228.                     new NotBlank(),
  229.                     new Email(),
  230.                 ],
  231.             ]);
  232.         $form2 $builder2->getForm();
  233.         if ($request->isXmlHttpRequest()) {
  234.             $data json_decode($request->getContent());
  235.             $email $data->email;
  236.             $user $manager->getRepository(User::class)->findOneBy(['email' => $email]);
  237.             if (!$user) {
  238.                 return $this->json(['errors' => 'error'], 500);
  239.             }
  240.             $userService->sendResetPasswordEMail($user$sender$symfonyMailer);;
  241.             return $this->json(['success' => 'ok'], 200);
  242.         }
  243.         $form->handleRequest($request);
  244.         $form2->handleRequest($request);
  245.         if ($form->isSubmitted() && $form->isValid()) {
  246.             $email $form->get('email')->getData();
  247.             $user $manager->getRepository(User::class)->findOneBy(['email' => $email]);
  248.             if (!$user) {
  249.                 $this->addFlash('error''Cet email n\'est pas connu.');
  250.             } else {
  251.                 $userService->sendResetPasswordEMail($user$sender$symfonyMailer);;
  252.                 return $this->redirectToRoute('home');
  253.             }
  254.         }
  255.         if ($form2->isSubmitted() && $form2->isValid()) {
  256.             $email $form2->get('email')->getData();
  257.             $user $manager->getRepository(User::class)->findOneBy(['email' => $email]);
  258.             if (!$user) {
  259.                 $this->addFlash('error''Cet email n\'est pas connu.');
  260.             } else {
  261.                 $userService->sendResetPasswordEMail($user$sender$symfonyMailer);;
  262.                 $this->addFlash('success''Le lien de réinitialisation a été envoyé à votre email.');
  263.                 return $this->redirectToRoute('auth.forgot_password');
  264.             }
  265.         }
  266.         return $this->render('auth/forgot_password.html.twig', [
  267.             'validator' => $validator,
  268.             'reset_password_form' => $form->createView(), 'form' => $form2->createView(),
  269.         ]);
  270.     }
  271.     /**
  272.      * @Route("/auth/legacy", name="auth.legacy")
  273.      */
  274.     public function legacy(Request $requestEntityManagerInterface $managerUserService $userServiceValidator $validator)
  275.     {
  276.         $username $request->getSession()->get(Security::LAST_USERNAME);
  277.         if (null === $username) {
  278.             return $this->redirectToRoute('auth.login');
  279.         }
  280.         $user $manager->getRepository(User::class)->findOneBy(['email' => $username]);
  281.         if (!$user) {
  282.             return $this->redirectToRoute('auth.login');
  283.         }
  284.         $userService->sendResetPasswordMail($user);
  285.         return $this->render('auth/legacy.html.twig', [
  286.             'username' => $username,
  287.         ]);
  288.     }
  289.     /**
  290.      * @Route("/auth/reset-password/{hash}", name="auth.reset_password")
  291.      */
  292.     public function resetPassword(Request $requestUserService $userServiceValidator $validator$hash)
  293.     {
  294.         $validator->context('auth.reset_password');
  295.         $user $userService->checkResetPasswordToken($hash);
  296.         if (!$user) {
  297.             return $this->redirectToRoute('auth.login');
  298.         }
  299.         $form $this->createForm(ResetPasswordType::class);
  300.         $form->handleRequest($request);
  301.         if ($validator->post()) {
  302.             $validator
  303.                 ->required('password''password_confirm')
  304.                 ->minLength('password'6)
  305.                 ->identical('password''password_confirm')
  306.             ;
  307.             if ($validator->check()) {
  308.                 $password $validator->get('password');
  309.                 $userService->updatePassword($user$password);
  310.                 $validator->keep();
  311.                 $this->loginAs($user);
  312.                 return $this->redirectToRoute('auth.redirect');
  313.             }
  314.         }
  315.         if ($form->isSubmitted() && $form->isValid()) {
  316.             $password $form->getData()['password'];
  317.             $userService->updatePassword($user$password);
  318.             $this->loginAs($user);
  319.             return $this->redirectToRoute('homepage');
  320.         }
  321.         return $this->render('auth/reset_password.html.twig', [
  322.             'user' => $user'form' => $form->createView(), 'hash' => $hash'email' => $user->getEmail(),
  323.         ]);
  324.     }
  325.     /**
  326.      * @Route("/connect/google", name="connect_google")
  327.      */
  328.     public function connectGoogle(ClientRegistry $clientRegistry): RedirectResponse
  329.     {
  330.         return $clientRegistry
  331.             ->getClient('google')
  332.             ->redirect(['email'])
  333.         ;
  334.     }
  335.     /**
  336.      * @Route("/oauth/check/google", name="oauth_check_google")
  337.      */
  338.     public function oauthCheckGoogle(Request $request)
  339.     {
  340.         return $this->extracted($request);
  341.     }
  342.     /**
  343.      * @Route("/connect/linkedIn", name="connect_linkedIn")
  344.      */
  345.     public function connectLinkedIn(ClientRegistry $clientRegistry): RedirectResponse
  346.     {
  347.         return $clientRegistry
  348.             ->getClient('linkedin')
  349.             ->redirect(['r_emailaddress''r_liteprofile'])
  350.         ;
  351.     }
  352.     /**
  353.      * @Route("/oauth/check/linkedIn", name="oauth_check_linkedIn")
  354.      */
  355.     public function oauthCheckLinkedIn(Request $request)
  356.     {
  357.         return $this->extracted($request);
  358.     }
  359.     /**
  360.      * @Route("/connect/facebook", name="connect_facebook")
  361.      */
  362.     public function connectFacebook(ClientRegistry $clientRegistry): RedirectResponse
  363.     {
  364.         return $clientRegistry
  365.             ->getClient('facebook')
  366.             ->redirect(['email''public_profile'])
  367.         ;
  368.     }
  369.     /**
  370.      * @Route("/oauth/check/facebook", name="oauth_check_facebook")
  371.      */
  372.     public function oauthCheckFacebook(Request $request)
  373.     {
  374.         return $this->extracted($request);
  375.     }
  376.     /**
  377.      * @return RedirectResponse|Response
  378.      */
  379.     public function extracted(Request $request)
  380.     {
  381.         $session $request->getSession();
  382.         $price_id $session->get('price_id');
  383.         if ($price_id) {
  384.             return $this->redirectToRoute('products.details', ['price_id' => $price_id]);
  385.         }
  386.         if ($request->getSession()->get('article_id') && $request->getSession()->get('article_slug')) {
  387.             $article_id $request->getSession()->get('article_id');
  388.             $article_slug $request->getSession()->get('article_slug');
  389.             return $this->redirectToRoute('article.view', ['id' => $article_id'slug' => $article_slug]);
  390.         }
  391.         return $this->redirectToRoute('homepage');
  392.     }
  393.    private function hasNumbers($str) {
  394.         return preg_match('/\d/'$str) === 1;
  395.     }
  396. }