<?php
// src/EventSubscriber/TokenSubscriber.php
namespace App\EventSubscriber;
use App\Controller\TokenAuthenticatedController;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\ControllerEvent;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\HttpKernel\KernelEvents;
use Psr\Log\LoggerInterface;
use App\Service\OAuth2\Autoloader;
use Doctrine\DBAL\Connection;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
use App\Service\OAuth2\Storage\Pdo;
use App\Service\OAuth2\Server;
use App\Service\OAuth2\Request;
use App\Service\OAuth2\Response;
class TokenSubscriber implements EventSubscriberInterface
{
private $tokens;
public function __construct(Connection $connection, ParameterBagInterface $params, LoggerInterface $apiLogger)
{
$this->connection = $connection;
$this->params = $params;
$this->logger = $apiLogger;
}
public function onKernelController(ControllerEvent $event)
{
$controller = $event->getController();
$allowed_ip = $this->params->get('api.allowed_ips');
// when a controller class defines multiple action methods, the controller
// is returned as [$controllerInstance, 'methodName']
if (is_array($controller)) {
$controller = $controller[0];
}
if(!in_array($_SERVER['REMOTE_ADDR'],$allowed_ip) && !in_array('0.0.0.0', $allowed_ip)){
$this->logger->warning("API called from not allowed ip",array("REMOTE_ADDR" => $_SERVER['REMOTE_ADDR']) );
throw new AccessDeniedHttpException();
}
if ($controller instanceof TokenAuthenticatedController) {
$token = $event->getRequest()->query->get('token');
Autoloader::register();
/** @var \Doctrine\DBAL\Connection */
$connectionParams = $this->connection->getParams();
$db_user = $connectionParams['user'];
$db_passwd = $connectionParams['password'];
$db_host = $connectionParams['host'];
$db_port = $connectionParams['port'];
$db_name = $connectionParams['dbname'];
$db_dsn = "pgsql:host=".$db_host.";port=".$db_port.";dbname=".$db_name.";";
// create your storage again
$storage = new Pdo(array('dsn' => $db_dsn, 'username' => $db_user, 'password' => $db_passwd));
// create your server again
$server = new Server($storage);
// Handle a request for an OAuth2.0 Access Token and send the response to the client
if (!$server->verifyResourceRequest(Request::createFromGlobals(), new Response())) {
$server->getResponse()->send();
die;
}
}
}
public static function getSubscribedEvents()
{
return [
KernelEvents::CONTROLLER => 'onKernelController',
];
}
}