Check for duplicate usernames does not properly increment

Created on 18 July 2023, almost 2 years ago
Updated 30 July 2024, 9 months ago

Problem/Motivation

In autoUsernameGenerateUsername(), the code checks if the username exists, and this code is meant to add a numeric increment until it finds a unique username:

    // Lets check if our name is used somewhere else, and append _1 if it is
    // eg:(chris_123). We do this regardless of whether hook has run, as we
    // can't assume the hook implementation will do this santity check.
    $i = 0;
    do {
      $new_name = empty($i) ? $new_name : $new_name . '_' . $i;
      $found = $this->databaseConnection
        ->select('users_field_data', 'u')
        ->fields('u')
        ->condition('uid', $account->id(), '!=')
        ->condition('name', $new_name)
        ->execute()
        ->fetchAll();
      $i++;
    } while (!empty($found));

The problem is, `$new_name` is overwritten with the previous value. So if multiple users register `info` for example, the result is `info_1_2_3_4_5_6_7_8_9`.

Steps to reproduce

  • Set the auto username pattern to evaluate PHP
  • Set pattern to: <?php echo substr("[user:mail]", 0, strpos("[user:mail]", "@"));?>
  • Save a user with email info@example.com. Result: info
  • Save a user with email info@example2.com. Result: info_1
  • Save a user with email info@example3.com. Result: info_1_2

Proposed resolution

Rework the increment code to use a new variable in the do while loop.

Remaining tasks

Patch and merge request coming shortly!

πŸ› Bug report
Status

Fixed

Version

1.0

Component

Code

Created by

πŸ‡ΊπŸ‡ΈUnited States earthday47 New York

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

Merge Requests

Comments & Activities

Production build 0.71.5 2024