src/Controller/RegistrationController.php line 30

  1. <?php
  2. namespace App\Controller;
  3. use App\Entity\User;
  4. use App\Form\Builder\RegistrationFormType;
  5. use App\Security\EmailVerifier;
  6. use Doctrine\ORM\EntityManagerInterface;
  7. use Symfony\Bridge\Twig\Mime\TemplatedEmail;
  8. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  9. use Symfony\Component\HttpFoundation\Request;
  10. use Symfony\Component\HttpFoundation\Response;
  11. use Symfony\Component\Mime\Address;
  12. use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
  13. use Symfony\Component\Routing\Annotation\Route;
  14. use Symfony\Contracts\Translation\TranslatorInterface;
  15. use SymfonyCasts\Bundle\VerifyEmail\Exception\VerifyEmailExceptionInterface;
  16. class RegistrationController extends AbstractController
  17. {
  18.     private EmailVerifier $emailVerifier;
  19.     public function __construct(EmailVerifier $emailVerifier)
  20.     {
  21.         $this->emailVerifier $emailVerifier;
  22.     }
  23.     #[Route('/register'name'app_register')]
  24.     public function register(
  25.         Request $request,
  26.         UserPasswordHasherInterface $userPasswordHasher,
  27.         EntityManagerInterface $entityManager
  28.     ): Response {
  29.         if ($this->getUser()) {
  30.             return $this->redirectToRoute('page_index');
  31.         }
  32.         $user = new User();
  33.         $form $this->createForm(RegistrationFormType::class, $user);
  34.         $form->handleRequest($request);
  35.         if ($form->isSubmitted() && $form->isValid()) {
  36.             $user->setPassword(
  37.                 $userPasswordHasher->hashPassword(
  38.                     $user,
  39.                     $form->get('plainPassword')->getData()
  40.                 )
  41.             );
  42.             $entityManager->persist($user);
  43.             $entityManager->flush();
  44.             $this->emailVerifier->sendEmailConfirmation(
  45.                 'app_verify_email',
  46.                 $user,
  47.                 (new TemplatedEmail())
  48.                     ->from(new Address('example@example.com''Vrshikyans'))
  49.                     ->to($user->getEmail())
  50.                     ->subject('Please Confirm your Email')
  51.                     ->htmlTemplate('registration/confirmation_email.html.twig')
  52.             );
  53.             return $this->redirectToRoute('sonata_admin_dashboard');
  54.         }
  55.         return $this->render('registration/register.html.twig', [
  56.             'registrationForm' => $form->createView(),
  57.         ]);
  58.     }
  59.     #[Route('/auth_register'name'app_auth_register'methods: ['POST'])]
  60.     public function authRegister(
  61.         Request $request,
  62.         UserPasswordHasherInterface $userPasswordHasher,
  63.         EntityManagerInterface $entityManager
  64.     ): \Symfony\Component\HttpFoundation\JsonResponse
  65.     {
  66.         // Only accept JSON
  67.         $data json_decode($request->getContent(), true);
  68.         if (!$data) {
  69.             return $this->json(['message' => 'Invalid JSON'], 400);
  70.         }
  71.         $username $data['username'] ?? null;
  72.         $email $data['email'] ?? null;
  73.         $password $data['password'] ?? null;
  74.         $errors = [];
  75.         // Validate username
  76.         if (!$username || strlen($username) < 3) {
  77.             $errors['username'] = 'Username should be at least 3 characters.';
  78.         }
  79.         // Validate email
  80.         if (!$email || !filter_var($emailFILTER_VALIDATE_EMAIL)) {
  81.             $errors['email'] = 'Enter a valid email address.';
  82.         }
  83.         // Validate password
  84.         if (!$password || strlen($password) < 8) {
  85.             $errors['password'] = 'Password should be at least 8 characters.';
  86.         }
  87.         if ($errors) {
  88.             return $this->json(['message' => 'Validation failed''errors' => $errors], 400);
  89.         }
  90.         // Create user
  91.         $user = new User();
  92.         $user->setUsername($username);
  93.         $user->setEmail($email);
  94.         $user->setPassword($userPasswordHasher->hashPassword($user$password));
  95.         $entityManager->persist($user);
  96.         $entityManager->flush();
  97.         // Send email verification
  98.         $this->emailVerifier->sendEmailConfirmation(
  99.             'app_verify_email',
  100.             $user,
  101.             (new TemplatedEmail())
  102.                 ->from(new Address('example@example.com''Vrshikyans'))
  103.                 ->to($user->getEmail())
  104.                 ->subject('Please Confirm your Email')
  105.                 ->htmlTemplate('registration/confirmation_email.html.twig')
  106.         );
  107.         return $this->json([
  108.             'message' => 'Account created successfully. Please check your email to verify.'
  109.         ], 200);
  110.     }
  111.     #[Route('/verify/email'name'app_verify_email')]
  112.     public function verifyUserEmail(Request $requestTranslatorInterface $translator): Response
  113.     {
  114.         $this->denyAccessUnlessGranted('IS_AUTHENTICATED_FULLY');
  115.         // validate email confirmation link, sets User::isVerified=true and persists
  116.         try {
  117.             $this->emailVerifier->handleEmailConfirmation($request$this->getUser());
  118.         } catch (VerifyEmailExceptionInterface $exception) {
  119.             $this->addFlash('verify_email_error'$translator->trans($exception->getReason(), [], 'VerifyEmailBundle'));
  120.             return $this->redirectToRoute('app_register');
  121.         }
  122.         // @TODO Change the redirect on success and handle or remove the flash message in your templates
  123.         $this->addFlash('success''Your email address has been verified.');
  124.         return $this->redirectToRoute('app_register');
  125.     }
  126. }