src/Security/Voter/IsActiveSessionVoter.php line 16

Open in your IDE?
  1. <?php
  2. namespace App\Security\Voter;
  3. use App\Utils\KeycloakAdmin;
  4. use Symfony\Component\EventDispatcher\EventDispatcherInterface;
  5. use Symfony\Component\HttpFoundation\RedirectResponse;
  6. use Symfony\Component\HttpFoundation\RequestStack;
  7. use Symfony\Component\HttpKernel\Event\ResponseEvent;
  8. use Symfony\Component\HttpKernel\KernelEvents;
  9. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  10. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  11. use Symfony\Component\Security\Core\Authorization\Voter\Voter;
  12. use Symfony\Component\Security\Core\User\UserInterface;
  13. class IsActiveSessionVoter extends Voter
  14. {
  15.     /**
  16.      * @param RequestStack $requestStack
  17.      * @param EventDispatcherInterface $dispatcher
  18.      * @param UrlGeneratorInterface $urlGenerator
  19.      */
  20.     public function __construct(private readonly RequestStack             $requestStack,
  21.                                 private readonly EventDispatcherInterface $dispatcher,
  22.                                 private readonly UrlGeneratorInterface    $urlGenerator)
  23.     {
  24.     }
  25.     protected function supports(string $attribute$subject): bool
  26.     {
  27.         return $attribute == 'IS_ACTIVE_SESSION';
  28.     }
  29.     protected function voteOnAttribute(string $attribute$subjectTokenInterface $token): bool
  30.     {
  31.         $user $token->getUser();
  32.         // if the user is anonymous, do not grant access
  33.         if (!$user instanceof UserInterface) {
  34.             return false;
  35.         }
  36.         $credentials $this->requestStack->getSession()->get('tokenSecurity');
  37.         if ($credentials) {
  38.             $keycloak = new KeycloakAdmin(false);
  39.             if ($keycloak->isSessionActive()) {
  40.                 return true;
  41.             } else {
  42.                 $this->dispatcher->addListener(KernelEvents::RESPONSE, array($this'onKernelResponse'));
  43.             }
  44.         }
  45.         return false;
  46.     }
  47.     private function onKernelResponse(ResponseEvent $event)
  48.     {
  49.         $event->setResponse(new RedirectResponse(
  50.             $this->urlGenerator->generate('app_logout')
  51.         ));
  52.     }
  53. }