You are here

public function LoginSecurityUserBlockingTest::testUserBlocking in Login Security 2.x

Test user blocking.

File

tests/src/Functional/LoginSecurityUserBlockingTest.php, line 187

Class

LoginSecurityUserBlockingTest
Test Login Security's user-blocking restrictions and default messages.

Namespace

Drupal\Tests\login_security\Functional

Code

public function testUserBlocking() {
  $config = \Drupal::configFactory()
    ->getEditable('login_security.settings');
  $login_attempts_limit = 2;

  // Allow 2 attempts to login before being blocking is enforced.
  $config
    ->set('user_wrong_count', $login_attempts_limit)
    ->save();

  // We can drupalGetMails() to see if a notice went out to admin.
  // In the meantime, turn the message off just in case it doesn't get
  // caught properly yet.
  $config
    ->set('user_blocked_notification_emails', '')
    ->save();
  $normal_user = $this
    ->drupalCreateUser();

  // Intentionally break the password to repeat invalid logins.
  $new_pass = user_password();
  $normal_user
    ->setPassword($new_pass);
  $config
    ->set('notice_attempts_available', 1)
    ->save();

  // First try.
  $this
    ->drupalLoginLite($normal_user);
  $this
    ->assertText($this
    ->getAttemptsAvailableMessage(1, $login_attempts_limit), 'Attempts available message displayed.');
  $this
    ->assertFieldByName('form_id', 'user_login_form', 'Login form found.');

  // Turns off the warning message we looked for in the previous assert.
  $config
    ->set('notice_attempts_available', 0)
    ->save();

  // Second try.
  $this
    ->drupalLoginLite($normal_user);
  $this
    ->assertNoText($this
    ->getAttemptsAvailableMessage(2, $login_attempts_limit), 'Attempts available message NOT displayed.');
  $this
    ->assertFieldByName('form_id', 'user_login_form', 'Login form found.');

  // Turns back on the warning message we looked for in the previous assert.
  $this
    ->assertText(new FormattableMarkup('The user @user_name has been blocked due to failed login attempts.', [
    '@user_name' => $normal_user
      ->getAccountName(),
  ]), 'Blocked message displayed.');
  $this
    ->assertFieldByName('form_id', 'user_login_form', 'Login form found.');
}