src/CoreBundle/Controller/AccountController.php line 34

Open in your IDE?
  1. <?php
  2. namespace CoreBundle\Controller;
  3. use CoreBundle\Form\RequestPasswordResetFormType;
  4. use CoreBundle\Form\ResetPasswordFormType;
  5. use CoreBundle\Model\Customer;
  6. use CoreBundle\Form\LoginFormType;
  7. use CoreBundle\Form\RegistrationFormHandler;
  8. use CoreBundle\Form\RegistrationFormType;
  9. use CustomerManagementFrameworkBundle\CustomerProvider\CustomerProviderInterface;
  10. use CustomerManagementFrameworkBundle\CustomerSaveValidator\Exception\DuplicateCustomerException;
  11. use CustomerManagementFrameworkBundle\Security\Authentication\LoginManagerInterface;
  12. use CustomerManagementFrameworkBundle\Security\OAuth\Exception\AccountNotLinkedException;
  13. use CustomerManagementFrameworkBundle\Security\OAuth\OAuthRegistrationHandler;
  14. use Pimcore\Bundle\EcommerceFrameworkBundle\EnvironmentInterface;
  15. use Pimcore\Bundle\EcommerceFrameworkBundle\IEnvironment;
  16. use Pimcore\Mail;
  17. use Pimcore\Model\Document;
  18. use Pimcore\Model\Site;
  19. use Symfony\Component\HttpFoundation\RedirectResponse;
  20. use Symfony\Component\HttpFoundation\Request;
  21. use Symfony\Component\HttpFoundation\Session\SessionInterface;
  22. use \Pimcore\Model\DataObject;
  23. use \Pimcore\Model\DataObject\OnlineShopOrder\Listing;
  24. use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security//important for annotation!
  25. use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route//important for annotation!
  26. //use CoreBundle\Controller\SecureController;
  27. use Symfony\Component\Security\Core\User\UserInterface;
  28. use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
  29. class AccountController extends AbstractController
  30. {
  31.     CONST TOKEN_DIGIT_SIZE 12;
  32.     CONST EMAIL_CUSTOMER_REGISTER "/mail/customerRegister";
  33.     CONST EMAIL_CUSTOMER_PW_RESET "/mail/passwordReset";
  34.     /**
  35.      * @param Request $request
  36.      * @param CustomerProviderInterface $customerProvider
  37.      * @param LoginManagerInterface $loginManager
  38.      * @param RegistrationFormHandler $registrationFormHandler
  39.      * @param UserInterface|null $user
  40.      * @param SessionInterface $session
  41.      * @param IEnvironment $environment
  42.      * @return \Symfony\Component\HttpFoundation\RedirectResponse
  43.      */
  44.     public function registerAction(
  45.         Request $request,
  46.         CustomerProviderInterface $customerProvider,
  47.         LoginManagerInterface $loginManager,
  48.         RegistrationFormHandler $registrationFormHandler,
  49.         UserInterface $user null,
  50.         SessionInterface $session,
  51.         EnvironmentInterface $environment
  52.     ) {
  53.         //redirect user to index page if logged in
  54.         if ($user && $this->isGranted('ROLE_USER')) {
  55.             return $this->redirectToRoute('acc_index', ['controller' => 'account''action' => 'index']);
  56.         }
  57.         $registrationKey $request->get('registrationKey');
  58.         // create a new, empty customer instance
  59.         $customer $customerProvider->create();
  60.         // the registration form handler is just a utility class to map pimcore object data to form
  61.         $formData $registrationFormHandler->buildFormData($customer);
  62.         $hidePassword false;
  63.         // build the registration form and pre-fill it with customer data
  64.         $form $this->createForm(RegistrationFormType::class, $formData, ['hidePassword' => $hidePassword]);
  65.         $form->handleRequest($request);
  66.         $errors = [];
  67.         if ($form->isSubmitted() && $form->isValid()) {
  68.             $registrationFormHandler->updateCustomerFromForm($customer$form);
  69.             $customer->setActive(true);
  70.             try {
  71.                 $token $this->generateToken();
  72.                 $customer->setEmailConfirmToken($token);
  73.                 $customer->save();
  74.                 //check if special redirect is necessary
  75.                 if($session->get("referrer")) {
  76.                     $response $this->redirect($session->get("referrer"));
  77.                     $session->remove("referrer");
  78.                 } else {
  79.                     $response $this->redirectToRoute('acc_index', ['controller' => 'account''action' => 'index']);
  80.                 }
  81.                 // log user in manually
  82.                 // pass response to login manager as it adds potential remember me cookies
  83.                 $loginManager->login($customer$request$response);
  84.                 $environment->setCurrentUserId($customer->getId());
  85.                 $environment->save();
  86.                 return $response;
  87.             } catch (DuplicateCustomerException $e) {
  88.                 $errors[] = 'Customer already exists';
  89.             } catch (\Exception $e) {
  90.                 $errors[] = $e->getMessage();
  91.             }
  92.         }
  93.         if($form->isSubmitted() && !$form->isValid()) {
  94.             foreach($form->getErrors() as $error) {
  95.                 $errors[] = $error->getMessage();
  96.             }
  97.             foreach($form->all()['captcha']->getErrors() as $error) {
  98.                 $errors[] = $error->getMessage();
  99.             }
  100.         }
  101.         $this->view->customer $customer;
  102.         $this->view->form     $form->createView();
  103.         $this->view->errors   $errors;
  104.         $this->view->hideNav true;
  105.         $this->view->hideBreadcrumb true;
  106.         $this->view->hidePassword $hidePassword;
  107.     }
  108.     /**
  109.      * @param AuthenticationUtils $authenticationUtils
  110.      * @param UserInterface|null $user
  111.      * @return \Symfony\Component\HttpFoundation\RedirectResponse
  112.      * @throws \Exception
  113.      */
  114.     public function loginAction(
  115.         AuthenticationUtils $authenticationUtils,
  116. //        OAuthRegistrationHandler $oAuthHandler,
  117.         UserInterface $user nullRequest $request
  118.     )
  119.     {
  120.         //redirect user to index page if logged in, write User ID to cart
  121.         if ($user && $this->isGranted('ROLE_USER')) {
  122.             $cart $this->getCart();
  123.             $cart->setUserId($user->getId());
  124.             $cart->save();
  125.             return $this->redirectToRoute('acc_index', ['controller' => 'account''action' => 'index']);
  126.         }
  127.         // get the login error if there is one
  128.         $error $authenticationUtils->getLastAuthenticationError();
  129.         // last username entered by the user
  130.         $lastUsername $authenticationUtils->getLastUsername();
  131.         $formData = [
  132.             '_username'    => $lastUsername
  133.         ];
  134.         $form $this->createForm(LoginFormType::class, $formData, [
  135.             'action' => $this->generateUrl('login'),
  136.         ]);
  137.         $this->view->reset = (bool)$request->get('reset');
  138.         $this->view->success = (bool)$request->get('success'); // After PW was successfully reset
  139.         $this->view->user $user;
  140.         $this->view->form  $form->createView();
  141.         $this->view->error $error;
  142.         $this->view->hideNav true;
  143.         $this->view->hideBreadcrumb true;
  144.     }
  145.     /**
  146.      * @param UserInterface|null $user
  147.      * @return RedirectResponse
  148.      */
  149.     private function buildUserRedirect(UserInterface $user null): RedirectResponse
  150.     {
  151.         if ($user!=null && $this->isGranted('ROLE_USER')) {
  152.             return $this->redirectToRoute('acc_index');
  153.         }
  154.         return $this->redirectToRoute('login');
  155.     }
  156.     /**
  157.      * Index page for account - it is restricted to ROLE_USER via security annotation
  158.      *
  159.      * @param UserInterface|null $user
  160.      * @return void
  161.      * @throws \Exception
  162.      * @Security("is_granted('ROLE_USER')")
  163.      */
  164.     public function indexAction() {
  165.         $user $this->getUser();
  166.         $this->view->user $user;
  167.         if($user!=null && $user->getEmailConfirmed()){
  168.             $orderList = new Listing();
  169.             //list all confirmed orders of logged in user
  170.             $orderList->addConditionParam('originShop = ?'$_SERVER['HTTP_HOST'], 'AND');
  171.             $orderList->addConditionParam('customerEmail = ?'$user->getEmail(), 'AND');
  172.             $orderList->addConditionParam('orderState = ?''committed''AND');
  173.             $orderList->load();
  174.         }
  175.         else{
  176.             $this->addFlash('error'$this->get("translator")->trans("emailAdressNotConfirmedError"));
  177.             $customer Customer::getByEmail($user->getEmail(), 1);
  178.             if($customer){
  179.                 $token $customer->getEmailConfirmToken();
  180.                 $this->sendTokenMail($customer->getId(), $customer->getEmail(), $tokenSite::getCurrentSite()->getRootPath().self::EMAIL_CUSTOMER_REGISTER);
  181.                 $customer->save();
  182.                 $this->addFlash('success'$this->get("translator")->trans("passwordResetEmailSent"));
  183.             }
  184.         }
  185.         $this->view->orders $orderList;
  186.     }
  187.     /**
  188.      * @param Request $request
  189.      * @param UserInterface|null $user
  190.      * @return RedirectResponse
  191.      */
  192.     public function confirmAction(Request $requestUserInterface $user null) {
  193.         $this->view->user $user;
  194.         $token $request->get('token');
  195.         //check if user is confirming his token
  196.         if ($user!=null && $this->isGranted('ROLE_USER')) {
  197.             if($user->getEmailConfirmToken() == $token){
  198.                 $user->setEmailConfirmed(true);
  199.                 $user->save();
  200.                 $this->addFlash('success'$this->get("translator")->trans("emailAddressConfirmedSuccess"));
  201.             }
  202.             else{
  203.                 $this->addFlash('error'$this->get("translator")->trans("emailAdressConfirmedError").$token);
  204.             }
  205.             return $this->redirectToRoute('acc_index');
  206.         }
  207.         //check if user (not logged in) is confirming an email
  208.         $unloggedUser Customer::getByEmailConfirmToken($token1);
  209.         if($unloggedUser){
  210.             $unloggedUser->setEmailConfirmed(true);
  211.             $unloggedUser->save();
  212.             $this->addFlash('success'$this->get("translator")->trans("emailAddressConfirmedSuccess"));
  213.             return $this->redirectToRoute('login');
  214.         }
  215.         $this->addFlash('error'$this->get("translator")->trans("emailAdressConfirmedError").$token);
  216.         return $this->redirectToRoute('login');
  217.     }
  218.     /**
  219.      * @param Request $request
  220.      * @return RedirectResponse
  221.      * @throws \Exception
  222.      */
  223.     public function requestPasswordResetAction(Request $request){
  224.         //Form -> email, send email with token to that mail -> link to resetPasswordAction
  225.         $form $this->createForm(RequestPasswordResetFormType::class);
  226.         $form->handleRequest($request);
  227.         if ($form->isSubmitted() && $form->isValid()) {
  228.             $customer Customer::getByEmail($request->get('email'), 1);
  229.             if($customer){
  230.                 $token $this->generateToken();
  231.                 $customer->setPwResetToken($token);
  232.                 $customer->save();
  233.                 $this->sendTokenMail($customer->getId(), $customer->getEmail(), $tokenSite::getCurrentSite()->getRootPath().self::EMAIL_CUSTOMER_PW_RESET);
  234.                 $this->addFlash('success'$this->get("translator")->trans("passwordResetEmailSent"));
  235.                 return $this->redirectToRoute('login', ['reset' => 1]);
  236.             }
  237.         }
  238.         $this->view->form $form->createView();
  239.     }
  240.     /**
  241.      * @param Request $request
  242.      * @return RedirectResponse
  243.      */
  244.     public function resetPasswordAction(Request $request){
  245.         $customer Customer::getByEmail($request->get('email'), 1);
  246.         //Check if token matches customer -> provide form to reset PW
  247.         if($customer && $request->get('token') == $customer->getPwResetToken()){
  248.             $form $this->createForm(ResetPasswordFormType::class);
  249.             $form->handleRequest($request);
  250.             $this->view->form     $form->createView();
  251.             if ($form->isSubmitted() && $form->isValid()) {
  252.                 $customer->setPassword($request->get('password')['first']);
  253.                 $customer->setPwResetToken('');
  254.                 $customer->save();
  255.                 $this->addFlash('success'$this->get("translator")->trans("passwordResetSuccessfully"));
  256.                 return $this->redirectToRoute('login', ['success' => 1]);
  257.             }
  258.         }
  259.         else{
  260.             $this->addFlash('error'$this->get("translator")->trans("passwordResetLinkNoLongerValid"));
  261.             return $this->redirectToRoute('login');
  262.         }
  263.     }
  264.     /**
  265.      * @param Int $customerId
  266.      * @param String $email
  267.      * @param String $token
  268.      * @param String $template
  269.      */
  270.     protected function sendTokenMail(Int $customerIdString $emailString $tokenString $template)
  271.     {
  272.         $customer Customer::getById($customerId);
  273.         $params = [];
  274.         $params['token'] = $token;
  275.         $params['customer'] = $customer;
  276.         $params['email'] = $email;
  277.         $emailDoc Document::getByPath($template);
  278.         $mail = new Mail(['document' => $emailDoc'params' => $params]);
  279.         $mail->setParams($params);
  280.         $mail->addTo($email);
  281.         $mail->send();
  282.     }
  283.     /**
  284.      * @return string
  285.      * @throws \Exception
  286.      */
  287.     protected function generateToken(){
  288.         return bin2hex(random_bytes(self::TOKEN_DIGIT_SIZE));
  289.     }
  290. }