src/Controller/SecurityController.php line 41

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\Services\Functions;
  4. use Carbon\Carbon;
  5. use Exception;
  6. use Pimcore\Log\ApplicationLogger;
  7. use Pimcore\Model\DataObject\Coupon;
  8. use Pimcore\Model\DataObject\LocationSource;
  9. use Pimcore\Model\DataObject\MemberStripeAccount;
  10. use Pimcore\Model\DataObject\MembersUser;
  11. use Pimcore\Model\DataObject\Price;
  12. use Pimcore\Model\DataObject\Promocode;
  13. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  14. use Symfony\Component\HttpFoundation\Request;
  15. use Symfony\Component\HttpFoundation\Response;
  16. use Symfony\Component\Routing\Annotation\Route;
  17. use Symfony\Component\Security\Http\Attribute\CurrentUser;
  18. use Lexik\Bundle\JWTAuthenticationBundle\Services\JWTTokenManagerInterface;
  19. use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
  20. use Symfony\Component\HttpFoundation\JsonResponse;
  21. class SecurityController extends AbstractController
  22. {
  23.     private JWTTokenManagerInterface $jwtManager;
  24.     private UserPasswordHasherInterface $passwordHasher;
  25.     public function __construct(
  26.         JWTTokenManagerInterface $jwtManager,
  27.         UserPasswordHasherInterface $passwordHasher
  28.     ) {
  29.         $this->jwtManager $jwtManager;
  30.         $this->passwordHasher $passwordHasher;
  31.     }
  32.     #[Route('/v1/api/login'name'v1_app_login'methods: ['POST'])]
  33.     public function loginAction(Request $request): JsonResponse
  34.     {
  35.         $logger ApplicationLogger::getInstance();
  36.     
  37.         try {
  38.             $data json_decode($request->getContent(), true);
  39.     
  40.             if (!isset($data['email']) || !isset($data['password'])) {
  41.                 return new JsonResponse([
  42.                     'error' => true,
  43.                     'message' => 'Email, password and source are required',
  44.                     'data' => []
  45.                 ], Response::HTTP_BAD_REQUEST);
  46.             }
  47.     
  48.             $email $data['email'];
  49.             $password $data['password'];
  50.             $sourceKey $data['source'] ?? null;
  51.     
  52.             // Trova l'utente
  53.             $user MembersUser::getByEmail($email, ['limit' => 1'unpublished' => false]);
  54.     
  55.             if (!$user instanceof MembersUser) {
  56.                 return new JsonResponse([
  57.                     'error' => true,
  58.                     'message' => 'Invalid credentials',
  59.                     'data' => []
  60.                 ], Response::HTTP_UNAUTHORIZED);
  61.             }
  62.     
  63.             // Verifica la password
  64.             if (!$this->passwordHasher->isPasswordValid($user$password)) {
  65.                 return new JsonResponse([
  66.                     'error' => true,
  67.                     'message' => 'Invalid credentials',
  68.                     'data' => []
  69.                 ], Response::HTTP_UNAUTHORIZED);
  70.             }
  71.     
  72.             // Verifica che l'utente sia attivo
  73.             if (!$user->getActive()) {
  74.                 return new JsonResponse([
  75.                     'error' => true,
  76.                     'message' => 'Utente non attivo',
  77.                     'data' => []
  78.                 ], Response::HTTP_UNAUTHORIZED);
  79.             }
  80.             $source null;
  81.             if ($sourceKey) {
  82.                 $source LocationSource::getByObjectKey($sourceKey1);
  83.                 if (!$source instanceof LocationSource) {
  84.                     return new JsonResponse([
  85.                         'error' => true,
  86.                         'message' => 'Source not found',
  87.                         'data' => []
  88.                     ], Response::HTTP_BAD_REQUEST);
  89.                 }
  90.             }
  91.             if (!empty($user->getEndDate()) && !$user->getEndDate()->greaterThan(Carbon::now())) {
  92.                 return new JsonResponse([
  93.                     'error' => true,
  94.                     'message' => 'Iscrizione scaduta',
  95.                     'data' => []
  96.                 ], Response::HTTP_UNAUTHORIZED);
  97.             }
  98.     
  99.             // Genera il token JWT
  100.             $token $this->jwtManager->create($user);
  101.             // Resto della logica per prodotti e promo codes...
  102.             // $userData = $this->getUserData($user, $source);
  103.             $role '';
  104.             if (in_array('ROLE_PIMCORE_USER'$user->getRoles())) {
  105.                 $role 'admin';
  106.             } elseif (in_array('ROLE_USER'$user->getRoles())) {
  107.                 $role 'user';
  108.             }
  109.             return new JsonResponse([
  110.                 'token' => $token,
  111.                 'user' => [
  112.                     'id' => $user->getId(),
  113.                     'firstname' => $user->getFirstname(),
  114.                     'lastname' => $user->getLastname(),
  115.                     'email' => $user->getEmail(),
  116.                     'phone' => $user->getPhone(),
  117.                     'role' => $role,
  118.                     // 'roles' => $user->getRoles()
  119.                 ]
  120.             ]);
  121.         } catch (Exception $e) {
  122.             $logger->error($e);
  123.             return new JsonResponse([
  124.                 'error' => true,
  125.                 'message' => $e->getMessage(),
  126.                 'data' => []
  127.             ], Response::HTTP_INTERNAL_SERVER_ERROR);
  128.         }
  129.     }
  130.     #[Route('/v1/api/profile'name'app_profile'methods: ['GET'])]
  131.     public function getProfileAction(Request $request, #[CurrentUser$user null): JsonResponse
  132.     {
  133.         $sourceKey $request->query->get('source');
  134.         if (!$user instanceof MembersUser) {
  135.             return new JsonResponse([
  136.                 'error' => true,
  137.                 'message' => 'User not found',
  138.                 'data' => []
  139.             ], Response::HTTP_UNAUTHORIZED);
  140.         }
  141.         $source LocationSource::getByObjectKey($sourceKey1);
  142.         if (!$source instanceof LocationSource) {
  143.             return new JsonResponse([
  144.                 'error' => true,
  145.                 'message' => 'Source not found',
  146.                 'data' => []
  147.             ], Response::HTTP_BAD_REQUEST);
  148.         }
  149.         $userData $this->getUserData($user$sourcefalse);
  150.         return new JsonResponse([
  151.             'error' => false,
  152.             'message' => null,
  153.             'data' => $userData
  154.         ]);
  155.     }
  156.     #[Route('/v1/api/refresh-token'name'app_refresh_token'methods: ['POST'])]
  157.     public function refreshTokenAction(#[CurrentUser$user null): JsonResponse
  158.     {
  159.         if (!$user instanceof MembersUser) {
  160.             return new JsonResponse([
  161.                 'error' => true,
  162.                 'message' => 'User not found',
  163.                 'data' => []
  164.             ], Response::HTTP_UNAUTHORIZED);
  165.         }
  166.         $token $this->jwtManager->create($user);
  167.         return new JsonResponse([
  168.             'token' => $token
  169.         ]);
  170.     }
  171.     private function getUserData(MembersUser $userLocationSource $source$exception true): array
  172.     {
  173.         $products = [];
  174.         $promoCodes = [];
  175.         $MemberStripeAccount = new MemberStripeAccount\Listing();
  176.         $MemberStripeAccount->setCondition('customerId = ? AND source__id = ?', [
  177.             $user->getId(),
  178.             $source->getId()
  179.         ]);
  180.         $MemberStripeAccount $MemberStripeAccount->current();
  181.         if (!$MemberStripeAccount instanceof MemberStripeAccount) {
  182.             if ($exception) {
  183.                 throw new Exception('Account not found');
  184.             }
  185.         }
  186.         $mainGroup '';
  187.         $groups $user->getGroups();
  188.         if (isset($groups[0]) && $groups[0]->getName() === 'Private') {
  189.             $mainGroup $groups[0]->getName();
  190.             if (!empty($user->getEndDate()) && !$user->getEndDate()->greaterThan(Carbon::now())) {
  191.                 if ($exception) {
  192.                     throw new Exception('Iscrizione utente scaduto');
  193.                 }
  194.             }
  195.         } elseif (isset($groups[0]) && !empty($groups[0]->getName())) {
  196.             $mainGroup $groups[0]->getName();
  197.         }
  198.         if ($MemberStripeAccount) {
  199.             $stripe = new \Stripe\StripeClient($MemberStripeAccount->getSource()?->getStripeAccount()->getStripeSecret());
  200.             // Prodotti base
  201.             if (null !== ($price Price::getByPriceid($MemberStripeAccount->getSource()->getStripeAccount()->getAssistanceItem(), 1))) {
  202.                 $products[$MemberStripeAccount->getSource()->getStripeAccount()->getAssistanceItem()]['price'] = $price->getPrice() / 100;
  203.                 $products[$MemberStripeAccount->getSource()->getStripeAccount()->getAssistanceItem()]['title'] = $price->getTitle();
  204.             }
  205.             if (null !== ($price Price::getByPriceid($MemberStripeAccount->getSource()->getStripeAccount()->getAttestationItem(), 1))) {
  206.                 $products[$MemberStripeAccount->getSource()->getStripeAccount()->getAttestationItem()]['price'] = $price->getPrice() / 100;
  207.                 $products[$MemberStripeAccount->getSource()->getStripeAccount()->getAttestationItem()]['title'] = $price->getTitle();
  208.             }
  209.             
  210.             // Gestione promo codes
  211.             if (!empty($MemberStripeAccount->getPromoCode())) {
  212.                 foreach ($MemberStripeAccount->getPromoCode() as $k => $promos) {
  213.                     $promoCodes[$promos[0]] = $promos[1];
  214.                     if (null !== ($price Price::getByPriceid($promos[0], 1))) {
  215.                         $products[$promos[0]]['price'] = $price->getPrice() / 100;
  216.                         $products[$promos[0]]['title'] = $price->getTitle();
  217.                     }
  218.                     if (null !== ($promo Promocode::getByPromoid($promos[1], 1))) {
  219.                         $coupon Coupon::getByPromo($promo1);
  220.                         if ($coupon instanceof Coupon) {
  221.                             preg_match('/\d+$/'$coupon->getTitle(), $matches);
  222.                             if (!empty($matches)) {
  223.                                 $products[$promos[0]]['promo'] = (float) $matches[0];
  224.                             }
  225.                         }
  226.                     } else {
  227.                         try {
  228.                             $promoObj $stripe->promotionCodes->retrieve($promos[1], []);
  229.                             if ($promoObj->active) {
  230.                                 preg_match('/\d+$/'$promoObj->coupon->name$matches);
  231.                                 if (!empty($matches)) {
  232.                                     $products[$promos[0]]['promo'] = (float) $matches[0];
  233.                                 }
  234.                             }
  235.                         } catch (\Exception $e) {
  236.                             // Log dell'errore se necessario
  237.                         }
  238.                     }
  239.                 }
  240.             }
  241.         }
  242.         
  243.         $role '';
  244.         if (in_array('ROLE_PIMCORE_USER'$user->getRoles())) {
  245.             $role 'admin';
  246.         } elseif (in_array('ROLE_USER'$user->getRoles())) {
  247.             $role 'user';
  248.         }
  249.         return [
  250.             'fullName' => $user->getFirstname() . ' ' $user->getLastname(),
  251.             'taxCode' => $user->getFiscalCode(),
  252.             'role' => $role,
  253.             'membership' => [
  254.                 'number' => $user->getMembershipNumber(),
  255.                 'expirationDate' => $user->getEndDate()?->format('Y-m-d'),
  256.             ],
  257.             'customerType' => $mainGroup,
  258.             'customerTypeId' => \Pimcore\Model\DataObject\MembersGroup::getByName($mainGroup1)?->getId(),
  259.             'businessName' => !empty($user->getBusinessName()) ? $user->getBusinessName() : '',
  260.             'firstname' => $user->getFirstname(),
  261.             'startDate' => $user->getCreatedDate(),
  262.             'endDate' => $user->getEndDate(),
  263.             'lastname' => $user->getLastname(),
  264.             'email' => $user->getEmail(),
  265.             'phone' => $user->getPhone(),
  266.             'customerId' => $user->getId(),
  267.             'stripeCustomerId' => $MemberStripeAccount $MemberStripeAccount?->getStripeCustomerId() : null,
  268.             'stripePromoCodes' => $promoCodes,
  269.             'products' => $products
  270.         ];
  271.     }
  272.     #[Route('/api/login'name'app_login'methods: ['POST'])]
  273.     public function appLoginAction(Request $request, #[CurrentUser$user null): Response
  274.     {
  275.         $logger ApplicationLogger::getInstance();
  276.         try {
  277.             $source LocationSource::getByObjectKey($request->toArray()['source'])->current();
  278.             if (empty($source)) {
  279.                 throw new Exception('Source not found');
  280.             }
  281.             $products = [];
  282.             if ($user instanceof  MembersUser && $user !== null && $user->getActive()) {
  283.                 $MemberStripeAccount = new MemberStripeAccount\Listing();
  284.                 $MemberStripeAccount->setCondition('customerId = ? AND source__id = ?', [
  285.                     $user->getId(),
  286.                     $source->getId()
  287.                 ]);
  288.                 $MemberStripeAccount $MemberStripeAccount->current();
  289.                 $stripe = new \Stripe\StripeClient($MemberStripeAccount->getSource()->getStripeAccount()->getStripeSecret());
  290.                 if (!$MemberStripeAccount instanceof MemberStripeAccount) {
  291.                     throw new Exception('Account not found');
  292.                 }
  293.                 if (null !== ($price Price::getByPriceid($MemberStripeAccount->getSource()->getStripeAccount()->getAssistanceItem(), 1))) {
  294.                     $products[$MemberStripeAccount->getSource()->getStripeAccount()->getAssistanceItem()]['price'] = $price->getPrice() / 100;
  295.                     $products[$MemberStripeAccount->getSource()->getStripeAccount()->getAssistanceItem()]['title'] = $price->getTitle();
  296.                 }
  297.                 if (null !== ($price Price::getByPriceid($MemberStripeAccount->getSource()->getStripeAccount()->getAttestationItem(), 1))) {
  298.                     $products[$MemberStripeAccount->getSource()->getStripeAccount()->getAttestationItem()]['price'] = $price->getPrice() / 100;
  299.                     $products[$MemberStripeAccount->getSource()->getStripeAccount()->getAttestationItem()]['title'] = $price->getTitle();
  300.                 }
  301.                 $promoCodes = [];
  302.                 $mainGroup '';
  303.                 $groups $user->getGroups();
  304.                 if (isset($groups[0]) && $groups[0]->getName() === 'Private') {
  305.                     $mainGroup $groups[0]->getName();
  306.                     if (!empty($user->getEndDate()) && !$user->getEndDate()->greaterThan(Carbon::now())) {
  307.                         $logger->info($user->getId() . ' Iscrizione utente scaduto');
  308.                         return $this->json([
  309.                             'error' => true,
  310.                             'message' => 'Iscrizione utente scaduto',
  311.                             'data' => []
  312.                         ]);
  313.                     }
  314.                 } elseif (isset($groups[0]) && !empty($groups[0]->getName())) {
  315.                     $mainGroup $groups[0]->getName();
  316.                 }
  317.                 if (!empty($user->getEndDate()) && !$user->getEndDate()->greaterThan(Carbon::now())) {
  318.                     if (!empty($MemberStripeAccount->getPromocode())) {
  319.                         foreach ($MemberStripeAccount->getPromoCode() as $k => $promos) {
  320.                             $promoCodes[$promos[0]] = $promos[1];
  321.                             if (null !== ($price Price::getByPriceid($promos[0], 1))) {
  322.                                 $products[$promos[0]]['price'] = $price->getPrice() / 100;
  323.                                 $products[$promos[0]]['title'] = $price->getTitle();
  324.                             }
  325.                             if (null !== ($promo Promocode::getByPromoid($promos[1], 1))) {
  326.                                 $coupon Coupon::getByPromo($promo1);
  327.                                 if ($coupon instanceof Coupon) {
  328.                                     preg_match('/\d+$/'$coupon->getTitle(), $matches);
  329.                                     if (!empty($matches)) {
  330.                                         $products[$promos[0]]['promo'] = (float) $matches[0];
  331.                                     }
  332.                                 }
  333.                             } else {
  334.                                 $promoObj $stripe->promotionCodes->retrieve($promos[1], []);
  335.                                 if ($promoObj->active) {
  336.                                     preg_match('/\d+$/'$promoObj->coupon->name$matches);
  337.                                     if (!empty($matches)) {
  338.                                         $products[$promos[0]]['promo'] = (float) $matches[0];
  339.                                     }
  340.                                 }
  341.                             }
  342.                         }
  343.                     }
  344.                 } elseif (!empty($MemberStripeAccount->getPromoCode())) {
  345.                     foreach ($MemberStripeAccount->getPromoCode() as $k => $promos) {
  346.                         $promoCodes[$promos[0]] = $promos[1];
  347.                         if (null !== ($price Price::getByPriceid($promos[0], 1))) {
  348.                             $products[$promos[0]]['price'] = $price->getPrice() / 100;
  349.                             $products[$promos[0]]['title'] = $price->getTitle();
  350.                         }
  351.                         if (null !== ($promo Promocode::getByPromoid($promos[1], 1))) {
  352.                             $coupon Coupon::getByPromo($promo1);
  353.                             if ($coupon instanceof Coupon) {
  354.                                 preg_match('/\d+$/'$coupon->getTitle(), $matches);
  355.                                 if (!empty($matches)) {
  356.                                     $products[$promos[0]]['promo'] = (float) $matches[0];
  357.                                 }
  358.                             }
  359.                         } else {
  360.                             $promoObj $stripe->promotionCodes->retrieve($promos[1], []);
  361.                             if ($promoObj->active) {
  362.                                 preg_match('/\d+$/'$promoObj->coupon->name$matches);
  363.                                 if (!empty($matches)) {
  364.                                     $products[$promos[0]]['promo'] = (float) $matches[0];
  365.                                 }
  366.                             }
  367.                         }
  368.                     }
  369.                 }
  370.                 return $this->json([
  371.                     'error' => false,
  372.                     'message' => null,
  373.                     'data' => [
  374.                         'customerType' =>  $mainGroup,
  375.                         'customerTypeId' =>  \Pimcore\Model\DataObject\MembersGroup::getByName($mainGroup1)?->getId(),
  376.                         'businessName' =>  !empty($user->getBusinessName()) ? $user->getBusinessName() : '',
  377.                         'firstname' =>  $user->getFirstname(),
  378.                         'startDate' =>  $user->getCreatedDate(),
  379.                         'endDate' =>  $user->getEndDate(),
  380.                         'lastname' => $user->getLastname(),
  381.                         'email' => $user->getEmail(),
  382.                         'phone' => $user->getPhone(),
  383.                         'authorization' => \Pimcore\Config::getWebsiteConfig()->get('rent_calculator_authorization'),
  384.                         'customerId' => $user->getId(),
  385.                         'stripeCustomerId' => $MemberStripeAccount->getStripeCustomerId(),
  386.                         'stripePromoCodes' => $promoCodes,
  387.                         'products' => $products,
  388.                         'token' => Functions::securedEncrypt($user->getId())
  389.                     ]
  390.                 ]);
  391.             } else {
  392.                 $logger->info($user->getId() . ' Utente non attivo');
  393.                 return $this->json([
  394.                     'error' => true,
  395.                     'message' => 'Utente non attivo',
  396.                     'data' => []
  397.                 ]);
  398.             }
  399.         } catch (Exception $e) {
  400.             return $this->json([
  401.                 'error' => true,
  402.                 'message' => $e->getMessage(),
  403.                 'data' => []
  404.             ]);
  405.         }
  406.     }
  407. }