<?php
namespace Elements\Bundle\AzureAuthBundle\EventSubscriber;
use Elements\Bundle\AzureAuthBundle\Service\RestrictionService;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\ResponseEvent;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\KernelEvents;
class CodeInjectionSubscriber implements EventSubscriberInterface
{
protected $enabled = false;
public function __construct(
private RestrictionService $restrictionService
)
{
}
/**
* @return array
*/
public static function getSubscribedEvents()// : array
{
return [
KernelEvents::RESPONSE => ['inject', 0],
KernelEvents::REQUEST => ['check', 0],
];
}
/**
* @param RequestEvent $event
*/
public function check(RequestEvent $event) {
// only enable on login page
if ($event->isMasterRequest()) {
if ($event->getRequest()->getPathInfo() == "/admin/login"&&
$this->restrictionService->checkIpAddresses($event->getRequest()->getClientIp())
) {
$this->enabled = true;
}
}
}
/**
* @param ResponseEvent $event
*/
public function inject(ResponseEvent $event) {
$response = $event->getResponse();
if ($this->enabled && $event->isMasterRequest()) {
$content = $response->getContent();
// search for the end <head> tag, and insert the google analytics code before
// this method is much faster than using simple_html_dom and uses less memory
$bodyEndPosition = strripos($content, '</body>');
if ($bodyEndPosition !== false) {
$code = '<script src="/bundles/elementsazureauth/js/main.js"></script>';
$content = substr_replace($content, $code . "\n\n" . '</body>', $bodyEndPosition, 7);
}
$headEndPosition = strripos($content, '</head>');
if ($headEndPosition !== false) {
$code = '<link rel="stylesheet" href="/bundles/elementsazureauth/css/style.css" type="text/css">';
$content = substr_replace($content, $code . "\n\n" . '</head>', $headEndPosition, 7);
}
$response->setContent($content);
}
}
}