src/Controller/RegistrationController.php line 221

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\Components\PaymentStatus;
  4. use App\Entity\Account;
  5. use App\Entity\ApiKey;
  6. use App\Entity\Payment;
  7. use App\Entity\Plan;
  8. use App\Entity\Service;
  9. use App\Form\RegistrationFormType;
  10. use App\Repository\AccountRepository;
  11. use App\Security\EmailVerifier;
  12. use App\Security\LoginFormAuthenticator;
  13. use App\Services\ApiKeyGenerator;
  14. use App\Services\MailHandler;
  15. use Symfony\Bridge\Twig\Mime\TemplatedEmail;
  16. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  17. use Symfony\Component\HttpFoundation\Request;
  18. use Symfony\Component\HttpFoundation\Response;
  19. use Symfony\Component\HttpFoundation\Session\SessionInterface;
  20. use Symfony\Component\Mime\Address;
  21. use Symfony\Component\Routing\Annotation\Route;
  22. use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
  23. use Symfony\Component\Security\Guard\GuardAuthenticatorHandler;
  24. use SymfonyCasts\Bundle\VerifyEmail\Exception\VerifyEmailExceptionInterface;
  25. use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
  26. class RegistrationController extends AbstractController
  27. {
  28.     private $emailVerifier;
  29.     private $session;
  30.     private $apiKeyGenerator;
  31.     private $mailHandler;
  32.     public function __construct(
  33.         EmailVerifier $emailVerifier,
  34.         SessionInterface $session,
  35.         ApiKeyGenerator $apiKeyGenerator,
  36.         MailHandler $mailHandler
  37.     ) {
  38.         $this->emailVerifier $emailVerifier;
  39.         $this->session $session;
  40.         $this->apiKeyGenerator $apiKeyGenerator;
  41.         $this->mailHandler $mailHandler;
  42.     }
  43.     /**
  44.      * @param Request $request
  45.      * @return Response
  46.      *
  47.      * @Route("/register/thank-you", name="app_register_thankyou")
  48.      */
  49.     public function finishedRegistration(Request $request): Response
  50.     {
  51.         return $this->render('registration/thank_you.html.twig');
  52.     }
  53.     /**
  54.      * @Route("/verify/email", name="app_verify_email")
  55.      */
  56.     public function verifyUserEmail(
  57.         Request $request,
  58.         AccountRepository $accountRepository,
  59.         GuardAuthenticatorHandler $guardHandler,
  60.         LoginFormAuthenticator $authenticator
  61.     ): Response {
  62.         $id $request->get('id');
  63.         if (null === $id) {
  64.             return $this->redirectToRoute('app_register');
  65.         }
  66.         $user $accountRepository->find($id);
  67.         if (null === $user) {
  68.             return $this->redirectToRoute('app_register');
  69.         }
  70.         // validate email confirmation link, sets User::isVerified=true and persists
  71.         try {
  72.             $this->emailVerifier->handleEmailConfirmation($request$user);
  73.         } catch (VerifyEmailExceptionInterface $exception) {
  74.             $this->addFlash('verify_email_error'$exception->getReason());
  75.             // generate a signed url and email it to the user
  76.             $this->emailVerifier->sendEmailConfirmation('app_verify_email'$user,
  77.                 (new TemplatedEmail())
  78.                     ->from(new Address('support@theeasyapi.com''The Easy API'))
  79.                     ->to($user->getEmail())
  80.                     ->subject('Please Confirm your Email')
  81.                     ->htmlTemplate('registration/confirmation_email.html.twig')
  82.             );
  83.             return $this->redirectToRoute('app_register_thankyou');
  84.         }
  85.         $this->addFlash('success''Your email address has been verified.');
  86.         if ($user->getPlan()) {
  87.             return $guardHandler->authenticateUserAndHandleSuccess(
  88.                 $user,
  89.                 $request,
  90.                 $authenticator,
  91.                 'main' // firewall name in security.yaml
  92.             );
  93.         }
  94.         $this->session->set('userId'$user->getId());
  95.         return $this->redirectToRoute('app_register_plan', ['plan' => $user->getDesiredPlan()->getName()]);
  96.     }
  97.     /**
  98.      * @param Plan $plan
  99.      * @param string|null $auth
  100.      * @return Response
  101.      *
  102.      * @Route("/register/plan/{plan}", name="app_register_plan")
  103.      * @Route("/register/plan/{plan}/{auth}", name="app_register_plan_auth")
  104.      * @ParamConverter("plan", options={"mapping": {"plan":"name"}})
  105.      */
  106.     public function registerPlan(Plan $plan$auth null): Response
  107.     {
  108.         // Catch someone coming from an email with an auth token set
  109.         if ($auth) {
  110.             $userId $this->apiKeyGenerator->getUserIdFromKey($auth);
  111.             // They either waited more than a year, or messed up the token
  112.             if (!$userId) {
  113.                 return $this->redirectToRoute("app_login");
  114.             }
  115.             $this->session->set('userId'$userId);
  116.         } else {
  117.             $userId $this->session->get('userId');
  118.         }
  119.         /** @var Account $user */
  120.         $user $this->getDoctrine()->getRepository(Account::class)->findOneById($userId);
  121.         if ($user->getPlan()) {
  122.             $this->addFlash("flash_success""You have already completed this step, please login.");
  123.             return $this->redirectToRoute("app_login");
  124.         }
  125.         // Catch a logged in user, set their UserId
  126.         if ($this->getUser()) {
  127.             $user $this->getDoctrine()->getRepository(Account::class)->findOneByEmail($this->getUser()->getUsername());
  128.             $this->session->set('userId'$user->getId());
  129.         }
  130.         $plans $this->getDoctrine()->getRepository(Plan::class)->findBy([
  131.             'version' => 2,
  132.             'show' => 1
  133.         ], ['price' => 'DESC']);
  134.         return $this->render('registration/register_plan.html.twig', [
  135.             'plans' => $plans,
  136.             'plan' => $plan
  137.         ]);
  138.     }
  139.     /**
  140.      * @param Request $request
  141.      * @param AccountRepository $accountRepository
  142.      * @param GuardAuthenticatorHandler $guardHandler
  143.      * @param LoginFormAuthenticator $authenticator
  144.      * @param Plan $plan
  145.      * @return Response
  146.      *
  147.      * @Route("/register/complete/{plan}", name="app_complete_plan")
  148.      * @ParamConverter("plan", options={"mapping": {"plan":"name"}})
  149.      */
  150.     public function completeRegistration(
  151.         Request $request,
  152.         AccountRepository $accountRepository,
  153.         GuardAuthenticatorHandler $guardHandler,
  154.         LoginFormAuthenticator $authenticator,
  155.         Plan $plan
  156.     ): Response {
  157.         $user $accountRepository->find($this->session->get('userId'));
  158.         if (null === $user) {
  159.             return $this->redirectToRoute('app_register');
  160.         }
  161.         if ($plan->getPrice() > 0) {
  162.             $payment $this->getDoctrine()->getRepository(Payment::class)->findOneBy([
  163.                 'account' => $user,
  164.                 'status' => PaymentStatus::INITIALIZED
  165.             ]);
  166.             if (!$payment) {
  167.                 return $this->redirectToRoute('app_register_plan', ['plan' => $plan->getName()]);
  168.             }
  169.         }
  170.         // Set the plan they picked
  171.         $user->setPlan($plan);
  172.         $entityManager $this->getDoctrine()->getManager();
  173.         $entityManager->persist($user);
  174.         $entityManager->flush();
  175.         return $guardHandler->authenticateUserAndHandleSuccess(
  176.             $user,
  177.             $request,
  178.             $authenticator,
  179.             'main' // firewall name in security.yaml
  180.         );
  181.     }
  182.     /**
  183.      * @Route("/register/{plan}", name="app_register")
  184.      * @ParamConverter("plan", options={"mapping": {"plan":"name"}})
  185.      *
  186.      * @param Request $request
  187.      * @param UserPasswordEncoderInterface $passwordEncoder
  188.      * @param Plan|null $plan
  189.      * @return Response
  190.      */
  191.     public function register(
  192.         Request $request,
  193.         UserPasswordEncoderInterface $passwordEncoder,
  194.         Plan $plan null
  195.     ): Response {
  196.         if (!$plan) {
  197.             $plan $this->getDoctrine()->getRepository(Plan::class)->findOneBy([
  198.                 'version' => 2,
  199.                 'name' => 'Starter'
  200.             ]);
  201.         }
  202.         $user = new Account();
  203.         $user->setDesiredPlan($plan);
  204.         $form $this->createForm(RegistrationFormType::class, $user);
  205.         $form->handleRequest($request);
  206.         if ($form->isSubmitted() && $form->isValid()) {
  207.             // encode the plain password
  208.             $user->setPassword(
  209.                 $passwordEncoder->encodePassword(
  210.                     $user,
  211.                     $form->get('plainPassword')->getData()
  212.                 )
  213.             );
  214.             $nameArr explode(" "$form->get('name')->getData(), 2);
  215.             if (count($nameArr) == 1) {
  216.                 $user->setFirstname($nameArr[0]);
  217.                 $user->setLastname(" ");
  218.             } else {
  219.                 $user->setFirstname($nameArr[0]);
  220.                 $user->setLastname($nameArr[1]);
  221.             }
  222.             try {
  223.                 $entityManager $this->getDoctrine()->getManager();
  224.                 $entityManager->persist($user);
  225.                 $entityManager->flush();
  226.             } catch (\Exception $e) {
  227.                 $this->addFlash("flash_error",
  228.                     "We were unable to create your account. Please check your information and try again.");
  229.                 return $this->redirectToRoute("app_register");
  230.             }
  231.             // Create a default API Key
  232.             $apiKey = new ApiKey($user);
  233.             $apiKey->setName("Default")->setApikey($this->apiKeyGenerator->createKey($user));
  234.             $entityManager->persist($apiKey);
  235.             $entityManager->flush();
  236.             // Setting the user
  237.             $this->session->set('userId'$user->getId());
  238.             // Send e-mail
  239.             $this->mailHandler->sendRegistration($user$apiKey);
  240.             return $this->redirectToRoute('app_register_plan', ['plan' => $user->getDesiredPlan()->getName()]);
  241.         }
  242.         return $this->render('registration/register.html.twig', [
  243.             'registrationForm' => $form->createView(),
  244.         ]);
  245.     }
  246. }