summaryrefslogtreecommitdiffstatshomepage
path: root/core/modules/user/src/EventSubscriber/UserFloodSubscriber.php
blob: 2acf9af6cbc533d5c954edca4a26c0a04bd80502 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
<?php

namespace Drupal\user\EventSubscriber;

use Drupal\user\Event\UserEvents;
use Drupal\user\Event\UserFloodEvent;
use Drupal\Core\Site\Settings;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Psr\Log\LoggerInterface;

/**
 * Logs details of User Flood Control events.
 */
class UserFloodSubscriber implements EventSubscriberInterface {

  /**
   * The default logger service.
   *
   * @var \Psr\Log\LoggerInterface
   */
  protected $logger;

  /**
   * Constructs a UserFloodSubscriber.
   *
   * @param \Psr\Log\LoggerInterface $logger
   *   A logger instance.
   */
  public function __construct(?LoggerInterface $logger = NULL) {
    $this->logger = $logger;
  }

  /**
   * {@inheritdoc}
   */
  public static function getSubscribedEvents(): array {
    $events[UserEvents::FLOOD_BLOCKED_USER][] = ['blockedUser'];
    $events[UserEvents::FLOOD_BLOCKED_IP][] = ['blockedIp'];
    return $events;
  }

  /**
   * An attempt to login has been blocked based on user name.
   *
   * @param \Drupal\user\Event\UserFloodEvent $floodEvent
   *   The flood event.
   */
  public function blockedUser(UserFloodEvent $floodEvent) {
    if (Settings::get('log_user_flood', TRUE)) {
      $uid = $floodEvent->getUid();
      if ($floodEvent->hasIp()) {
        $ip = $floodEvent->getIp();
        $this->logger->notice('Flood control blocked login attempt for uid %uid from %ip', ['%uid' => $uid, '%ip' => $ip]);
        return;
      }
      $this->logger->notice('Flood control blocked login attempt for uid %uid', ['%uid' => $uid]);
    }
  }

  /**
   * An attempt to login has been blocked based on IP.
   *
   * @param \Drupal\user\Event\UserFloodEvent $floodEvent
   *   The flood event.
   */
  public function blockedIp(UserFloodEvent $floodEvent) {
    if (Settings::get('log_user_flood', TRUE)) {
      $this->logger->notice('Flood control blocked login attempt from %ip', ['%ip' => $floodEvent->getIp()]);
    }
  }

}