src/Controller/RegistrationController.php line 129

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\Entity\User;
  4. use App\Form\RegistrationFormType;
  5. use App\Form\RequestResetPasswordType;
  6. use App\Form\ResetPasswordType;
  7. use App\Form\Model\RequestResetPasswordData;
  8. use App\Form\Model\ResetPasswordData;
  9. use App\Security\AppCustomAuthenticator;
  10. use App\Security\EmailVerifier;
  11. use Doctrine\ORM\EntityManagerInterface;
  12. use Symfony\Bridge\Twig\Mime\TemplatedEmail;
  13. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  14. use Symfony\Component\HttpFoundation\Request;
  15. use Symfony\Component\HttpFoundation\Response;
  16. use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
  17. use Symfony\Component\Mime\Address;
  18. use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
  19. use Symfony\Component\Routing\Annotation\Route;
  20. use Symfony\Component\Security\Http\Authentication\UserAuthenticatorInterface;
  21. use Symfony\Contracts\Translation\TranslatorInterface;
  22. use SymfonyCasts\Bundle\VerifyEmail\Exception\VerifyEmailExceptionInterface;
  23. use GuzzleHttp\Client;
  24. use App\Repository\UserRepository;
  25. use App\Model\Common;
  26. class RegistrationController extends AbstractController
  27. {
  28.     private EmailVerifier $emailVerifier;
  29.     public function __construct(EmailVerifier $emailVerifierUserRepository $userRepository)
  30.     {
  31.                 $this->userRepository $userRepository;
  32.         $this->emailVerifier $emailVerifier;
  33.     }
  34.     #[Route('/register'name'app_register')]
  35.     public function register(Request $requestUserPasswordHasherInterface $userPasswordHasherUserAuthenticatorInterface $userAuthenticatorAppCustomAuthenticator $authenticatorEntityManagerInterface $entityManager): Response
  36.     {
  37.         $user = new User();
  38.                 $common = new Common();
  39.         $form $this->createForm(RegistrationFormType::class, $user);
  40.         $form->handleRequest($request);
  41.                 $recaptcha_site_key $this->getParameter("recaptcha_site_key");
  42.                 $recaptcha_secret_key $this->getParameter("recaptcha_secret_key");
  43.                 $site_url $this->getParameter("site_url");
  44.         if ($form->isSubmitted() && $form->isValid()) {
  45.             // encode the plain password
  46.                     $recaptchaResponse $request->request->get('g-recaptcha-response');
  47.                     $client = new Client();
  48.                     $response $client->post('https://www.google.com/recaptcha/api/siteverify', [
  49.                         'form_params' => [
  50.                         'secret' => $recaptcha_secret_key,
  51.                         'response' => $recaptchaResponse
  52.                         ]
  53.                     ]);
  54.                     $responseData json_decode($response->getBody(), true);
  55.                     if ($responseData['success']) {
  56.                         // ... continue with user registration
  57.                         $token bin2hex(random_bytes(16));
  58.                         $user->setToken($token);
  59.                         $user->setPassword(
  60.                             $userPasswordHasher->hashPassword(
  61.                                 $user,
  62.                                 $form->get('plainPassword')->getData()
  63.                             )
  64.                         );
  65.                     $user->setNumberOfEmailSent(1);
  66.                     $entityManager->persist($user);
  67.                     $entityManager->flush();
  68.                     $common->sendEmail($user->getEmail(),"Confirm email"$this->render('admin/registration/confirmation_email.html.twig', [ 'signedUrl' => $site_url "login/" $token]));
  69.             
  70.                         $messageCode "ok";
  71.                     } else {
  72.                         $messageCode "error_recpacha";
  73.                         // ... handle invalid reCAPTCHA response
  74.                     }
  75.             return $this->render('admin/registration/verification.html.twig', [
  76.                     'user' => $user,
  77.                     'message_code' => $messageCode 
  78.             ]);
  79.         /*
  80.            return $userAuthenticator->authenticateUser(
  81.            $user,
  82.            $authenticator,
  83.            $request
  84.            );
  85.          */
  86.         }
  87.         return $this->render('admin/registration/register.html.twig', [
  88.             'registrationForm' => $form->createView(),
  89.             'recaptcha_site_key' => $recaptcha_site_key
  90.         ]);
  91.     }
  92. #[Route('/verify/email'name'app_verify_email')]
  93.     public function verifyUserEmail(Request $requestTranslatorInterface $translator): Response
  94.     {
  95.         $this->denyAccessUnlessGranted('IS_AUTHENTICATED_FULLY');
  96.         // validate email confirmation link, sets User::isVerified=true and persists
  97.         try {
  98.             $this->emailVerifier->handleEmailConfirmation($request$this->getUser());
  99.         } catch (VerifyEmailExceptionInterface $exception) {
  100.             $this->addFlash('verify_email_error'$translator->trans($exception->getReason(), [], 'VerifyEmailBundle'));
  101.             return $this->redirectToRoute('app_register');
  102.         }
  103.         // @TODO Change the redirect on success and handle or remove the flash message in your templates
  104.         $this->addFlash('success''Your email address has been verified.');
  105.         return $this->redirectToRoute('app_register');
  106.     }
  107.     #[Route('/reset-password'name'app_request_reset_password')]
  108.     public function requestResetPassword(Request $requestUserPasswordHasherInterface $userPasswordHasherUserAuthenticatorInterface $userAuthenticatorAppCustomAuthenticator $authenticatorEntityManagerInterface $entityManager): Response
  109.     {
  110.                 $success null;    
  111.                 $customError null;
  112.         $user = new User();
  113.                 $resetPasswordData = new RequestResetPasswordData();
  114.                 $common = new Common();
  115.         $form $this->createForm(RequestResetPasswordType::class, $resetPasswordData);
  116.         $form->handleRequest($request);
  117.                 $recaptcha_site_key $this->getParameter("recaptcha_site_key");
  118.                 $recaptcha_secret_key $this->getParameter("recaptcha_secret_key");
  119.                 $site_url $this->getParameter("site_url");
  120.         if ($form->isSubmitted() && $form->isValid()) {
  121.             // encode the plain password
  122.                     $recaptchaResponse $request->request->get('g-recaptcha-response');
  123.                     $client = new Client();
  124.                     $response $client->post('https://www.google.com/recaptcha/api/siteverify', [
  125.                         'form_params' => [
  126.                         'secret' => $recaptcha_secret_key,
  127.                         'response' => $recaptchaResponse
  128.                         ]
  129.                     ]);
  130.                     $responseData json_decode($response->getBody(), true);
  131.                     if ($responseData['success']) {
  132.                         // ... continue with user registration
  133.                         $email $resetPasswordData->email;
  134.                         $user $this->userRepository->findOneByEmail($email);
  135.             
  136.                         if ($user) {
  137.                             $token bin2hex(random_bytes(16));
  138.                             $user->setToken($token);
  139.   
  140.                             $entityManager->persist($user);
  141.                             $entityManager->flush();
  142.   
  143.                             $common->sendEmail($user->getEmail(),"Reset password"$this->render('admin/registration/password_email.html.twig', [ 'signedUrl' => $site_url "reset-password/" $token]));
  144.                 
  145.                             $success "Check your mailbox to complete.";
  146.                         } else {
  147.                             $customError "Email doesn't exists. Please register.";
  148.                         }
  149.                     } else {
  150.                             $customError "Google says You are a robot.";
  151.                     }
  152.         }
  153.         return $this->render('admin/registration/request-reset-password.html.twig', [
  154.             'requestResetPasswordForm' => $form->createView(),
  155.             'recaptcha_site_key' => $recaptcha_site_key,
  156.             'success' => $success
  157.             'custom_error' => $customError
  158.             
  159.         ]);
  160.     }
  161.     #[Route('/reset-password/{token}'name'app_reset_password')]
  162.     public function resetPassword(string $tokenRequest $requestUserPasswordHasherInterface $userPasswordHasherUserAuthenticatorInterface $userAuthenticatorAppCustomAuthenticator $authenticatorEntityManagerInterface $entityManager): Response
  163.     {
  164.                 $success null;    
  165.                 $customError null;
  166.                 $user $this->userRepository->findOneByToken($token);
  167.             
  168.                 if ($user) {
  169.                 $resetPasswordData = new ResetPasswordData();
  170.                 $common = new Common();
  171.         $form $this->createForm(ResetPasswordType::class, $resetPasswordData);
  172.         $form->handleRequest($request);
  173.                 $recaptcha_site_key $this->getParameter("recaptcha_site_key");
  174.                 $recaptcha_secret_key $this->getParameter("recaptcha_secret_key");
  175.                 $site_url $this->getParameter("site_url");
  176.         if ($form->isSubmitted() && $form->isValid()) {
  177.             // encode the plain password
  178.                     $recaptchaResponse $request->request->get('g-recaptcha-response');
  179.                     $client = new Client();
  180.                     $response $client->post('https://www.google.com/recaptcha/api/siteverify', [
  181.                         'form_params' => [
  182.                         'secret' => $recaptcha_secret_key,
  183.                         'response' => $recaptchaResponse
  184.                         ]
  185.                     ]);
  186.                     $responseData json_decode($response->getBody(), true);
  187.                     if ($responseData['success']) {
  188.                         // ... continue with user registration
  189.                             $password $form->getData()->getPassword();
  190.                             $confirmPassword $form->getData()->getConfirmPassword();
  191.                             if($password == $confirmPassword) {
  192.                                 $user->setPassword(
  193.                                     $userPasswordHasher->hashPassword(
  194.                                         $user,
  195.                                         $password
  196.                                     )
  197.                                 );
  198.                             $user->setToken("");
  199.   
  200.                             $entityManager->persist($user);
  201.                             $entityManager->flush();
  202.                                 
  203.                             $success "Password changed";
  204.                             } else {
  205.                                 $customError "Passwords does not match.";
  206.                             }
  207.   
  208.                 
  209.                     } else {
  210.                             $customError "Google says You are a robot.";
  211.                     }
  212.             }
  213.         return $this->render('admin/registration/reset-password.html.twig', [
  214.             'resetPasswordForm' => $form->createView(),
  215.             'recaptcha_site_key' => $recaptcha_site_key,
  216.             'success' => $success
  217.             'custom_error' => $customError
  218.             
  219.         ]);
  220.     } else { // Nie ma usera z tokenem
  221.         throw $this->createNotFoundException('The requested page was not found.');
  222.         }
  223.     }
  224. }