src/Ecommerce/Controller/RegisterController.php line 150

Open in your IDE?
  1. <?php
  2. namespace App\Ecommerce\Controller;
  3. use App\Form\Type\RegistrationType;
  4. use App\Security\OAuth\OAuthRegistrationHandler;
  5. use CoreShop\Bundle\CoreBundle\Event\CustomerRegistrationEvent;
  6. use CoreShop\Bundle\CoreBundle\Form\DataMapper\CustomerDataMapper;
  7. use CoreShop\Bundle\UserBundle\Event\RequestPasswordChangeEvent;
  8. use CoreShop\Bundle\UserBundle\Form\Type\RequestResetPasswordType;
  9. use CoreShop\Bundle\UserBundle\Form\Type\ResetPasswordType;
  10. use CoreShop\Component\Core\Model\CustomerInterface;
  11. use CoreShop\Component\Core\Model\UserInterface;
  12. use Exception;
  13. use HWI\Bundle\OAuthBundle\OAuth\Response\UserResponseInterface;
  14. use HWI\Bundle\OAuthBundle\Security\Core\Authentication\Token\OAuthToken;
  15. use HWI\Bundle\OAuthBundle\Security\Core\Exception\AccountNotLinkedException;
  16. use Pimcore\Model\DataObject\CoreShopCustomer;
  17. use RuntimeException;
  18. use Symfony\Component\EventDispatcher\EventDispatcherInterface;
  19. use Symfony\Component\EventDispatcher\GenericEvent;
  20. use Symfony\Component\Form\Form;
  21. use Symfony\Component\Form\FormError;
  22. use Symfony\Component\HttpFoundation\Request;
  23. use Symfony\Component\HttpFoundation\Response;
  24. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  25. use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
  26. use Pimcore\Twig\Extension\Templating\Placeholder;
  27. use Symfony\Component\Uid\Uuid;
  28. use CoreShop\Bundle\FrontendBundle\Controller\RegisterController as BaseRegisterController;
  29. class RegisterController extends BaseRegisterController
  30. {
  31.     public function __construct(
  32.         private readonly OAuthRegistrationHandler $oAuthHandler,
  33.         private readonly EventDispatcherInterface $eventDispatcher,
  34.         private readonly AuthenticationUtils      $authenticationUtils,
  35.         private readonly Placeholder              $placeholder
  36.     )
  37.     {
  38.     }
  39.     /**
  40.      * @param Request $request
  41.      * @return Response
  42.      * @throws Exception
  43.      */
  44.     public function registerAction(Request $request): Response
  45.     {
  46.         if (($customer $this->getCustomer()) instanceof CustomerInterface && null !== $customer->getUser()) {
  47.             return $this->redirectToRoute('coreshop_customer_profile');
  48.         }
  49.         $token null;
  50.         $lastError $this->authenticationUtils->getLastAuthenticationError(false);
  51.         if ($lastError instanceof AccountNotLinkedException) {
  52.             $token $lastError->getToken();
  53.         }
  54.         if ($lastError && $lastError->getPrevious() instanceof AccountNotLinkedException) {
  55.             $token $lastError->getPrevious()->getToken();
  56.         }
  57.         $registrationKey null;
  58.         $oAuthToken null;
  59.         $oAuthUserInfo null;
  60.         if ($token instanceof OAuthToken) {
  61.             $registrationKey Uuid::v4()->toRfc4122();
  62.             $this->oAuthHandler->saveToken($registrationKey$token);
  63.         }
  64.         if (null !== $registrationKey) {
  65.             $oAuthToken $this->oAuthHandler->loadToken($registrationKey);
  66.             $oAuthUserInfo $this->oAuthHandler->loadUserInformation($oAuthToken);
  67.         }
  68.         if ($oAuthUserInfo instanceof UserResponseInterface) {
  69.             if ($this->oAuthHandler->getCustomerFromUserResponse($oAuthUserInfo)) {
  70.                 throw new RuntimeException('Customer is already registered');
  71.             }
  72.         }
  73.         $redirect $this->getParameterFromRequest($request'_redirect'$this->generateUrl('profil'));
  74.         if ($oAuthToken instanceof OAuthToken) {
  75.             $form $this->container->get('form.factory')->createNamed('customer'RegistrationType::class, $this->container->get('coreshop.factory.customer')->createNew());
  76.             $array $this->mergeOAuthFormData([], $oAuthUserInfo);
  77.             if (!$array['firstname']) {
  78.                 $array['firstname'] = sprintf('N/A (%s login)'$oAuthToken->getResourceOwnerName());
  79.             }
  80.             if (!$array['lastname']) {
  81.                 $array['lastname'] = sprintf('N/A (%s login)'$oAuthToken->getResourceOwnerName());
  82.             }
  83.             $form->submit($array);
  84.             $mapper = new CustomerDataMapper();
  85.             $customer $form->getData();
  86.             $mapper->mapFormsToData($form$customer);
  87.             $checkCustomer CoreShopCustomer::getByEmail($customer->getEmail(), ['limit' => 1'unpublished' => true]);
  88.             if (!$checkCustomer) {
  89.                 $this->container->get('coreshop.customer.manager')->persistCustomer($customer);
  90.             } else {
  91.                 $customer $checkCustomer;
  92.                 if (!$customer->getPublished()) {
  93.                     $customer->setPublished(true);
  94.                     $customer->save();
  95.                 }
  96.             }
  97.             $this->oAuthHandler->connectSsoIdentity($customer->getUser(), $oAuthUserInfo);
  98.             // todo login and fire events after oauth registration
  99.             $this->eventDispatcher->dispatch(new CustomerRegistrationEvent($customer, ['type' => 'oAuthRegister']), 'coreshop.customer.register');
  100.             return $this->redirect($redirect);
  101.         }
  102.         /** @var Form $form */
  103.         $form $this->container->get('form.factory')->createNamed('customer'RegistrationType::class, $this->container->get('coreshop.factory.customer')->createNew());
  104.         if (in_array($request->getMethod(), ['POST''PUT''PATCH'], true)) {
  105.             $form $form->handleRequest($request);
  106.             if ($form->isSubmitted() && $form->isValid()) {
  107.                 $customer $form->getData();
  108.                 $customer->setLocaleCode($this->container->get('coreshop.context.locale')->getLocaleCode());
  109.                 try {
  110.                     $this->container->get('coreshop.customer.manager')->persistCustomer($customer);
  111.                     $this->eventDispatcher->dispatch(new CustomerRegistrationEvent($customer, ['type' => 'formRegister']), 'coreshop.customer.register');
  112.                     $this->addFlash('success''Sikeres regisztráció!<br>A regisztráció véglegesítéséhez szükséges információkat elküldtük a regisztrációkor megadott e-mail címre!');
  113.                     return $this->redirect($redirect);
  114.                 } catch (Exception $e) {
  115.                     $form->get('email')->addError(new FormError($e->getMessage()));
  116.                 }
  117.             }
  118.         }
  119.         $layout $this->templateConfigurator->findTemplate('Register/register.html');
  120.         $bc = [
  121.             ['title' => 'Főoldal''path' => '/'],
  122.             ['title' => 'Profil''path' => null],
  123.         ];
  124.         $pl $this->placeholder;
  125.         $pl('breadcrumbNews')->set($bc);
  126.         return $this->render($layout, [
  127.             'lastError' => $lastError,
  128.             'form' => $form->createView(),
  129.         ]);
  130.     }
  131.     public function passwordResetRequestAction(Request $request): Response
  132.     {
  133.         $resetIdentifier $this->container->getParameter('coreshop.customer.security.login_identifier');
  134.         $form $this->container->get('form.factory')->createNamed('coreshop'RequestResetPasswordType::class, null, ['reset_identifier' => $resetIdentifier]);
  135.         if (in_array($request->getMethod(), ['POST''PUT''PATCH'], true)) {
  136.             $handledForm $form->handleRequest($request);
  137.             if ($handledForm->isSubmitted() && $handledForm->isValid()) {
  138.                 $passwordResetData $handledForm->getData();
  139.                 $user $this->container->get('coreshop.repository.user')->findByLoginIdentifier($passwordResetData['email']);
  140.                 if (!$user instanceof UserInterface) {
  141.                     return $this->redirectToRoute('profil');
  142.                 }
  143.                 $user->setPasswordResetHash($this->generateResetPasswordHash($user));
  144.                 $user->save();
  145.                 $resetLink $this->generateUrl('coreshop_customer_password_reset', ['token' => $user->getPasswordResetHash()], UrlGeneratorInterface::ABSOLUTE_URL);
  146.                 $dispatcher $this->container->get('event_dispatcher');
  147.                 $dispatcher->dispatch(new RequestPasswordChangeEvent($user$resetLink), 'coreshop.user.request_password_reset');
  148.                 $this->addFlash('success'$this->container->get('translator')->trans('coreshop.ui.password_reset_request_success'));
  149.                 return $this->redirectToRoute('profil');
  150.             }
  151.         }
  152.         $bc = [
  153.             [
  154.                 'title' => 'Főoldal',
  155.                 'path' => '/'
  156.             ],
  157.             [
  158.                 'title' => 'Profil',
  159.                 'path' => $this->generateUrl('profil')
  160.             ],
  161.             [
  162.                 'title' => 'Elfelejtett jelszó',
  163.                 'path' => null
  164.             ],
  165.         ];
  166.         $pl $this->placeholder;
  167.         $pl('breadcrumbNews')->set($bc);
  168.         return $this->render($this->templateConfigurator->findTemplate('Register/password-reset-request.html'), [
  169.             'form' => $form->createView(),
  170.         ]);
  171.     }
  172.     public function passwordResetAction(Request $request): Response
  173.     {
  174.         $resetToken $this->getParameterFromRequest($request'token');
  175.         if ($resetToken) {
  176.             /**
  177.              * @var UserInterface $user
  178.              */
  179.             $user $this->container->get('coreshop.repository.user')->findByResetToken($resetToken);
  180.             if (!$user instanceof UserInterface) {
  181.                 return $this->redirectToRoute('profil');
  182.             }
  183.             $form $this->container->get('form.factory')->createNamed('coreshop'ResetPasswordType::class);
  184.             if (in_array($request->getMethod(), ['POST''PUT''PATCH'], true)) {
  185.                 $handledForm $form->handleRequest($request);
  186.                 if ($handledForm->isSubmitted() && $handledForm->isValid()) {
  187.                     $resetPassword $handledForm->getData();
  188.                     $user->setPasswordResetHash(null);
  189.                     $user->setPassword($resetPassword['password']);
  190.                     $user->save();
  191.                     $this->addFlash('success'$this->container->get('translator')->trans('coreshop.ui.password_reset_success'));
  192.                     $dispatcher $this->container->get('event_dispatcher');
  193.                     $dispatcher->dispatch(new GenericEvent($user), 'coreshop.user.password_reset');
  194.                     return $this->redirectToRoute('profil');
  195.                 }
  196.             }
  197.             $bc = [
  198.                 [
  199.                     'title' => 'Főoldal',
  200.                     'path' => '/'
  201.                 ],
  202.                 [
  203.                     'title' => 'Profil',
  204.                     'path' => $this->generateUrl('profil')
  205.                 ],
  206.                 [
  207.                     'title' => 'Jelszó visszaállítás',
  208.                     'path' => null
  209.                 ],
  210.             ];
  211.             $pl $this->placeholder;
  212.             $pl('breadcrumbNews')->set($bc);
  213.             return $this->render($this->templateConfigurator->findTemplate('Register/password-reset.html'), [
  214.                 'form' => $form->createView(),
  215.             ]);
  216.         }
  217.         return $this->redirectToRoute('profil');
  218.     }
  219.     /**
  220.      *
  221.      * @param array $formData
  222.      * @param UserResponseInterface $userInformation
  223.      *
  224.      * @return array
  225.      */
  226.     private function mergeOAuthFormData(
  227.         array                 $formData,
  228.         UserResponseInterface $userInformation
  229.     ): array
  230.     {
  231.         return array_replace([
  232.             'firstname' => $userInformation->getFirstName(),
  233.             'lastname' => $userInformation->getLastName(),
  234.             'email' => $userInformation->getEmail()
  235.         ], $formData);
  236.     }
  237. }