Calling user_load_by_name() is not necessary

Created on 20 September 2025, 2 days ago

Problem/Motivation

The validation handler added to the user account forms contains the following code.

if (\Drupal::currentUser()->hasPermission('bypass user restriction rules')) {
  return;
}

// During login, the current user will not be logged in, so check first and
// load the account used to log in.
if (!\Drupal::currentUser()->isAuthenticated()) {
  $user = user_load_by_name($form_state->getValue('name'));
  if ($user && $user->hasPermission('bypass user restriction rules')) {
    return;
  }
}

Calling user_load_by_name() is not necessary because:

In the login form, UserLoginForm::validateAuthentication() already stores the user ID using the following code.

      // We are not limited by flood control, so try to authenticate.
      // Store the user ID in form state as a flag for self::validateFinal().
      if ($this->userAuth instanceof UserAuthenticationInterface) {
        $form_state->set('uid', $this->userAuth
          ->authenticateAccount($account, $password) ? $account->id() : FALSE);
      }
      else {
        $uid = $this->userAuth
          ->authenticate($form_state->getValue('name'), $password);
        $form_state->set('uid', $uid);
      }
    }
    elseif (!$this->userAuth instanceof UserAuthenticationInterface) {
      $uid = $this->userAuth
        ->authenticate($form_state->getValue('name'), $password);
      $form_state->set('uid', $uid);
    }

In the registration form, when visitors create their own account, the account has not been yet created when the validation handler is invoked. Loading it would fail.

Proposed resolution

  • In the login form, load the account using the user ID stored by the previously invoked validation handler
  • In the registration form, do not load the account
🐛 Bug report
Status

Active

Version

3.0

Component

Code

Created by

🇮🇹Italy apaderno Brescia, 🇮🇹

Live updates comments and jobs are added and updated live.
Sign in to follow issues

Merge Requests

Comments & Activities

Not all content is available!

It's likely this issue predates Contrib.social: some issue and comment data are missing.

Production build 0.71.5 2024