src/Controller/RegistrationController.php line 288

  1. <?php
  2. namespace App\Controller;
  3. use App\Entity\User;
  4. use App\Form\RegistrationFormType;
  5. use App\Repository\UserRepository;
  6. use App\Security\AppAuthenticator;
  7. use App\Security\EmailVerifier;
  8. use Doctrine\ORM\EntityManagerInterface;
  9. use Symfony\Bridge\Twig\Mime\TemplatedEmail;
  10. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  11. use Symfony\Component\HttpFoundation\Request;
  12. use Symfony\Component\HttpFoundation\Response;
  13. use Symfony\Component\Mime\Address;
  14. use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
  15. use Symfony\Component\Routing\Annotation\Route;
  16. use Symfony\Component\Security\Http\Authentication\UserAuthenticatorInterface;
  17. use Symfony\Contracts\Translation\TranslatorInterface;
  18. use SymfonyCasts\Bundle\VerifyEmail\Exception\VerifyEmailExceptionInterface;
  19. use Symfony\Component\HttpFoundation\JsonResponse;
  20. use Symfony\Component\Validator\Validator\ValidatorInterface;
  21. use Symfony\Component\Validator\Constraints as Assert;
  22. use Symfony\Component\Security\Core\Exception\AuthenticationException;
  23. class RegistrationController extends AbstractController
  24. {
  25.     private EmailVerifier $emailVerifier;
  26.     public function __construct(EmailVerifier $emailVerifier)
  27.     {
  28.         $this->emailVerifier $emailVerifier;
  29.     }
  30. #[Route('/api/cities'name'get_moroccan_cities'methods: ['GET'])]
  31. public function getMoroccanCities(): JsonResponse
  32. {
  33.     $cities = [
  34.         "Casablanca""Rabat""Marrakech""Fes""Tangier""Agadir""Meknes",
  35.         "Oujda""Kenitra""Tetouan""Safi""El Jadida""Nador""Beni Mellal",
  36.         "Khouribga""Taza""Mohammedia""Settat""Laayoune""Dakhla"
  37.     ];
  38.     return new JsonResponse($citiesJsonResponse::HTTP_OK);
  39. }
  40. #[Route('/api/register'name'api_register'methods: ['POST'])]
  41. public function apiRegister(Request $request
  42.                              UserPasswordHasherInterface $userPasswordHasher
  43.                              UserAuthenticatorInterface $userAuthenticator
  44.                              AppAuthenticator $authenticator
  45.                              EntityManagerInterface $entityManager,
  46.                              ValidatorInterface $validator): JsonResponse
  47. {
  48.     // Decode JSON request
  49.     $data json_decode($request->getContent(), true);
  50.     // Check if the necessary fields are present in the request
  51.     if (!isset($data['email'], $data['password'], $data['fname'], $data['lname'], $data['phone'])) {
  52.         return new JsonResponse(['error' => 'Missing required fields'], Response::HTTP_CREATED);
  53.     }
  54.     // Validate email format
  55.     $emailConstraint = new Assert\Email();
  56.     $emailViolation $validator->validate($data['email'], $emailConstraint);
  57.     if (count($emailViolation) > 0) {
  58.         return new JsonResponse(['error' => 'Invalid email format'], Response::HTTP_CREATED);
  59.     }
  60.     // Check if email already exists
  61.     $existingUser $entityManager->getRepository(User::class)->findOneBy(['email' => $data['email']]);
  62.     if ($existingUser) {
  63.         return new JsonResponse(['error' => 'Email already in use'], Response::HTTP_CREATED);
  64.     }
  65.     // Validate phone number format (you can adjust the regex for more specific formats)
  66.     $phoneConstraint = new Assert\Regex([
  67.         'pattern' => '/^\+?[0-9]{10,15}$/'// Example regex: Adjust according to your phone number format
  68.         'message' => 'Invalid phone number format'
  69.     ]);
  70.     $phoneViolation $validator->validate($data['phone'], $phoneConstraint);
  71.     if (count($phoneViolation) > 0) {
  72.         return new JsonResponse(['error' => 'Invalid phone number format'], Response::HTTP_CREATED);
  73.     }
  74.     // Create a new User entity
  75.     $user = new User();
  76.     $user->setEmail($data['email']);
  77.     $user->setFname($data['fname']);
  78.     $user->setLName($data['lname']);
  79.     $user->setPhone($data['phone']);
  80.    if (isset($data['type'])) {
  81.       $user->setType($data['type']);
  82.     }
  83.  if (isset($data['identity'])) {
  84.       $user->setIdentity($data['identity']);
  85.     }
  86.  if (isset($data['city'])) {
  87.       $user->setCity($data['city']);
  88.     }
  89.     // Hash the password
  90.     $user->setPassword($userPasswordHasher->hashPassword($user$data['password']));
  91.     // Set default roles and other properties
  92.     $user->setStatus(0);
  93.     $user->setRoles(["ROLE_USER"]);
  94.     
  95.     // Persist the user to the database
  96.     try {
  97.         $entityManager->persist($user);
  98.         $entityManager->flush();
  99.     } catch (\Exception $e) {
  100.         return new JsonResponse(['error' => 'Error while saving user to database'], Response::HTTP_INTERNAL_SERVER_ERROR);
  101.     }
  102.     // Send email confirmation (if needed for your API, you can skip this if not required)
  103.     // Authenticate the user (optional, if you want to log them in automatically after registration)
  104.     try {
  105.         $userAuthenticator->authenticateUser(
  106.             $user,
  107.             $authenticator,
  108.             $request
  109.         );
  110.     } catch (AuthenticationException $e) {
  111.         return new JsonResponse(['error' => 'Authentication error'], Response::HTTP_CREATED);
  112.     }
  113.     // Return success response with user details (excluding sensitive data like password)
  114.     return new JsonResponse([
  115.         'message' => 'User registered successfully',
  116.         'user' => [
  117.             'id' => $user->getId(),
  118.             'email' => $user->getEmail(),
  119.             'roles' => $user->getRoles()
  120.         ]
  121.     ], Response::HTTP_CREATED);
  122. }
  123. #[Route('/api/update-profile'name'api_update_profile'methods: ['PATCH'])]
  124. public function updateProfile(Request $request
  125.                               EntityManagerInterface $entityManager
  126.                               ValidatorInterface $validator,
  127.                               UserPasswordHasherInterface $userPasswordHasher): JsonResponse
  128. {
  129.     // Assuming user is authenticated via token or session and we fetch the user ID from the token/session
  130.     // Here we assume that the user object is retrieved from the security context (i.e., the logged-in user).
  131.     $user $this->getUser(); // Get the authenticated user
  132.     if (!$user) {
  133.         return new JsonResponse(['error' => 'User not authenticated'], Response::HTTP_OK);
  134.     }
  135.     // Decode JSON request
  136.     $data json_decode($request->getContent(), true);
  137.     // Check if the necessary fields are present
  138.  if (isset($data['email'])) {
  139.     // Validate email format
  140.     $emailConstraint = new Assert\Email();
  141.     $emailViolation $validator->validate($data['email'], $emailConstraint);
  142.     if (count($emailViolation) > 0) {
  143.         return new JsonResponse(['error' => 'Invalid email format'], Response::HTTP_OK);
  144.     }
  145.     // Check if the email already exists for another user (excluding the current user)
  146.     $existingUser $entityManager->getRepository(User::class)->findOneBy(['email' => $data['email']]);
  147.     if ($existingUser && $existingUser->getId() !== $user->getId()) {
  148.         return new JsonResponse(['error' => 'Email already in use by another user'], Response::HTTP_OK);
  149.     }
  150.  }
  151.  if (isset($data['phone'])) {
  152.     // Validate phone number format (adjust regex as needed)
  153.     $phoneConstraint = new Assert\Regex([
  154.         'pattern' => '/^\+?[0-9]{10,15}$/',
  155.         'message' => 'Invalid phone number format'
  156.     ]);
  157.     $phoneViolation $validator->validate($data['phone'], $phoneConstraint);
  158.     if (count($phoneViolation) > 0) {
  159.         return new JsonResponse(['error' => 'Invalid phone number format'], Response::HTTP_OK);
  160.     }
  161.  }
  162.     // Update the user information
  163.  
  164.  if (isset($data['email'])) {
  165.       $user->setEmail($data['email']);
  166.     }
  167.    
  168.  if (isset($data['fname'])) {
  169.       $user->SetFname($data['fname']);
  170.     }
  171.  
  172.  if (isset($data['lname'])) {
  173.       $user->SetLname($data['lname']);
  174.     }
  175.  
  176.  if (isset($data['phone'])) {
  177.       $user->SetPhone($data['phone']);
  178.     }
  179.    if (isset($data['type'])) {
  180.       $user->setType($data['type']);
  181.     }
  182.    if (isset($data['identity'])) {
  183.       $user->setIdentity($data['identity']);
  184.     }
  185.  if (isset($data['city'])) {
  186.       $user->setCity($data['city']);
  187.     }
  188.     // Optionally update password if provided (ensure password is hashed)
  189.     if (isset($data['password']) && !empty($data['password'])) {
  190.         $user->setPassword($userPasswordHasher->hashPassword($user$data['password']));
  191.     }
  192.     // Persist the updated user to the database
  193.     try {
  194.         $entityManager->persist($user);
  195.         $entityManager->flush();
  196.     } catch (\Exception $e) {
  197.         return new JsonResponse(['error' => 'Error while updating user in the database'], Response::HTTP_OK);
  198.     }
  199.     // Return success response with updated user details (excluding sensitive data like password)
  200.     return new JsonResponse([
  201.         'message' => 'User profile updated successfully',
  202.         'user' => [
  203.             'id' => $user->getId(),
  204.             'email' => $user->getEmail(),
  205.             'fname' => $user->getFname(),
  206.             'lname' => $user->getLName(),
  207.             'phone' => $user->getPhone(),
  208.             'roles' => $user->getRoles()
  209.         ]
  210.     ], Response::HTTP_OK);
  211. }
  212.     #[Route('/register'name'app_register')]
  213.     public function register(Request $requestUserPasswordHasherInterface $userPasswordHasherUserAuthenticatorInterface $userAuthenticatorAppAuthenticator $authenticatorEntityManagerInterface $entityManager): Response
  214.     {
  215.         $user = new User();
  216.         $form $this->createForm(RegistrationFormType::class, $user);
  217.         $form->handleRequest($request);
  218.         if ($form->isSubmitted() && $form->isValid()) {
  219.             // encode the plain password
  220.             $user->setPassword(
  221.                 $userPasswordHasher->hashPassword(
  222.                     $user,
  223.                     $form->get('plainPassword')->getData()
  224.                 )
  225.             );
  226.             $user->setStatus(1);
  227.             $user->setRoles(["ROLE_USER","ROLE_BTOB_ADMIN"]);
  228.             $user->setType('B2B');
  229.             $entityManager->persist($user);
  230.             $entityManager->flush();
  231.             // generate a signed url and email it to the user
  232.             $this->emailVerifier->sendEmailConfirmation('app_verify_email'$user,
  233.                 (new TemplatedEmail())
  234.                     ->from(new Address('no-reply@metacard.gift''Email confirmation - Metacard'))
  235.                     ->to($user->getEmail())
  236.                     ->subject('Please Confirm your Email')
  237.                     ->htmlTemplate('registration/confirmation_email.html.twig')
  238.             );
  239.             // do anything else you need here, like send an email
  240.             return $userAuthenticator->authenticateUser(
  241.                 $user,
  242.                 $authenticator,
  243.                 $request
  244.             );
  245.         }
  246.         return $this->render('registration/register.html.twig', [
  247.             'registrationForm' => $form->createView(),
  248.         ]);
  249.     }
  250.     #[Route('/verify/email'name'app_verify_email')]
  251.     public function verifyUserEmail(Request $requestTranslatorInterface $translatorUserRepository $userRepository): Response
  252.     {
  253.         $id $request->get('id');
  254.         if (null === $id) {
  255.             return $this->redirectToRoute('app_register');
  256.         }
  257.         $user $userRepository->find($id);
  258.         if (null === $user) {
  259.             return $this->redirectToRoute('app_register');
  260.         }
  261.         // validate email confirmation link, sets User::isVerified=true and persists
  262.         try {
  263.             $this->emailVerifier->handleEmailConfirmation($request$user);
  264.         } catch (VerifyEmailExceptionInterface $exception) {
  265.             $this->addFlash('verify_email_error'$translator->trans($exception->getReason(), [], 'VerifyEmailBundle'));
  266.             return $this->redirectToRoute('app_register');
  267.         }
  268.         // @TODO Change the redirect on success and handle or remove the flash message in your templates
  269.         $this->addFlash('success''Your email address has been verified.');
  270.         return $this->redirectToRoute('dashboard');
  271.     }
  272. }