BanSubscriber.php 1.58 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<?php

/**
 * @file
 * Definition of Drupal\ban\EventSubscriber\BanSubscriber.
 */

namespace Drupal\ban\EventSubscriber;

use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

use Drupal\ban\BanIpManager;

/**
 * Ban subscriber for controller requests.
 */
class BanSubscriber implements EventSubscriberInterface {

  /**
   * The manager used to check the IP against.
   *
25
   * @var \Drupal\ban\BanIpManager
26
27
28
29
30
31
   */
  protected $manager;

  /**
   * Construct the BanSubscriber.
   *
32
   * @param \Drupal\ban\BanIpManager $manager
33
34
35
36
37
38
39
   *   The manager used to check the IP against.
   */
  public function __construct(BanIpManager $manager) {
    $this->manager = $manager;
  }

  /**
40
   * Response with 403 if the visitor's IP address is banned.
41
42
43
44
45
   *
   * @param Symfony\Component\HttpKernel\Event\GetResponseEvent $event
   *   The Event to process.
   */
  public function onKernelRequestBannedIpCheck(GetResponseEvent $event) {
46
    $ip = $event->getRequest()->getClientIp();
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
    if ($this->manager->isDenied($ip)) {
      $response = new Response('Sorry, ' . check_plain($ip) . ' has been banned.', 403);
      $event->setResponse($response);
    }
  }

  /**
   * Registers the methods in this class that should be listeners.
   *
   * @return array
   *   An array of event listener definitions.
   */
  static function getSubscribedEvents() {
    $events[KernelEvents::REQUEST][] = array('onKernelRequestBannedIpCheck', 40);
    return $events;
  }

}