<?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)
{
$logout = true;
$token = $this->tokenStorage->getToken();
if (
!is_null($token) and
$_SERVER['FIREWALL'] == 'true'
) {
$user_data = $this->location->getUserData();
$user_ip = $user_data['ip'];
$white_list = $this->em->getRepository(WhiteList::class)->findBy(['ip' => $user_ip]);
if ($white_list) {
foreach ($white_list as $white){
$status_user = $white->checkUser($token->getUser());
if($status_user) {
$logout = false;
break;
}
}
}
if($logout){
if(isset($_SESSION))
session_destroy();
$event->setController(function () {
return new RedirectResponse('/logout/no/valid/ip');
});
}
}
}
}