You are here

function login_user_block_user_name in Login Security 8

Same name and namespace in other branches
  1. 5 login_security.module \login_user_block_user_name()
  2. 6 login_security.module \login_user_block_user_name()
  3. 7 login_security.module \login_user_block_user_name()
  4. 2.x login_security.module \login_user_block_user_name()

Block a user by user name. If no user id then block current user.

2 calls to login_user_block_user_name()
LoginSecurityEmailTest::testBlockedEmail in src/Tests/LoginSecurityEmailTest.php
Test that email is sent when users are blocked.
login_security_validate in ./login_security.module
Implements hook_validate().

File

./login_security.module, line 364
Login Security module hooks.

Code

function login_user_block_user_name($variables, FormStateInterface $form_state) {
  $conf = \Drupal::config('login_security.settings');

  // If the user exists.
  if ($variables['@uid'] > 1) {

    // Modifying the user table is not an option so it disables the user hooks.
    // Need to do firing the hook so user_notifications can be used.
    $uid = $variables['@uid'];
    $account = User::load($uid);

    // Block account if is active.
    if ($account->status->value == 1) {
      $account->status
        ->setValue(0);
      $account
        ->save();

      // Remove user from site now.
      if (\Drupal::currentUser()
        ->isAuthenticated()) {
        user_logout();
      }

      // The watchdog alert is set to 'user' so it will show with other blocked
      // user messages.
      \Drupal::logger('login_security')
        ->notice('Blocked user @username due to security configuration.', $variables);

      // Also notify the user that account has been blocked.
      $form_state
        ->setErrorByName('void', SafeMarkup::format($conf
        ->get('user_blocked'), $variables));

      // Send notification.
      $to = $conf
        ->get('user_blocked_notification_emails');
      if ($to !== '') {
        $from = \Drupal::config('system.site')
          ->get('mail');
        $language = \Drupal::languageManager()
          ->getDefaultLanguage();
        return \Drupal::service('plugin.manager.mail')
          ->mail('login_security', 'block_user_notify', $to, $language, $variables, $from, TRUE);
      }
    }
  }
}