A platform for community discussion. Free, open, simple.
FEATURE: Generate random usernames instead of `userN` in code signup (#41954)
Keegan George1df32987f942
diff --git a/app/assets/stylesheets/common/login/code-login-form.scss b/app/assets/stylesheets/common/login/code-login-form.scssindex 55c4a0281b1..e922799ff6d 100644--- a/app/assets/stylesheets/common/login/code-login-form.scss+++ b/app/assets/stylesheets/common/login/code-login-form.scss@@ -1,5 +1,19 @@@use "lib/viewport";+@keyframes code-login-form-dice-roll {+ 0% {+ transform: rotate(0deg) scale(1);+ }++ 50% {+ transform: rotate(180deg) scale(1.2);+ }++ 100% {+ transform: rotate(360deg) scale(1);+ }+}+@keyframes code-login-form-step-in {from {opacity: 0;@@ -114,9 +128,57 @@gap: 0.25em;}+ &__username-input {+ // The regenerate button sits beside the input rather than inside it, so it+ // doesn't compete with password managers for the field's trailing edge.+ display: flex;+ align-self: stretch;+ gap: 0.5em;++ // Outweigh the base input[type="text"] margin-bottom so the input and the+ // regenerate button beside it stay the same height.+ input[type="text"] {+ flex: 1 1 auto;+ min-width: 0;+ width: auto;+ margin: 0;+ }+ }+&__new-account-username {width: 100%;- margin: 0;++ // Crossfade the text while a regenerated username is on its way, so the+ // new name fades in rather than snapping into place.+ @media (prefers-reduced-motion: no-preference) {+ transition: color 0.2s ease;++ &.--swapping {+ color: transparent;+ }+ }+ }++ &__username-regen {+ display: flex;+ flex: 0 0 auto;+ align-items: center;+ justify-content: center;++ // The dice glyph is wider than it is tall, so at the default 1em it+ // renders visually smaller than square icons.+ .d-icon {+ font-size: var(--font-up-2);+ }++ // One cycle matches the minimum rolling duration the component holds, so+ // the spin completes cleanly on fast responses and keeps going on slow+ // ones instead of freezing mid-roll.+ @media (prefers-reduced-motion: no-preference) {+ &.--rolling .d-icon {+ animation: code-login-form-dice-roll 0.4s ease infinite;+ }+ }}&__continue-to-site {diff --git a/app/controllers/session_controller.rb b/app/controllers/session_controller.rbindex 44f51c242bd..2ce7da8570a 100644--- a/app/controllers/session_controller.rb+++ b/app/controllers/session_controller.rb@@ -988,10 +988,12 @@ class SessionController < ApplicationControllersuccess_json.merge(account_created: true,user: serialize_data(user, UserSerializer, root: false),- # The username is only worth prefilling when it was derived- # from the email; otherwise it's a generic fallback and the- # client should make the user pick one.- prefill_username: SiteSetting.use_email_for_username_and_name_suggestions,+ # The generic "userN" fallback is a placeholder rather than a+ # suggestion, so the client leaves the field empty and makes+ # the user pick. Checked against the name actually assigned,+ # since generation can fall back for reasons beyond the+ # settings (e.g. unusable word lists).+ prefill_username: !UserNameSuggester.generic_username?(user.username),# Sites that lock usernames (e.g. username_change_period: 0)# can't offer an inline pick, so the client keeps the generated# name instead of dead-ending on a forbidden change.diff --git a/app/controllers/users_controller.rb b/app/controllers/users_controller.rbindex cf8b9a0e970..0d87b66cfb2 100644--- a/app/controllers/users_controller.rb+++ b/app/controllers/users_controller.rb@@ -628,6 +628,24 @@ class UsersController < ApplicationControllerrender json: checker.check_username(username, email)end+ def generate_random_username+ raise Discourse::NotFound if !SiteSetting.enable_random_usernames++ RateLimiter.new(nil, "random-username-#{request.remote_ip}", 20, 1.minute).performed!++ username = RandomUsernameGenerator.generate+ # The word lists are admin-editable, so they can end up unusable (e.g. once+ # unicode usernames are turned back off) while the feature is still on.+ if username.blank?+ return(+ render json: failed_json.merge(errors: [I18n.t("random_username.unavailable")]),+ status: :unprocessable_entity+ )+ end++ render json: { username: }+ end+def check_emailbeginRateLimiter.new(nil, "check-email-#{request.remote_ip}", 10, 1.minute).performed!diff --git a/app/services/user/action/create_from_verified_email.rb b/app/services/user/action/create_from_verified_email.rbindex e9a172484d5..179faeb16d5 100644--- a/app/services/user/action/create_from_verified_email.rb+++ b/app/services/user/action/create_from_verified_email.rb@@ -7,7 +7,12 @@ class User::Action::CreateFromVerifiedEmail < Service::ActionBaseoption :name, optional: truedef call- username = UserNameSuggester.suggest(email)+ # A random name beats the generic "userN" fallback here: there is no+ # signup form where the user could pick one before the account exists.+ # Sites that turn random names off fall through to that generic name.+ username =+ UserNameSuggester.suggest(email, allow_generic_fallback: false) ||+ RandomUsernameGenerator.generate || UserNameSuggester.suggest(email)user = User.where(staged: true).with_email(email).firstuser&.unstage!diff --git a/config/locales/client.en.yml b/config/locales/client.en.ymlindex 1372b3f59dc..7a9fd8ebf5f 100644--- a/config/locales/client.en.yml+++ b/config/locales/client.en.yml@@ -3087,6 +3087,7 @@ en:account_ready_continue: "Continue"username_label: "Username"username_placeholder: "Choose a username"+ regenerate_username: "Suggest a random username"change_avatar: "Change avatar"username_taken: "That username is taken. Try another."username_unavailable: "That username isn't available. Try %{suggestion}."diff --git a/config/locales/server.en.yml b/config/locales/server.en.ymlindex 7ce26a93825..7798de43688 100644--- a/config/locales/server.en.yml+++ b/config/locales/server.en.yml@@ -1918,6 +1918,9 @@ en:starttls_disabled: "The outgoing email configuration has STARTTLS disabled. This is almost never necessary. Consider removing <pre>DISCOURSE_SMTP_ENABLE_START_TLS=false</pre> from your environment. Please refer to <a href='https://meta.discourse.org/t/387286'>this topic</a> for more details."back_from_logster_text: "Back to site"+ random_username:+ unavailable: "A random username could not be generated. Check the random username word lists in your site settings."+site_settings:allow_bulk_invite: "Allow bulk invites by uploading a CSV file"disabled: "disabled"@@ -2222,6 +2225,9 @@ en:enable_local_logins: "Enable local username and password login based accounts. WARNING: if disabled, you may be unable to log in if you have not previously configured at least one alternate login method."enable_local_logins_via_email: "Allow users to request a one-click login link to be sent to them via email."enable_local_logins_via_code: "Allow members to sign up and log in faster using one-time email codes (OTPs)."+ enable_random_usernames: 'Generates random usernames for accounts created with a one-time email code using the format "adjective + noun + two random numbers" (example: QuietFalcon34). New members can change their username during the signup process.'+ random_username_adjectives: 'Words used as the first half of a randomly generated username. The leading letter is capitalized when the words are combined.'+ random_username_nouns: 'Words used as the second half of a randomly generated username. The leading letter is capitalized when the words are combined.'allow_passkeys_for_2fa: "Allow users to use a passkey to satisfy two-factor authentication when confirming a sensitive action."allow_new_registrations: "Allow new user registrations. Uncheck this to prevent anyone from creating a new account."enable_signup_cta: "Show a notice to returning anonymous users prompting them to sign up for an account."@@ -3067,6 +3073,7 @@ en:email_polling_disabled: "You must enable either manual, POP3 polling or have a custom mail poller enabled before enabling reply by email."user_locale_not_enabled: "You must first enable 'allow user locale' before enabling this setting."at_least_one_group_required: "You must specify at least one group for this setting."+ invalid_random_username_word_list: "This list must contain at least one word, and every word must be usable in a username on its own."invalid_regex: "Regex is invalid or not allowed."invalid_regex_with_message: "The regex '%{regex}' has an error: %{message}"email_editable_enabled: "You must disable 'email editable' before enabling this setting."diff --git a/config/routes.rb b/config/routes.rbindex f9fb02f3c1a..d7446c00efb 100644--- a/config/routes.rb+++ b/config/routes.rb@@ -652,6 +652,8 @@ Discourse::Application.routes.draw doendend+ get "#{root_path}/random-username" => "users#generate_random_username"+get "#{root_path}/trusted-session" => "users#trusted_session"post "#{root_path}/confirm-session" => "users#confirm_session"diff --git a/config/site_settings.yml b/config/site_settings.ymlindex 90b580acc36..b05eca1aa7b 100644--- a/config/site_settings.yml+++ b/config/site_settings.yml@@ -700,6 +700,28 @@ login:permanent_warning: falseallow_enabled_for:- everyone+ enable_random_usernames:+ client: true+ default: true+ area: "login"+ depends_on:+ - enable_local_logins_via_code+ random_username_adjectives:+ type: list+ list_type: compact+ default: "agile|amber|azure|bold|brave|breezy|bright|calm|candid|cheery|civic|clever|cosmic|crisp|curious|daring|deft|eager|earnest|fabled|gentle|golden|happy|hardy|hearty|humble|jolly|keen|kind|lively|lucid|lunar|mellow|merry|mighty|nimble|noble|plucky|proud|quick|quiet|rapid|rustic|silent|silver|smart|snappy|solar|stellar|sunny|swift|tidy|upbeat|valiant|vivid|warm|witty|zesty"+ area: "login"+ validator: "RandomUsernameWordListValidator"+ depends_on:+ - enable_random_usernames+ random_username_nouns:+ type: list+ list_type: compact+ default: "acorn|badger|beacon|bison|breeze|brook|canyon|cedar|comet|condor|coral|cougar|coyote|crane|cricket|dolphin|ember|falcon|fern|finch|fjord|fox|gecko|glacier|harbor|heron|hawk|ibis|jaguar|lagoon|lark|lemur|lynx|maple|marmot|meadow|meteor|nebula|newt|orca|osprey|otter|owl|panda|pebble|penguin|pine|prairie|puffin|quokka|raven|reef|river|sequoia|sparrow|summit|tundra|walrus|willow|wren|zephyr"+ area: "login"+ validator: "RandomUsernameWordListValidator"+ depends_on:+ - enable_random_usernamesenable_passkeys:client: truedefault: true@@ -1034,8 +1056,8 @@ users:reserved_usernames:type: listlist_type: compact- default: "admin|moderator|administrator|mod|sys|system|community|info|you|name|username|user|nickname|discourse|discourseorg|discourseforum|support|all|here"- mandatory_values: "admin|moderator|administrator|mod|sys|system|you|name|username|user|nickname|discourse|discourseorg|discourseforum|all|here"+ default: "admin|moderator|administrator|mod|sys|system|community|info|you|name|username|user|nickname|discourse|discourseorg|discourseforum|support|all|here|random-username"+ mandatory_values: "admin|moderator|administrator|mod|sys|system|you|name|username|user|nickname|discourse|discourseorg|discourseforum|all|here|random-username"area: "users"min_password_length:client: truediff --git a/frontend/discourse/app/components/code-login-form.gjs b/frontend/discourse/app/components/code-login-form.gjsindex f83b68f30c6..e1101474526 100644--- a/frontend/discourse/app/components/code-login-form.gjs+++ b/frontend/discourse/app/components/code-login-form.gjs@@ -38,6 +38,7 @@ const RESEND_COOLDOWN_SECONDS = 30;export default class CodeLoginForm extends Component {@service login;@service site;+ @service siteSettings;@service modal;@tracked email = this.args.initialEmail ?? "";@@ -56,6 +57,7 @@ export default class CodeLoginForm extends Component {@tracked usernameChecking = false;@tracked usernameError;@tracked usernameEditable = true;+ @tracked regenerating = false;@tracked avatarTemplate;@tracked avatarDetailsLoaded = false;@tracked secondFactorMethod = SECOND_FACTOR_METHODS.TOTP;@@ -366,7 +368,6 @@ export default class CodeLoginForm extends Component {can_upload_avatar: result.can_upload_avatar,});this.usernameEditable = result.can_edit_username;- // Only prefill an email-derived suggestion; otherwise the user picks one.this.username = result.prefill_username ? user.username : "";this.avatarTemplate = user.avatar_template;// Set when the server held back a DiscourseConnect provider handoff so this@@ -378,6 +379,40 @@ export default class CodeLoginForm extends Component {}}+ @action+ async regenerateUsername() {+ if (this.regenerating) {+ return;+ }++ this.regenerating = true;+ try {+ const before = this.username;+ // Hold the rolling state for at least one animation cycle so a fast+ // response doesn't cut the dice spin (and the text fade) short.+ const [result] = await Promise.all([+ ajax("/u/random-username.json"),+ new Promise((resolve) => discourseLater(resolve, 400)),+ ]);++ // Don't touch state (or fire the availability check) if the component+ // was torn down mid-roll, or clobber a name the user typed while the+ // request was in flight.+ if (this.isDestroying || this.username !== before) {+ return;+ }++ this.username = result.username;+ this.usernameError = null;+ this.usernameAvailable = false;+ await this.checkUsernameAvailability();+ } catch (e) {+ popupAjaxError(e);+ } finally {+ this.regenerating = false;+ }+ }+@actionusernameChanged(event) {this.username = event.target.value;@@ -741,18 +776,32 @@ export default class CodeLoginForm extends Component {<label for="code-login-username">{{i18n "code_login.username_label"}}</label>- <input- {{on "input" this.usernameChanged}}- type="text"- value={{this.username}}- id="code-login-username"- name="username"- autocomplete="off"- placeholder={{i18n "code_login.username_placeholder"}}- class="code-login-form__new-account-username"- aria-invalid={{if this.usernameError "true"}}- aria-describedby="code-login-username-error"- />+ <div class="code-login-form__username-input">+ <input+ {{on "input" this.usernameChanged}}+ type="text"+ value={{this.username}}+ id="code-login-username"+ name="username"+ autocomplete="off"+ placeholder={{i18n "code_login.username_placeholder"}}+ class="code-login-form__new-account-username+ {{if this.regenerating '--swapping'}}"+ aria-invalid={{if this.usernameError "true"}}+ aria-describedby="code-login-username-error"+ />+ {{#if this.siteSettings.enable_random_usernames}}+ <DButton+ @action={{this.regenerateUsername}}+ @icon="dice"+ @title="code_login.regenerate_username"+ @ariaLabel="code_login.regenerate_username"+ aria-busy={{if this.regenerating "true"}}+ class="btn-default code-login-form__username-regen+ {{if this.regenerating '--rolling'}}"+ />+ {{/if}}+ </div><divid="code-login-username-error"class="code-login-form__error"diff --git a/frontend/discourse/tests/integration/components/code-login-form-test.gjs b/frontend/discourse/tests/integration/components/code-login-form-test.gjsindex ca0b113af97..cbc3c839047 100644--- a/frontend/discourse/tests/integration/components/code-login-form-test.gjs+++ b/frontend/discourse/tests/integration/components/code-login-form-test.gjs@@ -123,7 +123,7 @@ module("Integration | Component | CodeLoginForm", function (hooks) {account_created: true,user: { id: 1, username: "jane", avatar_template: "/letter/j.png" },can_edit_username: true,- prefill_username: false,+ prefill_username: true,});}@@ -160,6 +160,106 @@ module("Integration | Component | CodeLoginForm", function (hooks) {"the trimmed name is sent");assert.dom(".code-login-form__complete-step").exists();+ assert+ .dom("#code-login-username")+ .hasValue("jane", "the assigned username is prefilled");+ });++ test("regenerates a random username suggestion on the account-ready step", async function (assert) {+ stubCodeRequest();+ pretender.post("/session/login-code/verify", () =>+ response({+ account_created: true,+ user: { id: 1, username: "jane", avatar_template: "/letter/j.png" },+ can_edit_username: true,+ prefill_username: true,+ })+ );+ pretender.get("/u/random-username.json", () =>+ response({ username: "QuietFalcon" })+ );++ await goToCodeStep();+ await fillIn(".d-otp-input", "123456");++ assert.dom("#code-login-username").hasValue("jane");++ await click(".code-login-form__username-regen");++ assert.dom("#code-login-username").hasValue("QuietFalcon");+ assert.dom(".code-login-form__continue-to-site").isEnabled();+ });++ test("keeps continue disabled when the regenerated username is unavailable", async function (assert) {+ stubCodeRequest();+ pretender.post("/session/login-code/verify", () =>+ response({+ account_created: true,+ user: { id: 1, username: "jane", avatar_template: "/letter/j.png" },+ can_edit_username: true,+ prefill_username: true,+ })+ );+ // The default pretender handler reports the username "taken" as+ // unavailable with the suggestion "nottaken".+ pretender.get("/u/random-username.json", () =>+ response({ username: "taken" })+ );++ await goToCodeStep();+ await fillIn(".d-otp-input", "123456");++ await click(".code-login-form__username-regen");++ assert.dom("#code-login-username").hasValue("taken");+ assert+ .dom(".code-login-form__username-field .code-login-form__error")+ .hasText(+ i18n("code_login.username_unavailable", { suggestion: "nottaken" })+ );+ assert.dom(".code-login-form__continue-to-site").isDisabled();+ });++ test("hides the regenerate button and makes the user pick when random usernames are disabled", async function (assert) {+ this.siteSettings.enable_random_usernames = false;+ stubCodeRequest();+ pretender.post("/session/login-code/verify", () =>+ response({+ account_created: true,+ user: { id: 1, username: "user1", avatar_template: "/letter/u.png" },+ can_edit_username: true,+ prefill_username: false,+ })+ );++ await goToCodeStep();+ await fillIn(".d-otp-input", "123456");++ assert.dom(".code-login-form__username-regen").doesNotExist();+ assert+ .dom("#code-login-username")+ .hasNoValue("the generic fallback name isn't prefilled");+ assert.dom(".code-login-form__continue-to-site").isDisabled();+ });++ test("shows a fixed username without editing controls when it can't be changed", async function (assert) {+ stubCodeRequest();+ pretender.post("/session/login-code/verify", () =>+ response({+ account_created: true,+ user: { id: 1, username: "jane", avatar_template: "/letter/j.png" },+ can_edit_username: false,+ prefill_username: true,+ })+ );++ await goToCodeStep();+ await fillIn(".d-otp-input", "123456");++ assert.dom(".code-login-form__new-account-username").hasText("jane");+ assert.dom("#code-login-username").doesNotExist();+ assert.dom(".code-login-form__username-regen").doesNotExist();+ assert.dom(".code-login-form__continue-to-site").isEnabled();});test("returns to the email step when using a different email", async function (assert) {diff --git a/lib/random_username_generator.rb b/lib/random_username_generator.rbnew file mode 100644index 00000000000..d4fc6f6e9b5--- /dev/null+++ b/lib/random_username_generator.rb@@ -0,0 +1,34 @@+# frozen_string_literal: true++# Builds random human-friendly usernames (e.g. "QuietFalcon42") for accounts+# created without user input, where no signup data can (or may) be used to+# derive one. The word lists are site settings so communities can tailor them+# to their tone or language.+module RandomUsernameGenerator+ # Returns nil when the site has opted out, or when the configured word lists+ # can't produce a usable name, so callers fall back to their own suggestion.+ def self.generate+ return nil if !SiteSetting.enable_random_usernames++ adjective = pick(SiteSetting.random_username_adjectives_map)+ noun = pick(SiteSetting.random_username_nouns_map)+ return nil if adjective.blank? || noun.blank?++ # A numeric suffix widens the namespace well beyond the word-pair count,+ # so very large sites don't exhaust it.+ candidate = "#{adjective}#{noun}#{rand(10..99)}"+ UserNameSuggester.find_available_username_based_on(+ UserNameSuggester.rightsize_username(candidate),+ )+ end++ # Words are admin-supplied, so skip any that sanitization would rewrite (a+ # non-Latin word once unicode usernames are turned back off, say) rather than+ # letting the replacement character leak into generated names.+ def self.pick(words)+ word = words.shuffle.find { |w| UserNameSuggester.sanitize_username(w) == w }+ # Only the leading letter, so a word like "McFly" keeps its shape.+ word&.sub(/\A./) { |first| first.upcase }+ end+ private_class_method :pick+enddiff --git a/lib/svg_sprite.rb b/lib/svg_sprite.rbindex ede9c82d661..1eae7ddec10 100644--- a/lib/svg_sprite.rb+++ b/lib/svg_sprite.rb@@ -82,6 +82,7 @@ module SvgSpritecubesdesktopdiagram-project+ dicediscourse-amazondiscourse-bell-exclamationdiscourse-bell-onediff --git a/lib/user_name_suggester.rb b/lib/user_name_suggester.rbindex 1b341bfdbbf..c3cebeb40a1 100644--- a/lib/user_name_suggester.rb+++ b/lib/user_name_suggester.rb@@ -102,6 +102,14 @@ module UserNameSuggesterendend+ # Whether a username is the generic fallback (e.g. "user1") rather than a name+ # derived from real signup data. Callers use it to decide whether the name is+ # worth offering back to the user as a suggestion.+ def self.generic_username?(username)+ base = User.normalize_username(username.to_s.sub(/\d+\z/, ""))+ base.present? && base == User.normalize_username(fix_username(nil).to_s.sub(/\d+\z/, ""))+ end+def self.fix_username(name, allow_generic_fallback: true)fixed_username = sanitize_username(name)if fixed_username.blank?diff --git a/lib/validators/random_username_word_list_validator.rb b/lib/validators/random_username_word_list_validator.rbnew file mode 100644index 00000000000..c0703b2dfa1--- /dev/null+++ b/lib/validators/random_username_word_list_validator.rb@@ -0,0 +1,18 @@+# frozen_string_literal: true++class RandomUsernameWordListValidator+ def initialize(opts = {})+ @opts = opts+ end++ # An empty list would leave the generator with nothing to build from, and a+ # word that sanitizes away would silently shrink every generated username.+ def valid_value?(val)+ words = val.to_s.split("|")+ words.any? && words.all? { |word| UserNameSuggester.sanitize_username(word).presence == word }+ end++ def error_message+ I18n.t("site_settings.errors.invalid_random_username_word_list")+ end+enddiff --git a/spec/lib/random_username_generator_spec.rb b/spec/lib/random_username_generator_spec.rbnew file mode 100644index 00000000000..b273affc4f9--- /dev/null+++ b/spec/lib/random_username_generator_spec.rb@@ -0,0 +1,52 @@+# frozen_string_literal: true++RSpec.describe RandomUsernameGenerator do+ describe ".generate" do+ it "returns a valid, available username built from the word lists and a number" do+ username = described_class.generate++ expect(username).to match(/\A[A-Z][a-z]+[A-Z][a-z]+\d{2}\z/)+ expect(UsernameValidator.new(username).valid_format?).to eq(true)+ expect(User.username_available?(username)).to eq(true)+ end++ it "finds an available variant when the generated name is taken" do+ SiteSetting.random_username_adjectives = "quiet"+ SiteSetting.random_username_nouns = "falcon"+ allow(described_class).to receive(:rand).and_return(42)+ Fabricate(:user, username: "QuietFalcon42")++ expect(described_class.generate).to eq("QuietFalcon421")+ end++ it "builds names from the admin-configured word lists" do+ SiteSetting.random_username_adjectives = "brisk"+ SiteSetting.random_username_nouns = "otter"++ expect(described_class.generate).to match(/\ABriskOtter\d{2}\z/)+ end++ it "respects the site's maximum username length" do+ SiteSetting.max_username_length = 10++ expect(described_class.generate.length).to be <= 10+ end++ it "returns nil when the site has opted out" do+ SiteSetting.enable_random_usernames = false++ expect(described_class.generate).to be_nil+ end++ it "returns nil when the words can't survive username sanitization" do+ # Unicode words pass validation while unicode usernames are on, then stop+ # being usable once the site turns them off.+ SiteSetting.unicode_usernames = true+ SiteSetting.random_username_adjectives = "静か"+ SiteSetting.random_username_nouns = "隼"+ SiteSetting.unicode_usernames = false++ expect(described_class.generate).to be_nil+ end+ end+enddiff --git a/spec/lib/user_name_suggester_spec.rb b/spec/lib/user_name_suggester_spec.rbindex 97d2886f8c3..cdfea5d5a09 100644--- a/spec/lib/user_name_suggester_spec.rb+++ b/spec/lib/user_name_suggester_spec.rb@@ -267,4 +267,23 @@ RSpec.describe UserNameSuggester doendendend++ describe ".generic_username?" do+ it "recognizes the generic fallback name and its numbered variants" do+ expect(UserNameSuggester.generic_username?("user")).to eq(true)+ expect(UserNameSuggester.generic_username?("user1")).to eq(true)+ expect(UserNameSuggester.generic_username?("User42")).to eq(true)+ end++ it "does not flag names derived from real signup data" do+ expect(UserNameSuggester.generic_username?("jane")).to eq(false)+ expect(UserNameSuggester.generic_username?("newuser")).to eq(false)+ expect(UserNameSuggester.generic_username?("QuietFalcon42")).to eq(false)+ end++ it "is blank-safe" do+ expect(UserNameSuggester.generic_username?(nil)).to eq(false)+ expect(UserNameSuggester.generic_username?("")).to eq(false)+ end+ endenddiff --git a/spec/lib/validators/random_username_word_list_validator_spec.rb b/spec/lib/validators/random_username_word_list_validator_spec.rbnew file mode 100644index 00000000000..7c17f117f5f--- /dev/null+++ b/spec/lib/validators/random_username_word_list_validator_spec.rb@@ -0,0 +1,33 @@+# frozen_string_literal: true++RSpec.describe RandomUsernameWordListValidator do+ subject(:validator) { described_class.new }++ it "accepts a list of username-safe words" do+ expect(validator.valid_value?("quiet|brisk|golden")).to eq(true)+ end++ it "rejects an empty list" do+ expect(validator.valid_value?("")).to eq(false)+ end++ it "rejects words that would be rewritten by username sanitization" do+ expect(validator.valid_value?("quiet falcon")).to eq(false)+ expect(validator.valid_value?("quiet|-falcon")).to eq(false)+ end++ it "is wired up to the word list settings" do+ expect { SiteSetting.random_username_adjectives = "quiet falcon" }.to raise_error(+ Discourse::InvalidParameters,+ )+ expect { SiteSetting.random_username_nouns = "" }.to raise_error(Discourse::InvalidParameters)+ end++ it "rejects non-Latin words unless unicode usernames are enabled" do+ expect(validator.valid_value?("静か")).to eq(false)++ SiteSetting.unicode_usernames = true++ expect(validator.valid_value?("静か")).to eq(true)+ end+enddiff --git a/spec/requests/session_controller_spec.rb b/spec/requests/session_controller_spec.rbindex 25d4ea6698d..ba2ca56a660 100644--- a/spec/requests/session_controller_spec.rb+++ b/spec/requests/session_controller_spec.rb@@ -859,9 +859,6 @@ RSpec.describe SessionController do# UserSerializer. (Its value depends on automatic group membership,# added on commit, so only assert the flag is present here.)expect(body).to have_key("can_upload_avatar")- # Off by default, so the client makes the user pick rather than- # prefilling a generic username.- expect(body["prefill_username"]).to eq(false)endit "defers a pending DiscourseConnect provider handoff to the account-ready step" do@@ -876,14 +873,83 @@ RSpec.describe SessionController doexpect(cookies[:sso_payload]).to be_blankend- it "flags the username for prefill when email-based suggestions are on" do- SiteSetting.use_email_for_username_and_name_suggestions = true+ it "does not derive the username from the email when email-based suggestions are off" do+ SiteSetting.use_email_for_username_and_name_suggestions = false++ post "/session/login-code/verify.json", params: { email: "[email protected]", code: }++ new_user = User.find_by_email("[email protected]")+ expect(new_user.username).not_to include("newuser")+ expect(new_user.username).to match(/\A[A-Z][a-z]+[A-Z][a-z]+\d+\z/)+ end++ it "falls back to the generic username when random usernames are disabled" do+ SiteSetting.use_email_for_username_and_name_suggestions = false+ SiteSetting.enable_random_usernames = false++ post "/session/login-code/verify.json", params: { email: "[email protected]", code: }++ expect(User.find_by_email("[email protected]").username).to match(/\Auser\d*\z/)+ # A generic placeholder isn't worth prefilling, so the client makes the+ # user pick a username instead.+ expect(response.parsed_body["prefill_username"]).to eq(false)+ end++ it "flags a randomly generated username for prefill" do+ SiteSetting.use_email_for_username_and_name_suggestions = falsepost "/session/login-code/verify.json", params: { email: "[email protected]", code: }expect(response.parsed_body["prefill_username"]).to eq(true)end+ it "does not flag the fallback for prefill when generation is on but yields nothing" do+ SiteSetting.use_email_for_username_and_name_suggestions = false+ # Unicode words pass validation while unicode usernames are on, then+ # stop being usable once the site turns them off.+ SiteSetting.unicode_usernames = true+ SiteSetting.random_username_adjectives = "静か"+ SiteSetting.random_username_nouns = "隼"+ SiteSetting.unicode_usernames = false++ post "/session/login-code/verify.json", params: { email: "[email protected]", code: }++ expect(User.find_by_email("[email protected]").username).to match(/\Auser\d*\z/)+ expect(response.parsed_body["prefill_username"]).to eq(false)+ end++ it "derives the username from the email when email-based suggestions are on" do+ SiteSetting.use_email_for_username_and_name_suggestions = true++ post "/session/login-code/verify.json", params: { email: "[email protected]", code: }++ expect(User.find_by_email("[email protected]").username).to eq("newuser")+ end++ it "appends a numeric suffix when the email-derived name is taken" do+ SiteSetting.use_email_for_username_and_name_suggestions = true+ Fabricate(:user, username: "newuser")++ post "/session/login-code/verify.json", params: { email: "[email protected]", code: }++ expect(User.find_by_email("[email protected]").username).to eq("newuser1")+ end++ context "when the email can't produce a username suggestion" do+ let(:login_code) { EmailLoginCode.generate!(email: "[email protected]") }++ it "assigns a random username instead of the generic fallback" do+ SiteSetting.use_email_for_username_and_name_suggestions = true++ post "/session/login-code/verify.json", params: { email: "[email protected]", code: }++ expect(response.parsed_body["account_created"]).to eq(true)+ expect(User.find_by_email("[email protected]").username).to match(+ /\A[A-Z][a-z]+[A-Z][a-z]+\d+\z/,+ )+ end+ end+it "renders an error when registrations are disabled" doSiteSetting.allow_new_registrations = falsediff --git a/spec/requests/users_controller_spec.rb b/spec/requests/users_controller_spec.rbindex 809f1144772..a23674fe679 100644--- a/spec/requests/users_controller_spec.rb+++ b/spec/requests/users_controller_spec.rb@@ -2302,6 +2302,48 @@ RSpec.describe UsersController doendend+ describe "#generate_random_username" do+ it "returns a generated username" do+ get "/u/random-username.json"++ expect(response.status).to eq(200)+ expect(response.parsed_body["username"]).to match(/\A[A-Z][a-z]+[A-Z][a-z]+\d+\z/)+ end++ it "rate limits requests per IP" do+ RateLimiter.enable++ 20.times { get "/u/random-username.json" }+ get "/u/random-username.json"++ expect(response.status).to eq(429)+ end++ it "404s when random usernames are disabled" do+ SiteSetting.enable_random_usernames = false++ get "/u/random-username.json"++ expect(response.status).to eq(404)+ end++ it "reports an error when the word lists can no longer produce a username" do+ # Unicode words pass validation while unicode usernames are on, then stop+ # being usable once the site turns them off.+ SiteSetting.unicode_usernames = true+ SiteSetting.random_username_adjectives = "静か"+ SiteSetting.random_username_nouns = "隼"+ SiteSetting.unicode_usernames = false++ get "/u/random-username.json"++ expect(response.status).to eq(422)+ expect(response.parsed_body["errors"]).to contain_exactly(+ I18n.t("random_username.unavailable"),+ )+ end+ end+describe "#check_email" doit "returns success if hide_email_address_taken is true" doSiteSetting.hide_email_address_taken = truediff --git a/spec/system/code_signup_spec.rb b/spec/system/code_signup_spec.rbindex 7ba40098ab8..05b591e6be8 100644--- a/spec/system/code_signup_spec.rb+++ b/spec/system/code_signup_spec.rb@@ -45,8 +45,15 @@ describe "Sign up via email code" doexpect(page).to have_css(".code-login-form__complete-step")screenshot_marker(label: "code-signup-complete-step")- # A username must be picked before the account can be used.- expect(page).to have_css(".code-login-form__continue-to-site[disabled]")+ # A random username is assigned and prefilled, so the account is usable+ # as-is; the user can roll a new suggestion or type their own.+ generated = find("#code-login-username").value+ expect(generated).to match(/\A[A-Z][a-z]+[A-Z][a-z]+\d+\z/)+ expect(page).to have_no_css(".code-login-form__continue-to-site[disabled]")++ find(".code-login-form__username-regen").click+ expect(page).to have_no_field("code-login-username", with: generated)+pick_username("new-person")find(".code-login-form__continue-to-site").click@@ -112,6 +119,28 @@ describe "Sign up via email code" doexpect(find("#code-login-username").value).to eq("jane")end+ it "makes the user pick a username when random usernames are disabled" do+ SiteSetting.use_email_for_username_and_name_suggestions = false+ SiteSetting.enable_random_usernames = false++ visit("/signup")+ submit_email("[email protected]")+ fill_code(latest_emailed_code("[email protected]"))++ expect(page).to have_css(".code-login-form__complete-step")+ expect(page).to have_no_css(".code-login-form__username-regen")+ # The account carries a generic placeholder name, so it isn't offered up+ # for the user to accept as-is.+ expect(find("#code-login-username").value).to eq("")+ expect(page).to have_css(".code-login-form__continue-to-site[disabled]")++ pick_username("no-random")+ find(".code-login-form__continue-to-site").click++ expect(page).to have_css(".header-dropdown-toggle.current-user")+ expect(User.find_by_email("[email protected]").username).to eq("no-random")+ end+it "keeps the generated username when usernames can't be changed" doSiteSetting.username_change_period = 0