Skip to content

Make generateUsername function deterministic #14

@tomast1337

Description

@tomast1337

The current implementation of the generateUsername function relies on a random number to generate unique usernames when the base username is already taken. This can lead to non-deterministic behavior and potentially "non-terminating" states.

Proposed Solution
Modify the generateUsername function to use a counter instead of a random number. This will ensure deterministic and unique username generation.

public async generateUsername(inputUsername: string) {
  // Normalize username (remove accents, replace spaces with underscores)
  const baseUsername = inputUsername
    .replace(' ', '_')
    .normalize('NFKD')
    .replace(/[\u0300-\u036f]/g, '')
    .replace(/[^a-zA-Z0-9_]/g, '');
  let newUsername = baseUsername;

  // Find if there's already a user with the same username
  let nameTaken = await this.usernameExists(baseUsername);
  let counter = 1;

  while (nameTaken) {
    newUsername = `${baseUsername}_${counter}`;
    nameTaken = await this.usernameExists(newUsername);
    counter++;
  }

  return newUsername;
}

While this solution addresses the issue, it's more a quick fix rather than a comprehensive one.

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions