src/EventSubscriber/TokenSubscriber.php line 25

  1. <?php
  2. // src/EventSubscriber/TokenSubscriber.php
  3. namespace App\EventSubscriber;
  4. use App\Controller\TokenAuthenticatedController;
  5. use App\Repository\ConfigRepository;
  6. use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
  7. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  8. use Symfony\Component\HttpKernel\Event\ControllerEvent;
  9. use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
  10. use Symfony\Component\HttpKernel\KernelEvents;
  11. class TokenSubscriber implements EventSubscriberInterface
  12. {
  13.     public function __construct
  14.     (
  15.         ParameterBagInterface $params,
  16.         ConfigRepository $configRepository
  17.     )
  18.     {
  19.         $this->params = $params;
  20.         $this->configRepository = $configRepository;
  21.     }
  22.     public function onKernelController(ControllerEvent $event)
  23.     {
  24.         $controller = $event->getController();
  25.         $whitelist = [
  26.             '127.0.0.1',
  27.             '::1'
  28.         ];
  29.         if((!in_array($_SERVER['REMOTE_ADDR'], $whitelist))) {
  30.             if (is_array($controller)) {
  31.                 $controller = $controller[0];
  32.             }
  33.             if ($controller instanceof TokenAuthenticatedController) {
  34.                 $token  = $event->getRequest()->headers->get('X-AUTH-TOKEN');
  35.                 $url    = $_SERVER['HTTP_HOST'];
  36.                 $config = $this->configRepository->findOneBy([
  37.                     'ApiToken'      => $token,
  38.                     'PlatFormUrl'   => $url,
  39.                     'Active'        => true
  40.                 ]);
  41.                 if(is_null($config)) {
  42.                     throw new AccessDeniedHttpException('This action needs valid token!');
  43.                 }
  44. //                if (!in_array($token, $this->tokens)) {
  45. //                    throw new AccessDeniedHttpException('This action needs a valid token!');
  46. //                }
  47.             }
  48.         }
  49.     }
  50.     public static function getSubscribedEvents()
  51.     {
  52.         return [
  53.             KernelEvents::CONTROLLER => 'onKernelController',
  54.         ];
  55.     }
  56. }