<?php
namespace App\EventSubscriber;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
class UserActivitySubscriber implements EventSubscriberInterface
{
public function __construct(
private readonly TokenStorageInterface $tokenStorage,
private readonly int $maxInactivityInSec = 3600
) {
}
public static function getSubscribedEvents(): array
{
return [
KernelEvents::REQUEST => 'onKernelRequest',
];
}
public function onKernelRequest(RequestEvent $event)
{
$request = $event->getRequest();
$token = $this->tokenStorage->getToken();
if ($token instanceof TokenInterface) {
// Użytkownik jest zalogowany
$lastActivity = $request->getSession()->get('last_activity');
// Sprawdź, czy minęła godzina od ostatniej aktywności
if ($lastActivity instanceof \DateTimeInterface && time() - $lastActivity->getTimestamp() > $this->maxInactivityInSec) {
// Użytkownik jest nieaktywny przez godzinę, wyloguj go
$this->tokenStorage->setToken(null);
$request->getSession()->invalidate();
throw new AuthenticationException('Twoja sesja wygasła z powodu braku aktywności.');
}
// Aktualizuj czas ostatniej aktywności
$request->getSession()->set('last_activity', new \DateTime());
}
}
}