<?php
namespace App\EventSubscriber;
use App\Entity\WhiteList;
use App\Service\System\Location;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\ExceptionEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpKernel\Event\ControllerEvent;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
class RequestSubscriber implements EventSubscriberInterface
{
public function __construct(
EntityManagerInterface $entityManager,
TokenStorageInterface $tokenStorage,
Location $location
)
{
$this->em = $entityManager;
$this->tokenStorage = $tokenStorage;
$this->location = $location;
}
public static function getSubscribedEvents()
{
// return the subscribed events, their methods and priorities
return [
KernelEvents::CONTROLLER => [
['logException', 0],
],
];
}
/**
* @param ControllerEvent $event
*/
public function logException($event)
{
$token = $this->tokenStorage->getToken();
$location = $this->location;
$user_data = $location->getUserData();
$request_url = $user_data['request_url'];
$firewall = $_SERVER['FIREWALL'];
if(!is_null($token)) {
$user = $token->getUser();
$last_login = $user->getLastLogin();
$this_time = (new \DateTime());
if(
(
$last_login and
$last_login < (clone $this_time)->modify('-20 minutes')
) and
$request_url !== '/security'
){
if (isset($_SESSION))
session_destroy();
$event->setController(function () {
return new RedirectResponse('/');
});
}
if($firewall === 'true') {
$user_ip = $user_data['ip'];
$logout = true;
$white_list = $this->em->getRepository(WhiteList::class)->findBy([
'ip' => $user_ip
]);
if ($white_list) {
foreach ($white_list as $white) {
$status_user = $white->checkUser($user);
if ($status_user) {
$logout = false;
break;
}
}
}
if ($logout) {
if (isset($_SESSION))
session_destroy();
$event->setController(function () {
return new RedirectResponse('/logout/no/valid/ip');
});
}
}
}
}
}