<?php
namespace App\EventListener;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use App\Repository\UsersRepository;
class TokenListener
{
private $usersRepository;
public function __construct(UsersRepository $usersRepository)
{
$this->usersRepository = $usersRepository;
}
public function onKernelRequest(RequestEvent $event)
{
$request = $event->getRequest();
$path = $request->getPathInfo();
// dump(strpos($path, '/app/user/login') );
// dump(strpos($path, 'app/user/signup') );
// dump(strpos($path, 'app/article/get-home') );
// die;
if ( strpos($path, '/app/article') === 0
|| strpos($path, '/app/invoice') === 0
|| strpos($path, '/app/cart') === 0
|| strpos($path, '/app/order') === 0
){
if(strpos($path, '/app/invoice/view-invoice/') !== 0 && strpos($path, '/app/user/login') !== 0
&& strpos($path, '/app/user/signup') !== 0 && strpos($path, '/app/article/get-home') !== 0
&& strpos($path, '/app/user/get-roles') !== 0){
$token = $request->headers->get('X-Token');
if (!$this->isValidToken($token))
{
$response = new Response('Invalid token', Response::HTTP_UNAUTHORIZED);
$event->setResponse($response);
}
}
}
}
public function isValidToken(string $token): bool
{
$user = $this->usersRepository->findOneBy(['token' => $token]);
return $user !== null;
}
}