src/Controller/SecurityController.php line 26

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