<?php
namespace App\Security;
use App\Security\BruteforceProtectedControllerInterface;
use App\Security\BruteforceProtectionHandler;
use Pimcore\Bundle\AdminBundle\Security\Exception\BruteforceProtectionException;
use Pimcore\Bundle\CoreBundle\EventListener\Traits\PimcoreContextAwareTrait;
use Pimcore\Http\Request\Resolver\PimcoreContextResolver;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\ControllerEvent;
use Symfony\Component\HttpKernel\Event\ExceptionEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Pimcore\Log\ApplicationLogger;
use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
/**
* @internal
*/
class BruteforceProtectionListener implements EventSubscriberInterface
{
use PimcoreContextAwareTrait;
/**
* @var BruteforceProtectionHandler
*/
protected $handler;
/**
* @var ApplicationLogger
*/
private $logger;
private $authenticationUtils;
/**
* @param BruteforceProtectionHandler $handler
*/
public function __construct(BruteforceProtectionHandler $handler, ApplicationLogger $logger,AuthenticationUtils $authenticationUtils)
{
$this->handler = $handler;
$this->logger = $logger;
$this->authenticationUtils = $authenticationUtils;
}
/**
* {@inheritdoc}
*/
public static function getSubscribedEvents()
{
return [
KernelEvents::CONTROLLER => 'onKernelController',
KernelEvents::EXCEPTION => 'onKernelException',
];
}
public function onKernelController(ControllerEvent $event)
{
$request = $event->getRequest();
if (!$this->matchesPimcoreContext($request, PimcoreContextResolver::CONTEXT_DEFAULT)) {
return;
}
$callable = $event->getController();
if (is_array($callable)) {
$controller = $callable[0];
if ($controller instanceof BruteforceProtectedControllerInterface) {
$this->handler->checkProtection($this->authenticationUtils->getLastUsername(), $request);
}
}
}
public function onKernelException(ExceptionEvent $event)
{
// handle brute force exception and return a plaintext response
$e = $event->getThrowable();
if ($e instanceof BruteforceProtectionException) {
$this->logger->error('Error al verificar el usuario ' . $e->getMessage());
$event->setResponse(new Response($e->getMessage()));
}
}
}