src/EventSubscriber/UserActivitySubscriber.php line 32

Open in your IDE?
  1. <?php
  2. namespace App\EventSubscriber;
  3. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  4. use Symfony\Component\HttpKernel\Event\RequestEvent;
  5. use Symfony\Component\HttpKernel\KernelEvents;
  6. use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
  7. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  8. use Symfony\Component\Security\Core\Exception\AuthenticationException;
  9. class UserActivitySubscriber implements EventSubscriberInterface
  10. {
  11.     public function __construct(private TokenStorageInterface $tokenStorage, private int $maxInactivityInSec = 3600)
  12.     {
  13.     }
  14.     public static function getSubscribedEvents(): array
  15.     {
  16.         return [
  17.             KernelEvents::REQUEST => 'onKernelRequest',
  18.         ];
  19.     }
  20.     public function onKernelRequest(RequestEvent $event)
  21.     {
  22.         $request = $event->getRequest();
  23.         $token = $this->tokenStorage->getToken();
  24.         if ($token instanceof TokenInterface) {
  25.             // Użytkownik jest zalogowany
  26.             $lastActivity = $request->getSession()->get('last_activity');
  27.             // Sprawdź, czy minęła godzina od ostatniej aktywności
  28.             if ($lastActivity instanceof \DateTimeInterface && time() - $lastActivity->getTimestamp() > $this->maxInactivityInSec) {
  29.                 // Użytkownik jest nieaktywny przez godzinę, wyloguj go
  30.                 $this->tokenStorage->setToken(null);
  31.                 $request->getSession()->invalidate();
  32.                 throw new AuthenticationException('Twoja sesja wygasła z powodu braku aktywności.');
  33.             }
  34.             // Aktualizuj czas ostatniej aktywności
  35.             $request->getSession()->set('last_activity', new \DateTime());
  36.         }
  37.     }
  38. }