src/EventSubscriber/UserActivitySubscriber.php line 27

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(
  12.         private readonly TokenStorageInterface $tokenStorage,
  13.         private readonly int $maxInactivityInSec = 3600
  14.     ) {
  15.     }
  16.     public static function getSubscribedEvents(): array
  17.     {
  18.         return [
  19.             KernelEvents::REQUEST => 'onKernelRequest',
  20.         ];
  21.     }
  22.     public function onKernelRequest(RequestEvent $event)
  23.     {
  24.         $request = $event->getRequest();
  25.         $token = $this->tokenStorage->getToken();
  26.         if ($token instanceof TokenInterface) {
  27.             // Użytkownik jest zalogowany
  28.             $lastActivity = $request->getSession()->get('last_activity');
  29.             // Sprawdź, czy minęła godzina od ostatniej aktywności
  30.             if ($lastActivity instanceof \DateTimeInterface && time() - $lastActivity->getTimestamp() > $this->maxInactivityInSec) {
  31.                 // Użytkownik jest nieaktywny przez godzinę, wyloguj go
  32.                 $this->tokenStorage->setToken(null);
  33.                 $request->getSession()->invalidate();
  34.                 throw new AuthenticationException('Twoja sesja wygasła z powodu braku aktywności.');
  35.             }
  36.             // Aktualizuj czas ostatniej aktywności
  37.             $request->getSession()->set('last_activity', new \DateTime());
  38.         }
  39.     }
  40. }