src/Subscriber/AppSubscriber.php line 102

Open in your IDE?
  1. <?php
  2. declare(strict_types=1);
  3. namespace App\Subscriber;
  4. use App\Logger\Log;
  5. use App\Entity\User;
  6. use App\Entity\BaseAuth;
  7. use App\Form\CommonForm;
  8. use App\Service\AuthService;
  9. use App\Service\FileService;
  10. use App\Service\IAppService;
  11. use App\Service\IAuthService;
  12. use App\Service\SchoolService;
  13. use App\Service\IOptionService;
  14. use App\Controller\AuthController;
  15. use App\Controller\UserController;
  16. use App\Controller\StaffController;
  17. use App\Controller\WizardController;
  18. use Symfony\Component\Security\Core\Security;
  19. use Symfony\Component\HttpKernel\KernelEvents;
  20. use Symfony\Component\HttpFoundation\JsonResponse;
  21. use Symfony\Component\HttpKernel\Event\RequestEvent;
  22. use Symfony\Component\HttpFoundation\RedirectResponse;
  23. use Symfony\Component\HttpKernel\Event\ExceptionEvent;
  24. use Symfony\Contracts\Translation\TranslatorInterface;
  25. use Symfony\Component\HttpKernel\Event\ControllerEvent;
  26. use Symfony\Component\HttpFoundation\Session\SessionInterface;
  27. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  28. use Symfony\Component\Security\Http\Event\InteractiveLoginEvent;
  29. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  30. use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
  31. use Doctrine\ORM\Tools\Console\Command\SchemaTool\AbstractCommand;
  32. use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
  33. use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
  34. class AppSubscriber implements EventSubscriberInterface
  35. {
  36.     private ParameterBagInterface $parameterBag;
  37.     private SessionInterface $session;
  38.     private Security $security;
  39.     private SchoolService $schoolService;
  40.     protected TokenStorageInterface $securityToken;
  41.     protected Log $log;
  42.     protected FileService $fileService;
  43.     protected AuthService $authService;
  44.     public function __construct(
  45.         ParameterBagInterface $parameterBag,
  46.         SessionInterface $session,
  47.         Security $security,
  48.         TokenStorageInterface $securityToken,
  49.         Log $log,
  50.         FileService $fileService,
  51.         SchoolService $schoolService,
  52.         TranslatorInterface $translator,
  53.         AuthService $authService
  54.     ) {
  55.         $this->session $session;
  56.         $this->security $security;
  57.         $this->schoolService $schoolService;
  58.         $this->securityToken $securityToken;
  59.         $this->fileService $fileService;
  60.         $this->log $log;
  61.         $this->parameterBag $parameterBag;
  62.         $this->authService $authService;
  63.     }
  64.     public function onInteractiveLogin(InteractiveLoginEvent $event)
  65.     {
  66.         $user $event->getAuthenticationToken()->getUser();
  67.         /*if (null !== $user->getLocale()) {
  68.             $this->translator->setLocale($user->getLocale());
  69.         }*/
  70.     }
  71.     public function checkSubscription(ControllerEvent $eventAbstractController $controller){
  72.          // Permet de controler l'abonnement du site connecté
  73.          $user $this->security->getUser();
  74.          if($controller instanceof UserController && !empty($user) && $user instanceof User) {
  75.              $school $user->getSchool();
  76.              $site null;
  77.              if(!empty($school)){
  78.                  if (!empty($site $this->session->get(IOptionService::CURRENT_SITE))) {
  79.                      $site $this->schoolService->findSite(['guid' => $site->getGuid()]);
  80.                  } elseif (\count($school->getSites()) > 0) {
  81.                      $site $school->getSites()[0];
  82.                      $this->session->set(IOptionService::CURRENT_SITE$site);
  83.                  }
  84.              }         
  85.              if(!empty($site) && (empty($site->getExpirationDate()))) {
  86.                  $event->setController(function () {
  87.                      return new RedirectResponse($this->parameterBag->get('app.url').'error/expired');
  88.                  });
  89.              } else if( !empty($site) && CommonForm::timeElapsed(new \DateTime('now'),$site->getExpirationDate()) <= 0){
  90.                  $event->setController(function () {
  91.                      return new RedirectResponse($this->parameterBag->get('app.url').'error/expired');
  92.                  });
  93.              }
  94.          }
  95.     }
  96.     public function onKernelController(ControllerEvent $event)
  97.     {
  98.         $controller $event->getController();
  99.         if (!is_array($controller)) {
  100.             return;
  101.         }
  102.         // Permet de controler l'abonnement du site connecté
  103.         if ($controller[0] instanceof StaffController || $controller[0] instanceof UserController || $controller[0] instanceof WizardController) {
  104.             $user $this->security->getUser();
  105.             if ($this->fileService->checkFile($this->parameterBag->get('app.connection_dir').DIRECTORY_SEPARATOR.IOptionService::MAINTENANCE_FILE) && IAuthService::STAFF != $this->parameterBag->get('app.user')
  106.                 && !in_array(IAuthService::ROLE.'_'.IAuthService::ROLE_SUPER_ADMINISTRATOR,
  107.                     $user->getRoles())) {
  108.                 // logger - site is under maintenance
  109.                 $this->log->writeLog(
  110.                     [
  111.                         IOptionService::KEY_CLASS => get_class($this),
  112.                         IOptionService::KEY_FUNCTION => __FUNCTION__,
  113.                         IOptionService::KEY_MESSAGE => 'site is under maintenance',
  114.                     ],
  115.                     Log::MESSAGE_INFO
  116.                 );
  117.                 // clean session i think is not working
  118.                 $session $event->getRequest()->getSession();
  119.                 $session->invalidate();
  120.                 $session->clear();
  121.                 // clean user activity
  122.                 $this->securityToken->setToken(null);
  123.                 // redirect to maintenance page
  124.                 $this->redirectionMaintenance($event);
  125.             } elseif (null === $user) {
  126.                 // logger - user is not log
  127.                 $this->log->writeLog(
  128.                     [
  129.                         IOptionService::KEY_CLASS => get_class($this),
  130.                         IOptionService::KEY_FUNCTION => __FUNCTION__,
  131.                         IOptionService::KEY_MESSAGE => "User is not connected. He can't access to the application",
  132.                     ],
  133.                     Log::MESSAGE_ERROR
  134.                 );
  135.                 $this->redirectLogout($event);
  136.             } elseif (
  137.                 !$this->fileService->checkFile(
  138.                     $this->parameterBag->get('app.connection_dir').DIRECTORY_SEPARATOR.
  139.                     $user->getUsername().'-'.$this->session->getId()
  140.                 )
  141.             ) {
  142.                 // logger - try to connect with no log
  143.                 $this->log->writeLog(
  144.                     [
  145.                         IOptionService::KEY_CLASS => get_class($this),
  146.                         IOptionService::KEY_FUNCTION => __FUNCTION__,
  147.                         IOptionService::KEY_MESSAGE => 'User is already connected on another device',
  148.                     ],
  149.                     Log::MESSAGE_ERROR
  150.                 );
  151.                 // $this->session->invalidate();
  152.                 // $this->session->clear();
  153.                 $this->redirectLogout($event);
  154.             } else if (!empty($user) && $user instanceof BaseAuth && !empty($user->getValidationCode()) && $event->getRequest()->attributes->get('_route') != "auth_activation") {
  155.                 // logger - try to connect with no log
  156.                 $this->log->writeLog(
  157.                     [
  158.                         IOptionService::KEY_CLASS => get_class($this),
  159.                         IOptionService::KEY_FUNCTION => __FUNCTION__,
  160.                         IOptionService::KEY_MESSAGE => "User has to connect with wright status. He can't access to the application"
  161.                     ],
  162.                     Log::MESSAGE_ERROR
  163.                 );
  164.                 $this->redirectLogout($event);
  165.             }  else {
  166.                 if (null == $this->session->get(IAppService::SESSION_URL) && !empty($user)) {
  167.                     $this->session->set(IAppService::SESSION_URL, [
  168.                         'last_date' => new \DateTime(),
  169.                         'page' => $event->getRequest()->getRequestUri(),
  170.                         'route' => $event->getRequest()->get('_route'),
  171.                     ]);
  172.                 } elseif (!empty($user)) {
  173.                     $lastUrl $this->session->get(IAppService::SESSION_URL);
  174.                     if (
  175.                         null != $lastUrl['last_date']
  176.                         && !CommonForm::checkActivity($lastUrl['last_date'], IAppService::MAX_IDLE_TIME)
  177.                     ) {
  178.                         // logger - timeout
  179.                         $this->log->writeLog(
  180.                             [
  181.                                 IOptionService::KEY_CLASS => get_class($this),
  182.                                 IOptionService::KEY_FUNCTION => __FUNCTION__,
  183.                                 IOptionService::KEY_MESSAGE => 'Connection TIMEOUT',
  184.                             ],
  185.                             Log::MESSAGE_ERROR
  186.                         );
  187.                         // $this->session->clear();
  188.                         $this->session->remove(IAppService::SESSION_URL);
  189.                         $this->redirectLogout($event);
  190.                     } else {
  191.                        // Permert de contrôler l'abonnement de l'utilisateur
  192.                         $this->checkSubscription($event,$controller[0]);
  193.                         
  194.                         $this->session->set(IAppService::SESSION_URL, [
  195.                             'last_date' => new \DateTime(),
  196.                             'page' => $event->getRequest()->getRequestUri(),
  197.                             'route' => $event->getRequest()->get('_route'),
  198.                         ]);
  199.                         $this->log->writeLog(
  200.                             [
  201.                                 IOptionService::KEY_CLASS => get_class($this),
  202.                                 IOptionService::KEY_FUNCTION => __FUNCTION__,
  203.                                 IOptionService::KEY_ACCOUNT => $user->getUsername(),
  204.                             ],
  205.                             Log::MESSAGE_INFO
  206.                         );
  207.                     }
  208.                 }
  209.             }
  210.         }
  211.     }
  212.     public static function getSubscribedEvents()
  213.     {
  214.         return [
  215.             KernelEvents::CONTROLLER => 'onKernelController',
  216.         ];
  217.     }
  218.     public function redirectLogout(ControllerEvent $event)
  219.     {
  220.         if ($event->getRequest()->isMethod('POST') && $event->getRequest()->isXmlHttpRequest()) {
  221.             if (!$event->getController() instanceof AuthController) {
  222.                 $event->setController(function () {
  223.                     return new JsonResponse([
  224.                         'code' => 'signout',
  225.                         'redirect' => $this->parameterBag->get('app.url').'signout',
  226.                     ], 400);
  227.                 });
  228.             } else {
  229.                 $event->setController(function () {
  230.                     return new JsonResponse('signout'200);
  231.                 });
  232.             }
  233.         } else {
  234.             $event->setController(function () {
  235.                 return new RedirectResponse($this->parameterBag->get('app.url').'signout');
  236.             });
  237.         }
  238.     }
  239.     public function redirectionMaintenance(ControllerEvent $event)
  240.     {
  241.         if ($event->getRequest()->isMethod('POST') && $event->getRequest()->isXmlHttpRequest()) {
  242.             if (!$event->getController() instanceof AuthController) {
  243.                 $event->setController(function () {
  244.                     return new JsonResponse([
  245.                         'redirect' => $this->parameterBag->get('app.url').'maintenance',
  246.                     ], 200);
  247.                 });
  248.             } else {
  249.                 $event->setController(function () {
  250.                     return new JsonResponse('maintenance'200);
  251.                 });
  252.             }
  253.         } else {
  254.             $event->setController(function () {
  255.                 return new RedirectResponse($this->parameterBag->get('app.url').'maintenance');
  256.             });
  257.         }
  258.     }
  259. }