src/Controller/AuthenticationController.php line 22

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\Form\Auth\LoginFormType;
  4. use App\Form\Auth\RegisterFormType;
  5. use CustomerManagementFrameworkBundle\CustomerProvider\CustomerProviderInterface;
  6. use Pimcore\Model\DataObject\Customer;
  7. use Pimcore\Model\Document;
  8. use Pimcore\Model\WebsiteSetting;
  9. use App\Classes\Controller\AbstractFrontController as AbstractFrontController;
  10. use App\Repository\CustomerRepository;
  11. use App\Service\Contract\RecaptchaValidationServiceInterface;
  12. use Symfony\Component\Cache\Adapter\FilesystemAdapter;
  13. use Symfony\Component\Form\FormError;
  14. use Symfony\Component\HttpFoundation\RedirectResponse;
  15. use Symfony\Component\HttpFoundation\Request;
  16. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  17. use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
  18. use Symfony\Contracts\Translation\TranslatorInterface;
  19. class AuthenticationController extends AbstractFrontController
  20. {
  21.     public function __construct(
  22.         protected CustomerRepository $customerRepository,
  23.         protected RecaptchaValidationServiceInterface $recaptchaValidationService,
  24.         protected TranslatorInterface $translator
  25.     ){}
  26.     public function loginAction(Request $requestAuthenticationUtils $authenticationUtils)
  27.     {
  28.         $parameters['division'] = $request->get('division');
  29.         if ($this->isGranted('ROLE_USER')) {
  30.             return new RedirectResponse($request->get('_target_path') ?? '/' $parameters['division']);
  31.         }
  32.         // get the login error if there is one
  33.         $error $authenticationUtils->getLastAuthenticationError();
  34.         // last username entered by the user
  35.         $lastUsername $authenticationUtils->getLastUsername();
  36.         $formData = [
  37.             '_username'    => $lastUsername,
  38.             '_target_path' => $request->get('_target_path') ?? '/' $parameters['division']
  39.         ];
  40.         $form $this->createForm(
  41.             LoginFormType::class,
  42.             $formData,
  43.             [
  44.                 'action' => $this->generateUrl('login'$parameters),
  45.             ]
  46.         );
  47.         return $this->render(
  48.             '@App/division/auth/login.html.twig',
  49.             [
  50.                 'form'     => $form->createView(),
  51.                 'errorBag'    => $request->getSession()->getFlashBag()->get('errors'),
  52.                 'document' => Document::getByPath('/' $parameters['division'])
  53.             ]
  54.         );
  55.     }
  56.     public function registerAction(Request $requestCustomerProviderInterface $customerProvider)
  57.     {
  58.         $division $request->get('division');
  59.         $selectedCountry 'US';
  60.         $cache = new FilesystemAdapter();
  61.         $cachedCountryCode $cache->getItem('country_code');
  62.         if (!$cachedCountryCode->isHit()) {
  63.             $accessKey WebsiteSetting::getByName('geoLocationApiKey')->getData();
  64.             if (empty($accessKey)) {
  65.                 $cachedCountryCode->set($selectedCountry)
  66.                     ->expiresAfter(3600 24 10); // 10 days
  67.                 $cache->save($cachedCountryCode);
  68.                 return;
  69.             }
  70.             // set IP address and API access key
  71.             $ip $request->getClientIp();
  72.             // Initialize CURL:
  73.             $ch curl_init('http://api.ipstack.com/'.$ip.'?access_key='.$accessKey.'');
  74.             curl_setopt($chCURLOPT_RETURNTRANSFERtrue);
  75.             // Store the data:
  76.             $json curl_exec($ch);
  77.             curl_close($ch);
  78.             // Decode JSON response:
  79.             $apiResult json_decode($jsontrue);
  80.             // Output the "capital" object inside "location"
  81.             if ($apiResult && !empty($apiResult['country_code'])) {
  82.                 $selectedCountry $apiResult['country_code'];
  83.             }
  84.             $cachedCountryCode->set($selectedCountry)
  85.                 ->expiresAfter(3600 24 10); // 10 days
  86.             $cache->save($cachedCountryCode);
  87.         }
  88.         $selectedCountry $cachedCountryCode->get();
  89.         if ($this->isGranted('ROLE_USER')) {
  90.             return new RedirectResponse('/' $division);
  91.         }
  92.         $form $this->createForm(
  93.             RegisterFormType::class,
  94.             [
  95.                 'accountInformation' => [
  96.                     'divisions' => [strtolower(str_replace(' ''-'$division))]
  97.                 ]
  98.             ]
  99.         );
  100.         $form->handleRequest($request);
  101.         if ($form->isSubmitted() && $form->isValid()) {
  102.             $formData $form->getData();
  103.             if (!$this->recaptchaValidationService->isValid($formData)) {
  104.                 $this->addFlash('error''stoelting.recaptcha-failed.error');
  105.                 return $this->redirectBack($request);
  106.             }
  107.             $userAlreadyExists Customer::getByEmail($formData['accountInformation']['email'], 1);
  108.             if (!$userAlreadyExists) {
  109.                 $backup \Pimcore\Model\DataObject\AbstractObject::getHideUnpublished();
  110.                 \Pimcore\Model\DataObject\AbstractObject::setHideUnpublished(false);
  111.                 $unpublishedCustomer Customer::getByEmail($formData['accountInformation']['email'])->current();
  112.                 \Pimcore\Model\DataObject\AbstractObject::setHideUnpublished($backup);
  113.                 if ($unpublishedCustomer && !empty(trim($unpublishedCustomer->getOldSiteRefId()))) {
  114.                     $unpublishedCustomer->setSalt(null);
  115.                     $customer $this->customerRepository->fillCustomerData(
  116.                         $formData,
  117.                         $unpublishedCustomer
  118.                     );
  119.                 } else {
  120.                     $customerInstance $customerProvider->createCustomerInstance();
  121.                     $customer $this->customerRepository->fillCustomerData(
  122.                         $formData,
  123.                         $customerInstance
  124.                     );
  125.                 }
  126.                 $this->addFlash(
  127.                     'success',
  128.                     $this->translator->trans('stoelting.user-successfully-registered')
  129.                 );
  130.                 $this->customerRepository->sendRegisteredEmail(
  131.                     $customer,
  132.                     [
  133.                         'loginLink' => $this->generateUrl('login', ['division' => $division], UrlGeneratorInterface::ABSOLUTE_URL),
  134.                         'loginLinkHref' => substr($this->generateUrl('login', ['division' => $division], UrlGeneratorInterface::NETWORK_PATH), 2)
  135.                     ]
  136.                 );
  137.                 return $this->redirectToRoute('login', ['division' => $division]);
  138.             }
  139.             $form->get('accountInformation')->get('email')->addError(
  140.                 new FormError(
  141.                     $this->translator->trans('stoelting.user-already-exists')
  142.                 )
  143.             );
  144.         }
  145.         return $this->render(
  146.             '@App/division/auth/register.html.twig',
  147.             [
  148.                 'form'     => $form->createView(),
  149.                 'selectedCountry' => $selectedCountry,
  150.                 'document' => Document::getByPath('/' $division)
  151.             ]
  152.         );
  153.     }
  154.     public function logoutAction()
  155.     {
  156.         // controller can be blank: it will never be executed!
  157.         throw new \Exception('Don\'t forget to activate logout in security.yaml');
  158.     }
  159.     function getRealIpAddr()
  160.     {
  161.         if (!empty($_SERVER['HTTP_CLIENT_IP']))   //check ip from share internet
  162.         {
  163.             $ip=$_SERVER['HTTP_CLIENT_IP'];
  164.         }
  165.         elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR']))   //to check ip is pass from proxy
  166.         {
  167.             $ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
  168.         }
  169.         else
  170.         {
  171.             $ip=$_SERVER['REMOTE_ADDR'];
  172.         }
  173.         return $ip;
  174.     }
  175. }