You are here

public function UserLoginHttpTest::testGlobalLoginFloodControl in Drupal 9

Same name and namespace in other branches
  1. 8 core/modules/user/tests/src/Functional/UserLoginHttpTest.php \Drupal\Tests\user\Functional\UserLoginHttpTest::testGlobalLoginFloodControl()

Tests the global login flood control.

See also

\Drupal\basic_auth\Tests\Authentication\BasicAuthTest::testGlobalLoginFloodControl

\Drupal\user\Tests\UserLoginTest::testGlobalLoginFloodControl

File

core/modules/user/tests/src/Functional/UserLoginHttpTest.php, line 290

Class

UserLoginHttpTest
Tests login and password reset via direct HTTP.

Namespace

Drupal\Tests\user\Functional

Code

public function testGlobalLoginFloodControl() {
  $database = \Drupal::database();
  $this
    ->config('user.flood')
    ->set('ip_limit', 2)
    ->set('user_limit', 4000)
    ->save();
  $user = $this
    ->drupalCreateUser([]);
  $incorrect_user = clone $user;
  $incorrect_user->passRaw .= 'incorrect';

  // Try 2 failed logins.
  for ($i = 0; $i < 2; $i++) {
    $response = $this
      ->loginRequest($incorrect_user
      ->getAccountName(), $incorrect_user->passRaw);
    $this
      ->assertEquals('400', $response
      ->getStatusCode());
  }

  // IP limit has reached to its limit. Even valid user credentials will fail.
  $response = $this
    ->loginRequest($user
    ->getAccountName(), $user->passRaw);
  $this
    ->assertHttpResponseWithMessage($response, '403', 'Access is blocked because of IP based flood prevention.');
  $last_log = $database
    ->select('watchdog', 'w')
    ->fields('w', [
    'message',
  ])
    ->condition('type', 'user')
    ->orderBy('wid', 'DESC')
    ->range(0, 1)
    ->execute()
    ->fetchField();
  $this
    ->assertEquals('Flood control blocked login attempt from %ip', $last_log, 'A watchdog message was logged for the login attempt blocked by flood control per IP.');
}