autoban-8.x-1.x-dev/src/EventSubscriber/AutobanSubscriber.php

src/EventSubscriber/AutobanSubscriber.php
<?php

declare(strict_types=1);

namespace Drupal\autoban\EventSubscriber;

use Drupal\autoban\Controller\AutobanController;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpKernel\Event\ExceptionEvent;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\HttpFoundation\Request;
use Drupal\Core\Config\ConfigFactoryInterface;

/**
 * Autoban event subscriber.
 */
final class AutobanSubscriber implements EventSubscriberInterface {

  /**
   * Constructs an AutobanSubscriber object.
   */
  public function __construct(
    private readonly AutobanController $autoban,
    private readonly ConfigFactoryInterface $configFactory,
  ) {}

  /**
   * {@inheritdoc}
   */
  public static function getSubscribedEvents(): array {
    return [
      KernelEvents::EXCEPTION => ['onKernelException'],
    ];
  }

  /**
   * Ban on Kernel exception.
   */
  public function onKernelException(ExceptionEvent $event) {
    $throwable = $event->getThrowable();
    if ($throwable instanceof NotFoundHttpException
    || $throwable instanceof AccessDeniedHttpException) {
      $this->ban($event->getRequest());
    }
  }

  /**
   * Ban the IP.
   */
  protected function ban(Request $request) {
    $config = $this->configFactory->get('autoban.settings');
    $force_mode = $config->get('force_mode') ?? FALSE;
    if (!$force_mode) {
      return;
    }

    $banManagerList = $this->autoban->getBanProvidersList();
    if (empty($banManagerList)) {
      return;
    }

    reset($banManagerList);
    $provider = key($banManagerList);

    $banManagerData = $this->autoban->getBanManagerData($provider);
    $banData = [
      'provider' => $banManagerData,
      'entity' => ['id' => 'force'],
    ];

    $ip = $request->getClientIp();
    $this->autoban->banIp($ip, $banData);
  }

}

Главная | Обратная связь

drupal hosting | друпал хостинг | it patrol .inc