A platform for community discussion. Free, open, simple.
FIX: Separate email-code signup details from completion (#43845)
Keegan George2d184776f7d8
diff --git a/app/assets/stylesheets/common/base/user.scss b/app/assets/stylesheets/common/base/user.scssindex ffb86086bc9..20ac5772934 100644--- a/app/assets/stylesheets/common/base/user.scss+++ b/app/assets/stylesheets/common/base/user.scss@@ -565,6 +565,23 @@.avatar-selector {--label-max-width: 300px;+ &__placeholder {+ display: inline-flex;+ align-items: center;+ justify-content: center;+ flex: 0 0 45px;+ height: 45px;+ margin-inline-end: 0.75em;+ border-radius: 50%;+ background: var(--primary-low);+ color: var(--primary-medium);+ }++ .selectable-avatar[aria-current="true"] {+ outline: 2px solid var(--tertiary);+ outline-offset: 2px;+ }+.avatar-choice {display: grid;grid-template-columns: 2em 1fr auto;diff --git a/app/assets/stylesheets/common/login/code-login-form.scss b/app/assets/stylesheets/common/login/code-login-form.scssindex bdaced03143..d0329524352 100644--- a/app/assets/stylesheets/common/login/code-login-form.scss+++ b/app/assets/stylesheets/common/login/code-login-form.scss@@ -51,7 +51,7 @@&__second-factor-step,&__account-details-step,&__user-fields-step,- &__complete-step,+ &__signup-details-step,&__pending-approval-step {display: flex;flex-direction: column;@@ -153,6 +153,22 @@}}+ &__avatar-placeholder {+ display: flex;+ align-items: center;+ justify-content: center;+ width: 144px;+ height: 144px;+ border-radius: 50%;+ background: var(--primary-low);+ color: var(--primary-medium);++ .d-icon {+ width: 50%;+ height: 50%;+ }+ }+&__avatar-edit {position: absolute;right: 0;diff --git a/app/controllers/session_controller.rb b/app/controllers/session_controller.rbindex c728b64cde4..b8e6896dd78 100644--- a/app/controllers/session_controller.rb+++ b/app/controllers/session_controller.rb@@ -39,6 +39,9 @@ class SessionController < ApplicationControllerACTIVATE_USER_KEY = "activate_user"FORGOT_PASSWORD_EMAIL_LIMIT_PER_DAY = 6LOGIN_CODE_SIGNUP_KEY_PREFIX = "login-code-signup-"+ GENERATED_USERNAME_SIGNUP_KEY_PREFIX = "login-code-generated-username-"+ GENERATED_USERNAME_SIGNUP_INDEX_KEY = "login-code-generated-username-ids"+ GENERATED_USERNAME_ATTEMPTS = 5def csrfrender json: { csrf: form_authenticity_token }@@ -972,8 +975,22 @@ class SessionController < ApplicationControllerendend+ login_code = EmailLoginCode.login.active.for_email(params[:email].to_s.strip).first+ generated_username =+ generated_username_signup?(+ login_code,+ params[:email],+ params[:username],+ params[:signup_context],+ )EmailLoginCode::Redeem.call(- service_params.deep_merge(ip_address: request.remote_ip),+ service_params.deep_merge(+ ip_address: request.remote_ip,+ options: {+ generated_username:,+ generated_username_login_code_id: login_code&.id,+ },+ ),) do |result|on_success do |user:, existing_user:|login_with_login_code(user, created_account: existing_user.nil?)@@ -985,7 +1002,15 @@ class SessionController < ApplicationControllerrender json: login_code_registration_ip_limit_errorendon_failed_policy(:username_allowed) do- render json: { error: I18n.t("login.reserved_username") }+ if generated_username+ render_signup_username_required(+ result[:params].email,+ login_code: result[:login_code],+ signup_context: params[:signup_context],+ )+ else+ render json: { username_errors: [I18n.t("login.reserved_username")] }+ endendon_failed_policy(:required_fields_provided) dorender json: { error: I18n.t("login.missing_user_field") }@@ -993,7 +1018,24 @@ class SessionController < ApplicationControlleron_failed_policy(:required_full_name_provided) dorender json: { error: I18n.t("login.missing_full_name") }end- on_model_errors(:user) { |user| render json: login_code_account_error(user) }+ on_failed_policy(:required_username_provided) do+ render_signup_username_required(+ result[:params].email,+ login_code: result[:login_code],+ signup_context: params[:signup_context],+ )+ end+ on_model_errors(:user) do |user|+ if generated_username && user.errors[:username].present?+ render_signup_username_required(+ result[:params].email,+ login_code: result[:login_code],+ signup_context: params[:signup_context],+ )+ else+ render json: login_code_account_error(user)+ end+ endon_failed_contract do |contract|render json: failed_json.merge(errors: contract.errors.full_messages), status: :bad_requestend@@ -1140,29 +1182,14 @@ class SessionController < ApplicationControllerelsif payload = login_error_check(user)render json: payloadelsif created_account- # Same tail as `login`, except the response tells the client a new- # account was created so it can show the "account ready" step before- # following the usual post-login redirect.session.delete(ACTIVATE_USER_KEY)user.update_timezone_if_missing(params[:timezone])log_on_user(user, replay_anonymous_action: true)+ complete_login_code_authentication(user)render json:success_json.merge(account_created: true,user: serialize_data(user, UserSerializer, root: false),- # 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.- can_edit_username: user.guardian.can_edit_username?(user),- # `can_upload_avatar` lives on CurrentUserSerializer, but the- # account-ready step builds the user from UserSerializer, so- # the avatar picker needs the upload permission passed through.can_upload_avatar:user.in_any_groups?(SiteSetting.uploaded_avatars_allowed_groups_map),# A pending provider handoff takes precedence, since an external@@ -1172,7 +1199,9 @@ class SessionController < ApplicationControllerredirect_url: deferred_sso_provider_url || redirect_url,)else- login(user, redirect_url:)+ response = login(user, redirect_url:)+ complete_login_code_authentication(user)+ responseendend@@ -1235,9 +1264,21 @@ class SessionController < ApplicationControlleron_failed_policy(:required_full_name_provided) dorender json: { error: I18n.t("login.missing_full_name") }end+ on_failed_policy(:required_username_provided) do+ render_signup_username_required(+ result[:params].email,+ invite: result[:invite],+ login_code: result[:login_code],+ )+ end+ on_failed_policy(:username_allowed) do+ render json: { username_errors: [I18n.t("login.reserved_username")] }+ endon_model_errors(:user) { |user| render json: login_code_account_error(user) }on_model_not_found(:user) do |model_result|- if model_result.exception.is_a?(Invite::UserExists)+ if model_result.exception.is_a?(ActiveRecord::RecordInvalid)+ render json: login_code_account_error(model_result.exception.record)+ elsif model_result.exception.is_a?(Invite::UserExists)render json: { error: model_result.exception.message }elserender json: invalid_login_code@@ -1255,9 +1296,118 @@ class SessionController < ApplicationControllertopic && user.guardian.can_see?(topic) ? path(topic.relative_url) : path("/")end+ def render_signup_username_required(email, invite: nil, login_code: nil, signup_context: nil)+ generated_username =+ invite.nil? && login_code.present? &&+ email_login_code_username_mode(email, signup_context) == :generated+ username =+ if generated_username+ generated_signup_username(email)+ else+ UserNameSuggester.suggest(email, allow_generic_fallback: false) ||+ RandomUsernameGenerator.generate+ end+ username = nil if UserNameSuggester.generic_username?(username)+ generated_username = false if username.blank?++ if generated_username+ store_generated_username_signup(login_code, email, username, signup_context)+ end++ trust_level = invite ? SiteSetting.default_invitee_trust_level : SiteSetting.default_trust_level+ group_ids =+ Group.desired_trust_level_groups(trust_level) + [Group::AUTO_GROUPS[:logged_in_users]]+ if !SiteSetting.granular_anonymous_and_logged_in_groups_permissions+ group_ids << Group::AUTO_GROUPS[:everyone]+ end+ group_ids.concat(invite.groups.pluck(:id)) if invite++ render json: {+ username_required: true,+ username: username,+ generated_username: generated_username,+ trust_level: trust_level,+ avatar_template: username && User.default_template(username),+ can_upload_avatar:+ group_ids.intersect?(SiteSetting.uploaded_avatars_allowed_groups_map),+ }+ end++ def generated_username_signup?(login_code, email, username, signup_context)+ return false if login_code.blank? || username.blank?++ proof = server_session[generated_username_signup_key(login_code.id)]+ proof_matches =+ proof.is_a?(Hash) && proof[:login_code_id] == login_code.id &&+ proof[:email] == email.to_s.strip.downcase && proof[:username] == username.to_s &&+ proof[:signup_context] == signup_context.to_s+ proof_matches && email_login_code_username_mode(email, signup_context) == :generated+ end++ def email_login_code_username_mode(email, signup_context)+ DiscoursePluginRegistry.apply_modifier(+ :email_login_code_username_mode,+ :required,+ email,+ server_session,+ signup_context,+ cookies[:destination_url],+ )+ end++ def generated_signup_username(email)+ GENERATED_USERNAME_ATTEMPTS.times do |attempt|+ username =+ if attempt.zero?+ UserNameSuggester.suggest(email, allow_generic_fallback: false)+ else+ RandomUsernameGenerator.generate(allow_when_disabled: true)+ end+ return username if valid_generated_signup_username?(username, email)+ end++ nil+ end++ def valid_generated_signup_username?(username, email)+ username.present? && UsernameValidator.new(username).valid_format? &&+ !UsernameValidator.clashing_with_existing_route?(username) &&+ User.username_available?(username, email)+ end++ def store_generated_username_signup(login_code, email, username, signup_context)+ expires_in = (login_code.expires_at - Time.zone.now).ceil+ return if expires_in <= 0++ server_session.set(+ generated_username_signup_key(login_code.id),+ {+ login_code_id: login_code.id,+ email: email.to_s.strip.downcase,+ username: username,+ signup_context: signup_context.to_s,+ },+ expires: expires_in,+ )+ ids = Array(server_session[GENERATED_USERNAME_SIGNUP_INDEX_KEY]) | [login_code.id]+ server_session.set(GENERATED_USERNAME_SIGNUP_INDEX_KEY, ids, expires: ServerSession.expiry)+ end++ def generated_username_signup_key(login_code_id)+ "#{GENERATED_USERNAME_SIGNUP_KEY_PREFIX}#{login_code_id}"+ end++ def complete_login_code_authentication(user)+ Array(server_session[GENERATED_USERNAME_SIGNUP_INDEX_KEY]).each do |login_code_id|+ server_session.delete(generated_username_signup_key(login_code_id))+ end+ server_session.delete(GENERATED_USERNAME_SIGNUP_INDEX_KEY)+ DiscourseEvent.trigger(:email_login_code_authenticated, user, server_session)+ end+# A pending provider handoff would redirect as soon as the session exists,- # skipping the account-ready step, so the URL is handed to the client to- # follow once signup is finished (as account activation does). Consumes the+ # skipping the pending avatar upload, so the client follows the URL once+ # signup is finished (as account activation does). Consumes the# payload so a later login isn't sent through a handoff it didn't start.def deferred_sso_provider_urlreturn if !SiteSetting.enable_discourse_connect_provider@@ -1289,6 +1439,10 @@ class SessionController < ApplicationControllerenddef login_code_account_error(user)+ if user.errors[:username].present?+ return { username_errors: user.errors.full_messages_for(:username) }+ end+ip_error =user.errors.find do |error|error.attribute == :ip_address &&diff --git a/app/controllers/users_controller.rb b/app/controllers/users_controller.rbindex 696b497cbf8..271a651e8d2 100644--- a/app/controllers/users_controller.rb+++ b/app/controllers/users_controller.rb@@ -610,8 +610,10 @@ class UsersController < ApplicationControllerendend- def render_available_true- render(json: { available: true })+ def render_available_true(username = nil)+ result = { available: true }+ result[:avatar_template] = User.default_template(username) if username+ render json: resultenddef changing_case_of_own_username(target_user, username)@@ -645,11 +647,13 @@ class UsersController < ApplicationControllertarget_user = user_from_params_or_current_user# The special case where someone is changing the case of their own username- return render_available_true if changing_case_of_own_username(target_user, username)+ return render_available_true(username) if changing_case_of_own_username(target_user, username)checker = UsernameCheckerService.new(allow_reserved_username: current_user&.admin?)email = params[:email] || target_user.try(:email)- render json: checker.check_username(username, email)+ result = checker.check_username(username, email)+ result[:avatar_template] = User.default_template(username) if result[:available]+ render json: resultenddef generate_random_username@@ -708,7 +712,12 @@ class UsersController < ApplicationControllerenddef user_from_params_or_current_user- params[:for_user_id] ? User.find(params[:for_user_id]) : current_user+ return current_user if !params[:for_user_id]+ raise Discourse::InvalidAccess if !current_user++ user = User.find(params[:for_user_id])+ guardian.ensure_can_edit_username!(user)+ userenddef creatediff --git a/app/models/invite_redeemer.rb b/app/models/invite_redeemer.rbindex aede3b95b6c..d30e7de02e9 100644--- a/app/models/invite_redeemer.rb+++ b/app/models/invite_redeemer.rb@@ -99,8 +99,10 @@ class InviteRedeemer)raise Discourse::SiteArchived if SiteSetting.site_archived- if username && UsernameValidator.new(username).valid_format? &&- User.username_available?(username, email)+ if email_verified && username.present?+ available_username = username+ elsif username && UsernameValidator.new(username).valid_format? &&+ User.username_available?(username, email)available_username = usernameelsif email_verifiedavailable_username =diff --git a/app/services/email_login_code/redeem.rb b/app/services/email_login_code/redeem.rbindex b7afb21c430..3810ab9abef 100644--- a/app/services/email_login_code/redeem.rb+++ b/app/services/email_login_code/redeem.rb@@ -31,6 +31,11 @@ class EmailLoginCode::Redeemvalidates :password, length: { maximum: User.max_password_length }, allow_nil: trueend+ options do+ attribute :generated_username, :boolean, default: false+ attribute :generated_username_login_code_id, :integer+ end+model :login_codepolicy :code_matchesmodel :existing_user, :fetch_existing_user, optional: true@@ -38,10 +43,10 @@ class EmailLoginCode::Redeempolicy :email_available_for_new_accountpolicy :can_register_new_accountpolicy :can_register_from_ip- policy :required_username_providedpolicy :username_allowedpolicy :required_fields_providedpolicy :required_full_name_provided+ policy :required_username_providedlock(:email) dotransaction do@@ -98,10 +103,6 @@ class EmailLoginCode::Redeemexisting_user.present? || !SpamHandler.should_prevent_registration_from_ip?(ip_address)end- def required_username_provided(existing_user:, params:)- existing_user.present? || !params.username_required || params.username.present?- end-def username_allowed(existing_user:, params:)return true if existing_user.present? || params.username.blank?@@ -132,13 +133,19 @@ class EmailLoginCode::Redeem!Site.full_name_required_for_signup || params.name.present?end+ def required_username_provided(existing_user:, params:)+ existing_user.present? || params.username.present?+ end+def consume_code(login_code:)# consume! is atomic; if it lost a race with a concurrent redemption the# code is already spent, so this redemption must not log anyone in.fail!("code already redeemed") unless login_code.consume!end- def ensure_user(existing_user:, params:, ip_address:)+ def ensure_user(existing_user:, login_code:, params:, ip_address:, options:)+ generated_username =+ options.generated_username && options.generated_username_login_code_id == login_code.idexisting_user ||User::Action::CreateFromVerifiedEmail.call(email: params.email,@@ -147,6 +154,7 @@ class EmailLoginCode::Redeemname: params.name,password: params.password,username: params.username,+ generated_username: generated_username,)enddiff --git a/app/services/invite/redeem_with_email_code.rb b/app/services/invite/redeem_with_email_code.rbindex adc94b39837..130a5959719 100644--- a/app/services/invite/redeem_with_email_code.rb+++ b/app/services/invite/redeem_with_email_code.rb@@ -7,6 +7,7 @@ class Invite::RedeemWithEmailCodeattribute :invite_key, :stringattribute :user_fieldsattribute :name, :string+ attribute :username, :stringbefore_validation doself.invite_key = invite_key.to_s.strip@@ -17,6 +18,7 @@ class Invite::RedeemWithEmailCode{}endself.name = name.to_s.strip.presence+ self.username = username.to_s.strip.presenceendvalidates :invite_key, presence: true@@ -32,6 +34,8 @@ class Invite::RedeemWithEmailCodepolicy :can_register_new_accountpolicy :required_fields_providedpolicy :required_full_name_provided+ policy :required_username_provided+ policy :username_allowedtry(ActiveRecord::RecordInvalid,@@ -110,6 +114,17 @@ class Invite::RedeemWithEmailCode!Site.full_name_required_for_signup || params.name.present?end+ def required_username_provided(existing_user:, params:)+ existing_user.present? || params.username.present?+ end++ def username_allowed(existing_user:, params:)+ return true if existing_user.present?++ !User.reserved_username?(params.username) &&+ !UsernameValidator.clashing_with_existing_route?(params.username)+ end+def consume_code(login_code:)fail!("code already redeemed") unless login_code.consume!end@@ -122,6 +137,7 @@ class Invite::RedeemWithEmailCode{email: params.email,name: params.name,+ username: params.username,user_custom_fields: params.user_fields,ip_address: ip_address,email_verified: true,diff --git a/app/services/user/action/create_from_verified_email.rb b/app/services/user/action/create_from_verified_email.rbindex c4644e37369..04b98390bc3 100644--- a/app/services/user/action/create_from_verified_email.rb+++ b/app/services/user/action/create_from_verified_email.rb@@ -2,31 +2,23 @@class User::Action::CreateFromVerifiedEmail < Service::ActionBaseoption :email+ option :username+ option :generated_username, default: -> { false }option :ip_address, optional: trueoption :user_fields, optional: trueoption :name, optional: trueoption :password, optional: true- option :username, optional: truedef callraise Discourse::SiteArchived if SiteSetting.site_archived- # 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.- suggested_username =- UserNameSuggester.suggest(email, allow_generic_fallback: false) ||- RandomUsernameGenerator.generate || UserNameSuggester.suggest(email)-user = User.where(staged: true).with_email(email).firstuser&.unstage!user ||= User.newuser.attributes = {email: email,- username: username.presence || suggested_username,- # The generated username is a placeholder, so it must never become the- # full name. A staged account's existing name is real and survives.+ username: username,name: name.presence || user.name,active: false,locale: I18n.locale,diff --git a/config/locales/client.en.yml b/config/locales/client.en.ymlindex fb428dd6f13..8b239a85e24 100644--- a/config/locales/client.en.yml+++ b/config/locales/client.en.yml@@ -3152,8 +3152,7 @@ en:signup_instructions: "Enter your email address to join this community. We'll send you a code to confirm it and you'll be on your way!"user_fields_title: "Almost done"user_fields_instructions: "Just a few more details to finish creating your account."- account_ready_title: "Your account is ready! 🎉"- account_ready_edit: "Pick your username and avatar"+ signup_details_title: "Choose your username and avatar"account_ready_continue: "Continue"account_details_title: "Finish creating your account"account_details_instructions: "Choose how you’ll appear to the community before submitting your account for approval."diff --git a/config/site_settings.yml b/config/site_settings.ymlindex 3974b7eb079..0bad3e4e232 100644--- a/config/site_settings.yml+++ b/config/site_settings.yml@@ -696,7 +696,7 @@ login:- everyoneenable_random_usernames:client: true- default: true+ default: falsearea: "login"depends_on:- enable_local_logins_via_codediff --git a/frontend/discourse/app/components/code-login-form.gjs b/frontend/discourse/app/components/code-login-form.gjsindex 23e45ceccd2..fe59ea389d3 100644--- a/frontend/discourse/app/components/code-login-form.gjs+++ b/frontend/discourse/app/components/code-login-form.gjs@@ -15,18 +15,18 @@ import UserField from "discourse/components/user-field";import WelcomeHeader from "discourse/components/welcome-header";import lazyHash from "discourse/helpers/lazy-hash";import valueEntered from "discourse/helpers/value-entered";-import { ajax } from "discourse/lib/ajax";+import { ajax, updateCsrfToken } from "discourse/lib/ajax";import { isReadOnlyError, popupAjaxError } from "discourse/lib/ajax-error";import cookie, { removeCookie } from "discourse/lib/cookie";import discourseDebounce from "discourse/lib/debounce";import escape from "discourse/lib/escape";-import getURL from "discourse/lib/get-url";import discourseLater from "discourse/lib/later";import PasswordValidationHelper from "discourse/lib/password-validation-helper";import {applyBehaviorTransformer,applyValueTransformer,} from "discourse/lib/transformer";+import { allowsImages } from "discourse/lib/uploads";import DiscourseURL from "discourse/lib/url";import UserFieldsValidationHelper from "discourse/lib/user-fields-validation-helper";import { emailValid } from "discourse/lib/utilities";@@ -59,8 +59,9 @@ export default class CodeLoginForm extends Component {@tracked notice;@tracked resendCooldown = 0;@tracked otpGeneration = 0;- @tracked newAccount;- @tracked accountUser;+ @tracked canUploadAvatar = false;+ @tracked pendingAvatar;+ @tracked pendingAvatarUrl;@tracked name = "";@tracked accountPassword = "";@tracked showOptionalPassword = false;@@ -73,10 +74,9 @@ export default class CodeLoginForm extends Component {@tracked usernameAvailable = false;@tracked usernameChecking = false;@tracked usernameError;- @tracked usernameEditable = true;+ @tracked generatedUsername = false;@tracked regenerating = false;@tracked avatarTemplate;- @tracked avatarDetailsLoaded = false;@tracked secondFactorMethod = SECOND_FACTOR_METHODS.TOTP;@tracked secondFactorToken;@tracked securityKeyCredential;@@ -95,8 +95,11 @@ export default class CodeLoginForm extends Component {});#cooldownTimer;#draftEmail;- #postSignupRedirectUrl;+ #collectedUserFields = false;+ #generatedUsernameAutoSubmits = 0;#usernameCheckSeq = 0;+ #usernameDebounce;+ @tracked _signupTrustLevel = 0;@tracked _step;constructor() {@@ -114,6 +117,9 @@ export default class CodeLoginForm extends Component {willDestroy() {super.willDestroy(...arguments);cancel(this.#cooldownTimer);+ cancel(this.#usernameDebounce);+ this.#usernameCheckSeq++;+ this.#clearPendingAvatarUrl();}// Tracked-backed so the parent can react to step transitions via onStepChange.@@ -164,8 +170,8 @@ export default class CodeLoginForm extends Component {return this.step === "user-fields";}- get isCompleteStep() {- return this.step === "complete";+ get isSignupDetailsStep() {+ return this.step === "signup-details";}get isAccountDetailsStep() {@@ -176,6 +182,14 @@ export default class CodeLoginForm extends Component {return this.step === "pending-approval";}+ get signupDetailsTitle() {+ return i18n(+ this.generatedUsername+ ? "code_login.account_details_title"+ : "code_login.signup_details_title"+ );+ }+get heading() {if (this.isAccountDetailsStep) {return {@@ -206,12 +220,9 @@ export default class CodeLoginForm extends Component {title: i18n("code_login.user_fields_title"),subtitle: i18n("code_login.user_fields_instructions"),};- case "complete":+ case "signup-details":return {- title: i18n("code_login.account_ready_title"),- subtitle: this.usernameEditable- ? i18n("code_login.account_ready_edit")- : null,+ title: this.signupDetailsTitle,};case "second-factor":return { title: i18n("login.second_factor_title"), subtitle: null };@@ -224,13 +235,17 @@ export default class CodeLoginForm extends Component {if (this.verifying || this.passwordValidation.failed) {return true;}- // When the username can't be changed there's nothing to validate.- if (!this.usernameEditable) {- return false;- }return !this.usernameAvailable || this.usernameChecking;}+ get previewAvatarTemplate() {+ return (+ this.pendingAvatarUrl ||+ this.pendingAvatar?.url ||+ (this.username.trim() ? this.avatarTemplate : null)+ );+ }+get userFields() {return this.userFieldsValidationHelper.userFields;}@@ -348,6 +363,14 @@ export default class CodeLoginForm extends Component {this.code = "";this.codeError = null;this.notice = null;+ this.username = "";+ this.usernameAvailable = false;+ this.usernameError = null;+ this.generatedUsername = false;+ this.#generatedUsernameAutoSubmits = 0;+ this.avatarTemplate = null;+ this.pendingAvatar = null;+ this.#clearPendingAvatarUrl();this.otpGeneration++;this.#clearSignupContinuation();this.step = "email";@@ -392,7 +415,9 @@ export default class CodeLoginForm extends Component {if (!this.isPasswordReset &&- (this.isUserFieldsStep || this.#prefillUserFields())+ (this.#collectedUserFields ||+ this.isUserFieldsStep ||+ this.#prefillUserFields())) {data.user_fields = {};this.userFields.forEach((f) => (data.user_fields[f.field.id] = f.value));@@ -401,6 +426,13 @@ export default class CodeLoginForm extends Component {}}+ if (this.isSignupDetailsStep) {+ data.username = this.username.trim();+ }+ if (this.isSignup && this.args.signupContext) {+ data.signup_context = this.args.signupContext;+ }+try {const endpoint = this.isPasswordReset? "/session/password-reset-code/verify"@@ -411,10 +443,31 @@ export default class CodeLoginForm extends Component {data,});const result =- this.isSignup && this.isCodeStep+ this.isSignupDetailsStep && !this.isInvite? await applyBehaviorTransformer("create-account", verify): await verify();+ if (this.isDestroying) {+ return;+ }++ if (result?.success === false && result.message) {+ this.codeError = result.message;+ return;+ }++ if (result?.username_required) {+ this.setupSignupDetails(result);+ this.step = "signup-details";+ return;+ }++ if (result?.username_errors) {+ this.usernameError = result.username_errors.join(" ");+ this.usernameAvailable = false;+ return;+ }+if ((result?.user_fields_required || result?.name_required) &&!this.isUserFieldsStep@@ -441,7 +494,7 @@ export default class CodeLoginForm extends Component {if (this.isSecondFactorStep) {this.securityKeyCredential = null;this.codeError = result.error;- } else if (this.isUserFieldsStep) {+ } else if (this.isUserFieldsStep || this.isSignupDetailsStep) {this.codeError = result.error;} else {this.codeError = result.error;@@ -469,20 +522,28 @@ export default class CodeLoginForm extends Component {}if (result?.account_created) {- this.setupNewAccount(result);- this.step = "complete";+ await this.#savePendingAvatar(result);+ if (this.isDestroying) {+ return;+ }+ this.redirectAfterLogin(result.redirect_url);return;}this.redirectAfterLogin(result?.redirect_url);} catch (e) {+ if (this.isDestroying) {+ return;+ }if (isReadOnlyError(e)) {this.codeError = this.login.readOnlyLoginMessage;} else {popupAjaxError(e);}} finally {- this.verifying = false;+ if (!this.isDestroying) {+ this.verifying = false;+ }}}@@ -520,28 +581,21 @@ export default class CodeLoginForm extends Component {) {return;}+ this.#collectedUserFields = true;return this.verifyCode();}- // The account is logged in server-side but the app is still in its anonymous- // boot state, so username/avatar are edited through authenticated requests on- // a User model built from the verify response rather than the current user.- setupNewAccount(result) {- const user = result.user;- this.newAccount = user;- // can_upload_avatar isn't in UserSerializer, so carry it from the response.- this.accountUser = User.create({- ...user,- can_upload_avatar: result.can_upload_avatar,- });- this.usernameEditable = result.can_edit_username;- this.username = result.prefill_username ? user.username : "";- this.avatarTemplate = user.avatar_template;- // Set when the server held back a DiscourseConnect provider handoff so this- // step could run; continuing resumes it.- this.#postSignupRedirectUrl = result.redirect_url;-- if (this.usernameEditable && this.username) {+ setupSignupDetails(result) {+ this.username = result.username || "";+ this.generatedUsername = !!result.generated_username;+ this.avatarTemplate = result.avatar_template;+ this._signupTrustLevel = result.trust_level ?? 0;+ this.canUploadAvatar =+ result.can_upload_avatar && allowsImages(false, this.siteSettings);+ if (this.generatedUsername) {+ this.usernameAvailable = !!this.username;+ schedule("afterRender", () => this.#autoCreateGeneratedAccount());+ } else if (this.username) {this.checkUsernameAvailability();}}@@ -577,9 +631,13 @@ export default class CodeLoginForm extends Component {this.usernameAvailable = false;await this.checkUsernameAvailability();} catch (e) {- popupAjaxError(e);+ if (!this.isDestroying) {+ popupAjaxError(e);+ }} finally {- this.regenerating = false;+ if (!this.isDestroying) {+ this.regenerating = false;+ }}}@@ -588,10 +646,20 @@ export default class CodeLoginForm extends Component {this.username = event.target.value;this.usernameAvailable = false;this.usernameError = null;- discourseDebounce(this, this.checkUsernameAvailability, 350);+ this.avatarTemplate = null;+ cancel(this.#usernameDebounce);+ this.#usernameDebounce = discourseDebounce(+ this,+ this.checkUsernameAvailability,+ 350+ );}async checkUsernameAvailability() {+ if (this.isDestroying) {+ return;+ }+const username = this.username?.trim();if (!username) {this.usernameAvailable = false;@@ -603,19 +671,22 @@ export default class CodeLoginForm extends Component {const seq = ++this.#usernameCheckSeq;this.usernameChecking = true;try {- const result = await User.checkUsername(- username,- this.email,- this.newAccount?.id- );+ const result = await User.checkUsername(username, this.email);- if (seq !== this.#usernameCheckSeq) {+ if (+ this.isDestroying ||+ seq !== this.#usernameCheckSeq ||+ username !== this.username.trim()+ ) {return;}if (result.available) {this.usernameAvailable = true;this.usernameError = null;+ if (result.avatar_template) {+ this.avatarTemplate = result.avatar_template;+ }} else {this.usernameAvailable = false;this.usernameError =@@ -627,43 +698,36 @@ export default class CodeLoginForm extends Component {: i18n("code_login.username_taken"));}} catch {- if (seq === this.#usernameCheckSeq) {+ if (!this.isDestroying && seq === this.#usernameCheckSeq) {this.usernameAvailable = false;}} finally {- if (seq === this.#usernameCheckSeq) {+ if (!this.isDestroying && seq === this.#usernameCheckSeq) {this.usernameChecking = false;}}}@action- async changeAvatar() {- try {- // The picker needs the gravatar/system/upload state, loaded on demand.- if (!this.avatarDetailsLoaded) {- await this.accountUser.findDetails();- this.avatarDetailsLoaded = true;- }- } catch (e) {- return popupAjaxError(e);- }-+ changeAvatar() {this.modal.show(AvatarSelectorModal, {model: {- user: this.accountUser,- onAvatarChange: () => this.avatarChanged(),+ deferSave: true,+ avatarTemplate: this.avatarTemplate,+ canUploadAvatar: this.canUploadAvatar,+ trustLevel: this._signupTrustLevel,+ selection: this.pendingAvatar,+ onSelect: this.selectPendingAvatar,},});}- async avatarChanged() {- // pickAvatar doesn't update the model, so reload to show the new avatar.- try {- await this.accountUser.findDetails();- this.avatarTemplate = this.accountUser.avatar_template;- } catch (e) {- popupAjaxError(e);+ @action+ selectPendingAvatar(selection) {+ this.#clearPendingAvatarUrl();+ this.pendingAvatar = selection;+ if (selection?.file) {+ this.pendingAvatarUrl = URL.createObjectURL(selection.file);}}@@ -700,10 +764,17 @@ export default class CodeLoginForm extends Component {});try {- const result = await ajax("/session/login-code/verify", {- type: "POST",- data,- });+ const result = await applyBehaviorTransformer("create-account", () =>+ ajax("/session/login-code/verify", {+ type: "POST",+ data,+ })+ );++ if (result?.success === false && result.message) {+ this.codeError = result.message;+ return;+ }if (result?.pending_approval) {this.accountPassword = "";@@ -736,29 +807,9 @@ export default class CodeLoginForm extends Component {@actionasync continueAfterSignup() {- if (this.continueDisabled) {- return;+ if (!this.continueDisabled) {+ await this.verifyCode();}-- this.verifying = true;-- const username = this.username.trim();- if (- this.usernameEditable &&- username.toLowerCase() !== this.newAccount.username.toLowerCase()- ) {- try {- await this.accountUser.changeUsername(username);- } catch (e) {- this.verifying = false;- popupAjaxError(e);- return;- }- }-- // Leave the button disabled and spinning through the redirect so it doesn't- // flash back to its idle state before the page navigates away.- this.redirectAfterLogin(this.#postSignupRedirectUrl);}@action@@ -819,6 +870,10 @@ export default class CodeLoginForm extends Component {email: this.email,signup: this.isSignup,invite_key: this.isInvite ? this.args.inviteKey : undefined,+ signup_context:+ this.isSignup && this.args.signupContext+ ? this.args.signupContext+ : undefined,password_confirmation: honeypot.value,challenge: honeypot.challenge.split("").reverse().join(""),},@@ -841,12 +896,12 @@ export default class CodeLoginForm extends Component {redirectAfterLogin(redirectUrl) {const destinationUrl = cookie("destination_url");if (redirectUrl) {- window.location.assign(redirectUrl);+ DiscourseURL.redirectTo(redirectUrl);} else if (destinationUrl) {removeCookie("destination_url");- window.location.assign(destinationUrl);+ DiscourseURL.redirectTo(destinationUrl);} else {- window.location.assign(getURL("/"));+ DiscourseURL.redirectTo("/");}}@@ -867,6 +922,29 @@ export default class CodeLoginForm extends Component {}, 1000);}+ #autoCreateGeneratedAccount() {+ if (+ this.isDestroying ||+ !this.generatedUsername ||+ !this.isSignupDetailsStep ||+ !applyValueTransformer("code-login-auto-create-account", true, {+ context: this.args.context,+ generatedUsername: true,+ })+ ) {+ return;+ }++ if (this.#generatedUsernameAutoSubmits >= 2) {+ this.generatedUsername = false;+ this.checkUsernameAvailability();+ return;+ }++ this.#generatedUsernameAutoSubmits++;+ this.verifyCode();+ }+#setupSignupContinuation(result) {this.signupToken = result.signup_token;this.username = result.username || "";@@ -922,6 +1000,46 @@ export default class CodeLoginForm extends Component {this.sessionStore.remove(SIGNUP_CONTINUATION_KEY);}+ #clearPendingAvatarUrl() {+ if (this.pendingAvatarUrl) {+ URL.revokeObjectURL(this.pendingAvatarUrl);+ this.pendingAvatarUrl = null;+ }+ }++ async #savePendingAvatar(result) {+ const selection = this.pendingAvatar;+ if (!selection) {+ return;+ }++ const user = User.create(result.user);+ try {+ await updateCsrfToken();+ if (selection.file && result.can_upload_avatar) {+ const data = new FormData();+ data.append("type", "avatar");+ data.append("user_id", user.id);+ data.append("files[]", selection.file);+ const upload = await ajax("/uploads.json", {+ type: "POST",+ data,+ processData: false,+ contentType: false,+ timeout: 30000,+ ignoreUnsent: false,+ });+ if (upload?.id) {+ await user.pickAvatar(upload.id, "custom");+ }+ } else if (selection.url) {+ await user.selectAvatar(selection.url);+ }+ } catch {+ // Avatar customization must not block an account that was successfully created.+ }+ }+// A signup flow can gather the required signup fields before the code is// verified — a themed landing page that asks for them up front, say. Taking// those answers here lets the extra step be skipped entirely.@@ -1092,13 +1210,6 @@ export default class CodeLoginForm extends Component {</p>{{/unless}}- {{#if this.isSignup}}- <PluginOutlet- @name="code-login-after-code"- @outletArgs={{lazyHash context=@context}}- />- {{/if}}-{{#each this.otpGenerationArray as |generation|}}<DOtpid="code-login-otp-{{generation}}"@@ -1288,6 +1399,11 @@ export default class CodeLoginForm extends Component {{{/each}}</div>+ <PluginOutlet+ @name="code-login-after-code"+ @outletArgs={{lazyHash context=@context}}+ />+<div aria-live="polite" class="code-login-form__error" role="alert">{{this.codeError}}</div>@@ -1304,33 +1420,36 @@ export default class CodeLoginForm extends Component {</div>{{else if this.isPendingApprovalStep}}<div class="code-login-form__pending-approval-step" role="status"></div>- {{else if this.isCompleteStep}}- <div class="code-login-form__complete-step">+ {{else if this.isSignupDetailsStep}}+ <div class="code-login-form__signup-details-step">{{#unless this.isSignup}}<h2 class="code-login-form__title">- {{i18n "code_login.account_ready_title"}}+ {{this.signupDetailsTitle}}</h2>- {{#if this.usernameEditable}}- <p class="code-login-form__instructions">- {{i18n "code_login.account_ready_edit"}}- </p>- {{/if}}{{/unless}}- <div class="code-login-form__new-account">- <button- class="code-login-form__avatar"- title={{i18n "code_login.change_avatar"}}- type="button"- {{on "click" this.changeAvatar}}- >- {{dBoundAvatarTemplate this.avatarTemplate "huge"}}- <span class="code-login-form__avatar-edit">- {{dIcon "pencil"}}- </span>- </button>+ {{#unless this.generatedUsername}}+ <div class="code-login-form__new-account">+ <button+ aria-label={{i18n "code_login.change_avatar"}}+ class="code-login-form__avatar"+ disabled={{this.verifying}}+ title={{i18n "code_login.change_avatar"}}+ type="button"+ {{on "click" this.changeAvatar}}+ >+ {{#if this.previewAvatarTemplate}}+ {{dBoundAvatarTemplate this.previewAvatarTemplate "huge"}}+ {{else}}+ <span class="code-login-form__avatar-placeholder">+ {{dIcon "user"}}+ </span>+ {{/if}}+ <span class="code-login-form__avatar-edit">+ {{dIcon "pencil"}}+ </span>+ </button>- {{#if this.usernameEditable}}<div class="code-login-form__username-field"><label for="code-login-username">{{i18n "code_login.username_label"}}@@ -1342,6 +1461,7 @@ export default class CodeLoginForm extends Component {autocomplete="off"class="code-login-form__new-account-username{{if this.regenerating '--swapping'}}"+ disabled={{this.verifying}}id="code-login-username"name="username"placeholder={{i18n "code_login.username_placeholder"}}@@ -1356,6 +1476,7 @@ export default class CodeLoginForm extends Component {{{if this.regenerating '--rolling'}}"@action={{this.regenerateUsername}}@ariaLabel="code_login.regenerate_username"+ @disabled={{this.verifying}}@icon="dice"@title="code_login.regenerate_username"/>@@ -1370,12 +1491,22 @@ export default class CodeLoginForm extends Component {{{this.usernameError}}</div></div>- {{else}}- <div class="code-login-form__new-account-username">- {{this.newAccount.username}}- </div>- {{/if}}- </div>+ </div>+ {{/unless}}++ {{#unless this.isInvite}}+ <PluginOutlet+ @name="code-login-after-code"+ @outletArgs={{lazyHash context=@context}}+ />+ {{/unless}}++ {{#if this.codeError}}+ <p+ class="code-login-form__error"+ role="alert"+ >{{this.codeError}}</p>+ {{/if}}<DButtonclass="btn-large btn-primary code-login-form__continue-to-site"diff --git a/frontend/discourse/app/components/modal/avatar-selector.gjs b/frontend/discourse/app/components/modal/avatar-selector.gjsindex fc6699f81fd..081daf92aff 100644--- a/frontend/discourse/app/components/modal/avatar-selector.gjs+++ b/frontend/discourse/app/components/modal/avatar-selector.gjs@@ -1,20 +1,23 @@import Component from "@glimmer/component";import { tracked } from "@glimmer/tracking";-import { fn } from "@ember/helper";+import { fn, hash } from "@ember/helper";import { on } from "@ember/modifier";-import { action } from "@ember/object";+import { action, get } from "@ember/object";import { service } from "@ember/service";import { trustHTML } from "@ember/template";import AvatarUploader from "discourse/components/avatar-uploader";import { ajax } from "discourse/lib/ajax";import { popupAjaxError } from "discourse/lib/ajax-error";import { isTesting } from "discourse/lib/environment";-import { allowsImages } from "discourse/lib/uploads";+import { allowsImages, validateUploadedFile } from "discourse/lib/uploads";+import { eq, or } from "discourse/truth-helpers";import DButton from "discourse/ui-kit/d-button";import DModal from "discourse/ui-kit/d-modal";import DModalCancel from "discourse/ui-kit/d-modal-cancel";+import DPickFilesButton from "discourse/ui-kit/d-pick-files-button";import DRadioButton from "discourse/ui-kit/d-radio-button";import dBoundAvatarTemplate from "discourse/ui-kit/helpers/d-bound-avatar-template";+import dIcon from "discourse/ui-kit/helpers/d-icon";import { i18n } from "discourse-i18n";export default class AvatarSelectorModal extends Component {@@ -24,6 +27,26 @@ export default class AvatarSelectorModal extends Component {@tracked gravatarRefreshDisabled = false;@tracked gravatarFailed = false;@tracked _selected = null;+ @tracked _pendingFile;+ @tracked _filePreview;++ constructor() {+ super(...arguments);+ if (this.deferSave) {+ const selection = this.args.model.selection;+ this._pendingFile = selection?.file;+ this._filePreview = this._pendingFile+ ? URL.createObjectURL(this._pendingFile)+ : null;+ this._selected =+ selection?.url || (this._pendingFile ? "custom" : "system");+ }+ }++ willDestroy() {+ super.willDestroy(...arguments);+ this.#clearFilePreview();+ }get selected() {return this._selected ?? this.defaultSelection;@@ -33,12 +56,31 @@ export default class AvatarSelectorModal extends Component {this._selected = value;}+ get deferSave() {+ return this.args.model.deferSave;+ }++ get systemAvatarTemplate() {+ return this.deferSave+ ? this.args.model.avatarTemplate+ : get(this.user, "system_avatar_template");+ }++ get customAvatarTemplate() {+ return this.deferSave+ ? this._filePreview+ : get(this.user, "custom_avatar_template");+ }+get user() {return this.args.model.user;}get submitDisabled() {- return this.selected === "logo";+ return (+ this.selected === "logo" ||+ (this.deferSave && this.selected === "custom" && !this._pendingFile)+ );}get selectableAvatars() {@@ -57,6 +99,9 @@ export default class AvatarSelectorModal extends Component {get showCustomAvatarSelector() {const mode = this.siteSettings.selectable_avatars_mode;+ const trustLevel = this.deferSave+ ? this.args.model.trustLevel+ : this.user?.trust_level;switch (mode) {case "no_one":return false;@@ -66,12 +111,12 @@ export default class AvatarSelectorModal extends Component {case "tl4":const allowedTl = parseInt(mode.replace("tl", ""), 10);return (- this.user.admin ||- this.user.moderator ||- this.user.trust_level >= allowedTl+ this.user?.admin ||+ this.user?.moderator ||+ (trustLevel ?? 0) >= allowedTl);case "staff":- return this.user.admin || this.user.moderator;+ return this.user?.admin || this.user?.moderator;case "everyone":default:return true;@@ -79,7 +124,9 @@ export default class AvatarSelectorModal extends Component {}get defaultSelection() {- if (this.user.use_logo_small_as_avatar) {+ if (this.deferSave) {+ return "system";+ } else if (this.user.use_logo_small_as_avatar) {return "logo";} else if (this.user.avatar_template === this.user.system_avatar_template) {return "system";@@ -105,8 +152,12 @@ export default class AvatarSelectorModal extends Component {}get allowAvatarUpload() {- // Falls back to the edited user when there is no current user yet, e.g.- // right after a passwordless signup before the app has rebooted.+ if (this.deferSave) {+ return (+ this.args.model.canUploadAvatar &&+ allowsImages(false, this.siteSettings)+ );+ }const user = this.currentUser ?? this.user;return (user.can_upload_avatar && allowsImages(user.staff, this.siteSettings)@@ -114,7 +165,11 @@ export default class AvatarSelectorModal extends Component {}get allowGravatar() {- return this.allowAvatarUpload && this.siteSettings.gravatar_enabled;+ return (+ !this.deferSave &&+ this.allowAvatarUpload &&+ this.siteSettings.gravatar_enabled+ );}@action@@ -122,8 +177,6 @@ export default class AvatarSelectorModal extends Component {this.selected = value;}- // Callers that pass `model.onAvatarChange` (e.g. inline signup) handle the- // result themselves; otherwise we reload so the new avatar shows everywhere.afterAvatarSaved({ guardTesting = false } = {}) {if (this.args.model.onAvatarChange) {this.args.model.onAvatarChange();@@ -136,6 +189,10 @@ export default class AvatarSelectorModal extends Component {@actionasync selectAvatar(url, event) {event?.preventDefault();+ if (this.deferSave) {+ this.selected = url;+ return;+ }try {await this.user.selectAvatar(url);this.afterAvatarSaved();@@ -144,6 +201,23 @@ export default class AvatarSelectorModal extends Component {}}+ @action+ filesPicked(files) {+ const file = files[0];+ if (+ !validateUploadedFile(file, {+ imagesOnly: true,+ siteSettings: this.siteSettings,+ })+ ) {+ return;+ }+ this.#clearFilePreview();+ this._pendingFile = file;+ this._filePreview = URL.createObjectURL(file);+ this.selected = "custom";+ }+@actionuploadComplete() {this.selected = "custom";@@ -177,6 +251,17 @@ export default class AvatarSelectorModal extends Component {@actionasync saveAvatarSelection() {+ if (this.deferSave) {+ let selection = null;+ if (this.selected === "custom") {+ selection = { file: this._pendingFile };+ } else if (this.selected !== "system") {+ selection = { url: this.selected };+ }+ this.args.model.onSelect(selection);+ this.args.closeModal();+ return;+ }try {await this.user.pickAvatar(this.selectedUploadId, this.selected);this.afterAvatarSaved({ guardTesting: true });@@ -185,6 +270,13 @@ export default class AvatarSelectorModal extends Component {}}+ #clearFilePreview() {+ if (this._filePreview) {+ URL.revokeObjectURL(this._filePreview);+ this._filePreview = null;+ }+ }+<template><DModalclass="avatar-selector-modal"@@ -197,6 +289,7 @@ export default class AvatarSelectorModal extends Component {<div class="selectable-avatars">{{#each this.selectableAvatars as |avatar|}}<a+ aria-current={{if (eq this.selected avatar) "true"}}class="selectable-avatar"href{{on "click" (fn this.selectAvatar avatar)}}@@ -237,7 +330,13 @@ export default class AvatarSelectorModal extends Component {@value="system"/><label class="radio" for="system-avatar">- {{dBoundAvatarTemplate this.user.system_avatar_template "large"}}+ {{#if this.systemAvatarTemplate}}+ {{dBoundAvatarTemplate this.systemAvatarTemplate "large"}}+ {{else}}+ <span class="avatar-selector__placeholder">{{dIcon+ "user"+ }}</span>+ {{/if}}{{i18n "user.change_avatar.letter_based"}}</label></div>@@ -299,31 +398,41 @@ export default class AvatarSelectorModal extends Component {@value="custom"/><label class="radio" for="uploaded-avatar">- {{#if this.user.custom_avatar_template}}- {{dBoundAvatarTemplate- this.user.custom_avatar_template- "large"- }}+ {{#if this.customAvatarTemplate}}+ {{dBoundAvatarTemplate this.customAvatarTemplate "large"}}{{i18n "user.change_avatar.uploaded_avatar"}}{{else}}{{i18n "user.change_avatar.uploaded_avatar_empty"}}{{/if}}</label>- <AvatarUploader- class="avatar-uploader"- @done={{this.uploadComplete}}- @id="avatar-uploader"- @uploadedAvatarId={{this.user.custom_avatar_upload_id}}- @uploadedAvatarTemplate={{this.user.custom_avatar_template}}- @user_id={{this.user.id}}- />+ {{#if this.deferSave}}+ <DPickFilesButton+ @acceptedFormatsOverride=".png,.jpg,.jpeg,.gif,.svg,.ico,.heic,.heif,.webp,.avif,.jxl"+ @currentUser={{hash staff=false}}+ @fileInputClass="hidden-upload-field"+ @fileInputId="deferred-avatar-upload"+ @icon="upload"+ @label="upload"+ @onFilesPicked={{this.filesPicked}}+ @showButton={{true}}+ />+ {{else}}+ <AvatarUploader+ class="avatar-uploader"+ @done={{this.uploadComplete}}+ @id="avatar-uploader"+ @uploadedAvatarId={{this.user.custom_avatar_upload_id}}+ @uploadedAvatarTemplate={{this.user.custom_avatar_template}}+ @user_id={{this.user.id}}+ />+ {{/if}}</div>{{/if}}{{/if}}</:body><:footer>- {{#if this.showCustomAvatarSelector}}+ {{#if (or this.showCustomAvatarSelector this.deferSave)}}<DButtonclass="btn-primary"@action={{this.saveAvatarSelection}}diff --git a/frontend/discourse/app/controllers/invites/show.js b/frontend/discourse/app/controllers/invites/show.jsindex 5db29d20125..11f538cf692 100644--- a/frontend/discourse/app/controllers/invites/show.js+++ b/frontend/discourse/app/controllers/invites/show.js@@ -207,7 +207,7 @@ export default class InvitesShowController extends Controller {@computed("codeInviteStep", "showCodeInviteForm", "successMessage")get progressBarStep() {if (this.showCodeInviteForm) {- if (this.codeInviteStep === "complete") {+ if (this.codeInviteStep === "signup-details") {return "login";}diff --git a/frontend/discourse/app/controllers/signup.js b/frontend/discourse/app/controllers/signup.jsindex b1a8b8da85f..73094a45661 100644--- a/frontend/discourse/app/controllers/signup.js+++ b/frontend/discourse/app/controllers/signup.js@@ -37,8 +37,11 @@ export default class SignupPageController extends Controller {@tracked serverAccountEmail;@tracked serverEmailValidation;@tracked codeSignupStep = "email";+ @tracked signupContext;@autoTrackedArray rejectedEmails = [];+ queryParams = [{ signupContext: "signup_context" }];+accountChallenge = 0;accountHoneypot = 0;formSubmitted = false;diff --git a/frontend/discourse/app/lib/registry/transformers.js b/frontend/discourse/app/lib/registry/transformers.jsindex 5ca93468355..084c188ace3 100644--- a/frontend/discourse/app/lib/registry/transformers.js+++ b/frontend/discourse/app/lib/registry/transformers.js@@ -61,6 +61,7 @@ export const VALUE_TRANSFORMERS = Object.freeze(["category-subcategories","category-text-color","category-visibility-private-locked",+ "code-login-auto-create-account","code-login-user-field-values","composer-actions-content","composer-editing-post",diff --git a/frontend/discourse/app/routes/signup.js b/frontend/discourse/app/routes/signup.jsindex 34a3f9ab894..74a8a26c6ef 100644--- a/frontend/discourse/app/routes/signup.js+++ b/frontend/discourse/app/routes/signup.js@@ -100,6 +100,12 @@ export default class extends DiscourseRoute {}}+ resetController(controller, isExiting) {+ if (isExiting) {+ controller.signupContext = null;+ }+ }+setupController(controller) {super.setupController(...arguments);diff --git a/frontend/discourse/app/templates/signup.gjs b/frontend/discourse/app/templates/signup.gjsindex f0fcb630b54..5c68b49ea84 100644--- a/frontend/discourse/app/templates/signup.gjs+++ b/frontend/discourse/app/templates/signup.gjs@@ -81,6 +81,7 @@ export default <template>@context="signup"@initialEmail={{@controller.accountEmail}}@onStepChange={{@controller.updateCodeSignupStep}}+ @signupContext={{@controller.signupContext}}/>{{#if(and @controller.codeSignupOnEmailStep @controller.disclaimerHtml)diff --git a/frontend/discourse/tests/integration/components/code-login-form-test.gjs b/frontend/discourse/tests/integration/components/code-login-form-test.gjsindex f332b4b6900..9d8969094ef 100644--- a/frontend/discourse/tests/integration/components/code-login-form-test.gjs+++ b/frontend/discourse/tests/integration/components/code-login-form-test.gjs@@ -1,7 +1,20 @@-import { click, fillIn, render, waitFor } from "@ember/test-helpers";+import {+ clearRender,+ click,+ fillIn,+ find,+ render,+ settled,+ triggerEvent,+ waitFor,+ waitUntil,+} from "@ember/test-helpers";import { module, test } from "qunit";+import sinon from "sinon";import CodeLoginForm from "discourse/components/code-login-form";+import ModalContainer from "discourse/components/modal-container";import { withPluginApi } from "discourse/lib/plugin-api";+import DiscourseURL from "discourse/lib/url";import { setupRenderingTest } from "discourse/tests/helpers/component-test";import pretender, { response } from "discourse/tests/helpers/create-pretender";import formKit from "discourse/tests/helpers/form-kit-helper";@@ -15,7 +28,7 @@ function stubCodeRequest() {}async function goToCodeStep() {- await render(<template><CodeLoginForm /></template>);+ await render(<template><CodeLoginForm /><ModalContainer /></template>);await fillIn(".code-login-form__email-step .form-kit__control-input",@@ -23,6 +36,17 @@ async function goToCodeStep() {await formKit().submit();}+async function selectLocalAvatar() {+ await click(".code-login-form__avatar");+ const file = new File(["avatar"], "avatar.png", { type: "image/png" });+ const transfer = new DataTransfer();+ transfer.items.add(file);+ find("#deferred-avatar-upload").files = transfer.files;+ await triggerEvent("#deferred-avatar-upload", "change");+ await click(".avatar-selector-modal .btn-primary");+ return file;+}+module("Integration | Component | CodeLoginForm", function (hooks) {setupRenderingTest(hooks);@@ -66,24 +90,37 @@ module("Integration | Component | CodeLoginForm", function (hooks) {.exists("the email can still be corrected before verification");});- test("signup requests declare their intent", async function (assert) {- let signup;+ test("signup requests declare their intent and context", async function (assert) {+ let requestParams;pretender.get("/session/hp.json", () =>response({ value: "hp-value", challenge: "abc", expires_in: 300 }));pretender.post("/session/login-code", (request) => {- signup = new URLSearchParams(request.requestBody).get("signup");+ requestParams = new URLSearchParams(request.requestBody);return response({ success: "OK" });});- await render(<template><CodeLoginForm @context="signup" /></template>);+ await render(+ <template>+ <CodeLoginForm @context="signup" @signupContext="opaque-context" />+ </template>+ );await fillIn(".code-login-form__email-step .form-kit__control-input",);await formKit().submit();- assert.strictEqual(signup, "true", "the request identifies signup intent");+ assert.strictEqual(+ requestParams.get("signup"),+ "true",+ "the request identifies signup intent"+ );+ assert.strictEqual(+ requestParams.get("signup_context"),+ "opaque-context",+ "the request forwards the opaque signup context"+ );assert.dom(".code-login-form__code-step").exists("the form advances after the request succeeds");@@ -129,7 +166,7 @@ module("Integration | Component | CodeLoginForm", function (hooks) {.doesNotExist("the scoped invitation address cannot be changed");});- test("runs create-account behavior transformers before verifying a signup code", async function (assert) {+ test("runs create-account behavior transformers only when submitting the chosen username", async function (assert) {stubCodeRequest();let transformed = false;@@ -140,9 +177,18 @@ module("Integration | Component | CodeLoginForm", function (hooks) {return next();}));- pretender.post("/session/login-code/verify", () => {+ pretender.post("/session/login-code/verify", (request) => {verificationRequests++;- return response({ error: i18n("email_login_code.invalid_code") });+ const params = new URLSearchParams(request.requestBody);+ return response(+ params.get("username")+ ? { success: false, message: "Signup verification failed" }+ : {+ username_required: true,+ username: "jane",+ avatar_template: "/letter/j.png",+ }+ );});await render(<template><CodeLoginForm @context="signup" /></template>);@@ -151,16 +197,264 @@ module("Integration | Component | CodeLoginForm", function (hooks) {);await formKit().submit();- await fillIn(".d-otp-input", "000000");+ await fillIn(".d-otp-input", "123456");- assert.true(+ assert.false(transformed,- "the signup verification passes through the transformer"+ "checking the email code does not run account creation challenges");+ await click(".code-login-form__continue-to-site");++ assert.true(transformed, "account creation passes through the transformer");+ assert.strictEqual(+ verificationRequests,+ 2,+ "the transformer continues to account creation"+ );+ assert+ .dom(".code-login-form__signup-details-step")+ .exists("signup remains on the username step after rejection");+ assert+ .dom(".code-login-form__signup-details-step > p.code-login-form__error")+ .hasText(+ "Signup verification failed",+ "the account creation rejection is shown"+ );+ });++ test("automatically creates an account with a server-generated username", async function (assert) {+ stubCodeRequest();+ const redirect = sinon.stub(DiscourseURL, "redirectTo");+ let transformed = false;+ const verificationParams = [];+ withPluginApi((api) =>+ api.registerBehaviorTransformer("create-account", async ({ next }) => {+ transformed = true;+ return next();+ })+ );+ pretender.post("/session/login-code/verify", (request) => {+ const params = new URLSearchParams(request.requestBody);+ verificationParams.push(params);+ return response(+ params.get("username")+ ? { account_created: true, redirect_url: "/welcome" }+ : {+ username_required: true,+ generated_username: true,+ username: "generated-name",+ }+ );+ });++ await render(+ <template>+ <CodeLoginForm @context="signup" @signupContext="opaque-context" />+ </template>+ );+ await fillIn(+ ".code-login-form__email-step .form-kit__control-input",+ );+ await formKit().submit();+ await fillIn(".d-otp-input", "123456");+ await waitUntil(() => redirect.calledOnce);+ await settled();++ assert.true(transformed, "the actual creation runs account security gates");+ assert.strictEqual(+ verificationParams.length,+ 2,+ "creation is submitted once"+ );+ assert.strictEqual(+ verificationParams[1].get("username"),+ "generated-name",+ "the generated username is submitted through the normal endpoint"+ );+ assert.deepEqual(+ verificationParams.map((params) => params.get("signup_context")),+ ["opaque-context", "opaque-context"],+ "the context accompanies verification and account creation"+ );+ assert+ .dom(".code-login-form__new-account")+ .doesNotExist("generated mode does not ask for identity details");+ });++ test("reveals a stable manual fallback after two generated retries", async function (assert) {+ stubCodeRequest();+ const redirect = sinon.stub(DiscourseURL, "redirectTo");+ const submittedUsernames = [];+ pretender.post("/session/login-code/verify", (request) => {+ const params = new URLSearchParams(request.requestBody);+ submittedUsernames.push(params.get("username"));+ return response({+ username_required: true,+ generated_username: true,+ username: `generated-${submittedUsernames.length}`,+ });+ });++ await render(<template><CodeLoginForm @context="signup" /></template>);+ await fillIn(+ ".code-login-form__email-step .form-kit__control-input",+ );+ await formKit().submit();+ await fillIn(".d-otp-input", "123456");+ await waitFor(".code-login-form__new-account");+ await settled();++ assert.deepEqual(+ submittedUsernames,+ [null, "generated-1", "generated-2"],+ "the flow makes the initial verification and exactly two automatic retries"+ );+ assert+ .dom("#code-login-username")+ .hasValue("generated-3", "the final candidate remains editable");+ assert.false(redirect.called, "the rejected attempts do not redirect");+ });++ test("does not mutate or redirect after an automatic verification is destroyed", async function (assert) {+ stubCodeRequest();+ const redirect = sinon.stub(DiscourseURL, "redirectTo");+ let resolveCreation;+ let creationStarted = false;+ withPluginApi((api) =>+ api.registerBehaviorTransformer("create-account", async ({ next }) => {+ creationStarted = true;+ await new Promise((resolve) => (resolveCreation = resolve));+ return next();+ })+ );+ pretender.post("/session/login-code/verify", (request) => {+ const params = new URLSearchParams(request.requestBody);+ return response(+ params.get("username")+ ? { account_created: true, redirect_url: "/welcome" }+ : {+ username_required: true,+ generated_username: true,+ username: "generated-name",+ }+ );+ });++ await render(<template><CodeLoginForm @context="signup" /></template>);+ await fillIn(+ ".code-login-form__email-step .form-kit__control-input",+ );+ await formKit().submit();+ const verification = fillIn(".d-otp-input", "123456");+ await waitUntil(() => creationStarted);++ const teardown = clearRender();+ resolveCreation();+ await Promise.all([verification, teardown]);+ await settled();++ assert.false(redirect.called, "the destroyed flow does not redirect");+ assert.dom(".code-login-form").doesNotExist("the form stays destroyed");+ });++ test("ignores an in-flight username response after destruction", async function (assert) {+ stubCodeRequest();+ let resolveUsername;+ let usernameRequestStarted = false;+ pretender.post("/session/login-code/verify", () =>+ response({ username_required: true, username: "generated-name" })+ );+ pretender.get("/u/check_username", async () => {+ usernameRequestStarted = true;+ await new Promise((resolve) => (resolveUsername = resolve));+ return response({ available: true, avatar_template: "/letter/g.png" });+ });++ await render(<template><CodeLoginForm @context="signup" /></template>);+ await fillIn(+ ".code-login-form__email-step .form-kit__control-input",+ );+ await formKit().submit();+ const verification = fillIn(".d-otp-input", "123456");+ await waitUntil(() => usernameRequestStarted);++ const teardown = clearRender();+ resolveUsername();+ await Promise.all([verification, teardown]);+ await settled();++ assert.dom(".code-login-form").doesNotExist("the form stays destroyed");+ });++ test("waits for interaction when automatic generated account creation is disabled", async function (assert) {+ stubCodeRequest();+ let transformed = false;+ let verificationRequests = 0;+ withPluginApi((api) => {+ api.registerValueTransformer(+ "code-login-auto-create-account",+ () => false+ );+ api.registerBehaviorTransformer("create-account", async ({ next }) => {+ transformed = true;+ return next();+ });+ });+ pretender.post("/session/login-code/verify", (request) => {+ verificationRequests++;+ const params = new URLSearchParams(request.requestBody);+ return response(+ params.get("username")+ ? { success: false, message: "Interaction is required" }+ : {+ username_required: true,+ generated_username: true,+ username: "generated-name",+ }+ );+ });++ await render(<template><CodeLoginForm @context="signup" /></template>);+ await fillIn(+ ".code-login-form__email-step .form-kit__control-input",+ );+ await formKit().submit();+ await fillIn(".d-otp-input", "123456");+assert.strictEqual(verificationRequests,1,- "the transformer continues to code verification"+ "creation does not run automatically"+ );+ assert.false(+ transformed,+ "the account security gate has not run prematurely"+ );+ assert+ .dom(".code-login-form__signup-details-step")+ .exists("the interaction step is visible");+ assert+ .dom(".login-title")+ .hasText(+ i18n("code_login.account_details_title"),+ "generated mode uses the generic account details heading"+ );+ assert+ .dom(".code-login-form__continue-to-site")+ .exists("the normal final action remains available");++ await click(".code-login-form__continue-to-site");++ assert.true(transformed, "the security gate runs after interaction");+ assert.strictEqual(+ verificationRequests,+ 2,+ "creation uses the normal request");});@@ -395,6 +689,67 @@ module("Integration | Component | CodeLoginForm", function (hooks) {.exists("valid details submit for approval");});+ test("preserves approval signup details when an account creation transformer rejects submission", async function (assert) {+ const redirect = sinon.stub(DiscourseURL, "redirectTo");+ this.owner.lookup("service:session-store").setObject({+ key: "email-code-signup-continuation",+ value: {+ email: "[email protected]",+ expiresAt: Date.now() + 60_000,+ signupToken: "signup-token",+ username: "",+ },+ });++ let rejected = true;+ withPluginApi((api) => {+ api.registerBehaviorTransformer("create-account", async ({ next }) =>+ rejected ? { success: false, message: "Complete the CAPTCHA" } : next()+ );+ });+ let verificationRequests = 0;+ pretender.post("/session/login-code/verify", () => {+ verificationRequests++;+ return response({ pending_approval: true });+ });++ await render(<template><CodeLoginForm @context="signup" /></template>);+ await fillIn("#code-login-username", "chosen-name");+ await waitFor(".code-login-form__submit-approval:not([disabled])");+ await click(".code-login-form__submit-approval");++ assert.false(redirect.called, "a rejected submission does not redirect");+ assert.strictEqual(+ verificationRequests,+ 0,+ "rejection prevents account creation"+ );+ assert+ .dom("#code-login-username")+ .hasValue("chosen-name", "the username is preserved");+ assert+ .dom(".code-login-form__account-details-step")+ .includesText(+ "Complete the CAPTCHA",+ "the rejection is shown for correction"+ );+ assert+ .dom(".code-login-form__submit-approval")+ .isNotDisabled("submission can be retried");++ rejected = false;+ await click(".code-login-form__submit-approval");++ assert.strictEqual(+ verificationRequests,+ 1,+ "corrected details are submitted once"+ );+ assert+ .dom(".code-login-form__pending-approval-step")+ .exists("the retry reaches pending approval");+ });+test("ignores missing and expired signup continuations", async function (assert) {const sessionStore = this.owner.lookup("service:session-store");@@ -488,10 +843,10 @@ module("Integration | Component | CodeLoginForm", function (hooks) {verifyParams = new URLSearchParams(request.requestBody);return response({- account_created: true,- user: { id: 1, username: "jane", avatar_template: "/letter/j.png" },- can_edit_username: true,- prefill_username: true,+ username_required: true,+ username: "jane",+ avatar_template: "/letter/j.png",+ can_upload_avatar: true,});});@@ -506,6 +861,19 @@ module("Integration | Component | CodeLoginForm", function (hooks) {assert.dom(".code-login-form__user-fields-step").doesNotExist("the fields are already answered, so the step is skipped");++ await click(".code-login-form__continue-to-site");++ assert.strictEqual(+ verifyParams.get("username"),+ "jane",+ "the final request submits the chosen username"+ );+ assert.strictEqual(+ verifyParams.get("user_fields[7]"),+ "true",+ "the prefilled answer is retained for account creation"+ );});test("withholds prefilled user fields while a required one is unanswered", async function (assert) {@@ -542,18 +910,31 @@ module("Integration | Component | CodeLoginForm", function (hooks) {test("collects a required full name before completing signup", async function (assert) {stubCodeRequest();+ const redirect = sinon.stub(DiscourseURL, "redirectTo");const verifyRequests = [];pretender.post("/session/login-code/verify", (request) => {const params = new URLSearchParams(request.requestBody);verifyRequests.push(params);- if (params.get("name")) {+ if (params.get("username")) {return response({account_created: true,- user: { id: 1, username: "jane", avatar_template: "/letter/j.png" },- can_edit_username: true,- prefill_username: true,+ user: {+ id: 1,+ username: "jane",+ avatar_template: "/letter/j.png",+ },+ redirect_url: "/latest",+ });+ }++ if (params.get("name")) {+ return response({+ username_required: true,+ username: "jane",+ avatar_template: "/letter/j.png",+ can_upload_avatar: true,});}@@ -589,20 +970,42 @@ module("Integration | Component | CodeLoginForm", function (hooks) {"Jane Doe","the trimmed name is sent");- assert.dom(".code-login-form__complete-step").exists();+ assert.dom(".code-login-form__signup-details-step").exists();assert.dom("#code-login-username")- .hasValue("jane", "the assigned username is prefilled");+ .hasValue("jane", "the suggested username is prefilled");+ await click(".code-login-form__continue-to-site");++ assert.strictEqual(+ verifyRequests.length,+ 3,+ "Continue submits account creation"+ );+ assert.strictEqual(+ verifyRequests[2].get("name"),+ "Jane Doe",+ "the full name is retained for account creation"+ );+ assert.strictEqual(+ verifyRequests[2].get("username"),+ "jane",+ "the chosen username is submitted"+ );+ assert.true(+ redirect.calledOnceWithExactly("/latest"),+ "signup completes after username selection"+ );});- test("regenerates a random username suggestion on the account-ready step", async function (assert) {+ test("regenerates a random username suggestion before creating the account", async function (assert) {+ this.siteSettings.enable_random_usernames = true;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,+ username_required: true,+ username: "jane",+ avatar_template: "/letter/j.png",+ can_upload_avatar: true,}));pretender.get("/u/random-username.json", () =>@@ -628,13 +1031,14 @@ module("Integration | Component | CodeLoginForm", function (hooks) {});test("keeps continue disabled when the regenerated username is unavailable", async function (assert) {+ this.siteSettings.enable_random_usernames = true;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,+ username_required: true,+ username: "jane",+ avatar_template: "/letter/j.png",+ can_upload_avatar: true,}));// The default pretender handler reports the username "taken" as@@ -657,15 +1061,72 @@ module("Integration | Component | CodeLoginForm", function (hooks) {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;+ test("previews the avatar for a valid username and uses a person icon otherwise", async function (assert) {+ stubCodeRequest();+ pretender.post("/session/login-code/verify", () =>+ response({+ username_required: true,+ username: null,+ avatar_template: null,+ can_upload_avatar: true,+ })+ );+ pretender.get("/u/check_username", (request) =>+ response(+ request.queryParams.username === "taken"+ ? { available: false }+ : { available: true, avatar_template: "/letter/j.png" }+ )+ );++ await goToCodeStep();+ await fillIn(".d-otp-input", "123456");++ assert+ .dom(".code-login-form__avatar .d-icon-user")+ .exists("a blank username has a neutral person icon");+ assert+ .dom(".code-login-form__avatar img")+ .doesNotExist("the fallback avatar is hidden");++ await fillIn("#code-login-username", "jane");++ assert+ .dom(".code-login-form__avatar img")+ .hasAttribute(+ "src",+ /letter\/j/,+ "the preview matches the validated username"+ );+ assert+ .dom(".code-login-form__avatar .d-icon-user")+ .doesNotExist("the letter avatar replaces the icon");++ await fillIn("#code-login-username", "taken");++ assert+ .dom(".code-login-form__avatar .d-icon-user")+ .exists("an unavailable username has no letter preview");++ await fillIn("#code-login-username", "jane");+ await fillIn("#code-login-username", "");++ assert+ .dom(".code-login-form__avatar .d-icon-user")+ .exists("clearing the username restores the icon");+ assert+ .dom(".code-login-form__continue-to-site")+ .isDisabled("a username is still required");+ });++ test("hides the regenerate button and makes the user pick by default", async function (assert) {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,+ username_required: true,+ username: null,+ avatar_template: null,+ can_upload_avatar: true,}));@@ -679,26 +1140,200 @@ module("Integration | Component | CodeLoginForm", function (hooks) {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) {+ test("keeps a local avatar preview without uploading before account creation", async function (assert) {stubCodeRequest();+ this.siteSettings.selectable_avatars_mode = "tl2";+ let uploads = 0;+ pretender.post("/uploads.json", () => {+ uploads++;+ return response({ id: 42 });+ });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,+ username_required: true,+ can_upload_avatar: true,+ trust_level: 2,}));+ pretender.get("/u/check_username", () =>+ response({ available: true, avatar_template: "/letter/j.png" })+ );await goToCodeStep();await fillIn(".d-otp-input", "123456");+ await selectLocalAvatar();- 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();+ const preview = find(".code-login-form__avatar img").getAttribute("src");+ assert.true(preview.startsWith("blob:"), "the preview uses a local file");++ await fillIn("#code-login-username", "jane");+ await fillIn("#code-login-username", "");++ assert+ .dom(".code-login-form__avatar img")+ .hasAttribute(+ "src",+ preview,+ "username changes preserve the selected image"+ );+ assert.strictEqual(+ uploads,+ 0,+ "no avatar is uploaded before signup completes"+ );+ assert+ .dom(".code-login-form__continue-to-site")+ .isDisabled("an avatar does not replace the username requirement");});+ test("does not redirect when destroyed during the pending avatar upload", async function (assert) {+ stubCodeRequest();+ const redirect = sinon.stub(DiscourseURL, "redirectTo");+ let resolveUpload;+ let uploadStarted = false;+ pretender.post("/session/login-code/verify", (request) => {+ const params = new URLSearchParams(request.requestBody);+ return response(+ params.get("username")+ ? {+ account_created: true,+ user: {+ id: 1,+ username: "jane",+ avatar_template: "/letter/j.png",+ },+ can_upload_avatar: true,+ redirect_url: "/latest",+ }+ : { username_required: true, can_upload_avatar: true }+ );+ });+ pretender.get("/u/check_username", () =>+ response({ available: true, avatar_template: "/letter/j.png" })+ );+ pretender.post("/uploads.json", async () => {+ uploadStarted = true;+ await new Promise((resolve) => (resolveUpload = resolve));+ return response({ id: 42 });+ });+ pretender.put("/u/jane/preferences/avatar/pick", () =>+ response({ success: "OK" })+ );++ await goToCodeStep();+ await fillIn(".d-otp-input", "123456");+ await selectLocalAvatar();+ await fillIn("#code-login-username", "jane");+ const submission = click(".code-login-form__continue-to-site");+ await waitUntil(() => uploadStarted);++ const teardown = clearRender();+ resolveUpload();+ await Promise.all([submission, teardown]);+ await settled();++ assert.false(redirect.called, "the destroyed flow does not redirect");+ assert.dom(".code-login-form").doesNotExist("the form stays destroyed");+ });++ for (const failure of [null, "upload", "pick"]) {+ test(`creates the account before uploading and continues ${failure ? `after ${failure} failure` : "after selecting the avatar"}`, async function (assert) {+ stubCodeRequest();+ const requests = [];+ const redirect = sinon.stub(DiscourseURL, "redirectTo").callsFake(() => {+ requests.push("redirect");+ });+ const alert = sinon.spy(this.owner.lookup("service:dialog"), "alert");+ let uploadBody;+ let creationParams;+ pretender.post("/session/login-code/verify", (request) => {+ const params = new URLSearchParams(request.requestBody);+ let result = { username_required: true, can_upload_avatar: true };+ if (params.get("username")) {+ requests.push("create");+ creationParams = params;+ result = {+ account_created: true,+ user: {+ id: 1,+ username: "jane",+ avatar_template: "/letter/j.png",+ },+ can_upload_avatar: true,+ redirect_url: "/latest",+ };+ }+ return response(result);+ });+ pretender.get("/u/check_username", () =>+ response({ available: true, avatar_template: "/letter/j.png" })+ );+ pretender.post("/uploads.json", (request) => {+ requests.push("upload");+ uploadBody = request.requestBody;+ return failure === "upload"+ ? response(500, { errors: ["Upload failed"] })+ : response({ id: 42 });+ });+ pretender.put("/u/jane/preferences/avatar/pick", (request) => {+ requests.push("pick");+ const params = new URLSearchParams(request.requestBody);+ assert.strictEqual(+ params.get("upload_id"),+ "42",+ "the uploaded image is selected"+ );+ return failure === "pick"+ ? response(500, { errors: ["Selection failed"] })+ : response({ success: "OK" });+ });++ await goToCodeStep();+ await fillIn(".d-otp-input", "123456");+ const file = await selectLocalAvatar();+ await fillIn("#code-login-username", "jane");+ await click(".code-login-form__continue-to-site");++ assert.strictEqual(+ creationParams.get("username"),+ "jane",+ "account creation receives the chosen username"+ );+ assert.strictEqual(+ creationParams.get("code"),+ "123456",+ "the verified code accompanies account creation"+ );+ assert.deepEqual(+ requests,+ failure === "upload"+ ? ["create", "upload", "redirect"]+ : ["create", "upload", "pick", "redirect"],+ "signup finishes after attempting the authenticated avatar upload"+ );+ assert.strictEqual(+ uploadBody.get("type"),+ "avatar",+ "the file is uploaded as an avatar"+ );+ assert.strictEqual(+ uploadBody.get("user_id"),+ "1",+ "the upload belongs to the newly created user"+ );+ assert.strictEqual(+ uploadBody.get("files[]").name,+ file.name,+ "the selected file is uploaded"+ );+ assert.true(+ redirect.calledOnceWithExactly("/latest"),+ "signup continues to the destination"+ );+ assert.false(alert.called, "avatar failures do not show a retry dialog");+ });+ }+test("returns to the email step when using a different email", async function (assert) {stubCodeRequest();diff --git a/frontend/discourse/tests/integration/components/modal/avatar-selector-test.gjs b/frontend/discourse/tests/integration/components/modal/avatar-selector-test.gjsnew file mode 100644index 00000000000..cb76355b0b4--- /dev/null+++ b/frontend/discourse/tests/integration/components/modal/avatar-selector-test.gjs@@ -0,0 +1,173 @@+import {+ click,+ find,+ render,+ settled,+ triggerEvent,+} from "@ember/test-helpers";+import { module, test } from "qunit";+import sinon from "sinon";+import AvatarSelectorModal from "discourse/components/modal/avatar-selector";+import ModalContainer from "discourse/components/modal-container";+import User from "discourse/models/user";+import { setupRenderingTest } from "discourse/tests/helpers/component-test";+import pretender, { response } from "discourse/tests/helpers/create-pretender";++async function showAvatarSelector(context, model) {+ await render(<template><ModalContainer /></template>);+ context.owner.lookup("service:modal").show(AvatarSelectorModal, { model });+ await settled();+}++module("Integration | Component | Modal | AvatarSelector", function (hooks) {+ setupRenderingTest(hooks, { anonymous: true });++ test("deferred file selection can be cancelled without changing the saved selection", async function (assert) {+ const initialFile = new File(["initial"], "initial.png", {+ type: "image/png",+ });+ const selection = { file: initialFile };+ const onSelect = sinon.spy();+ const model = {+ deferSave: true,+ canUploadAvatar: true,+ selection,+ onSelect,+ };++ await showAvatarSelector(this, model);++ assert+ .dom(".avatar-choice--upload img")+ .hasAttribute(+ "src",+ /^blob:/,+ "the saved file is previewed on reopening"+ );+ assert.dom("#uploaded-avatar").isChecked("the pending file is selected");+ assert+ .dom(".avatar-choice--gravatar")+ .doesNotExist("Gravatar requires an account");++ const replacement = new File(["replacement"], "replacement.png", {+ type: "image/png",+ });+ const transfer = new DataTransfer();+ transfer.items.add(replacement);+ find("#deferred-avatar-upload").files = transfer.files;+ await triggerEvent("#deferred-avatar-upload", "change");+ await click(".d-modal-cancel");++ assert+ .dom(".avatar-selector-modal")+ .doesNotExist("cancel closes the modal");+ assert.true(onSelect.notCalled, "cancel does not save a selection");+ assert.strictEqual(+ selection.file,+ initialFile,+ "the caller retains its original file"+ );+ });++ test("deferred preset selection waits for Save even when custom avatars are disabled", async function (assert) {+ this.siteSettings.selectable_avatars_mode = "no_one";+ this.siteSettings.selectable_avatars = ["/preset.png"];+ const onSelect = sinon.spy();+ const model = { deferSave: true, onSelect };++ await showAvatarSelector(this, model);+ await click(".selectable-avatar");++ assert.true(onSelect.notCalled, "choosing a preset does not save it");+ assert+ .dom(".avatar-selector-modal")+ .exists("the modal stays open until saved");+ assert+ .dom(".selectable-avatar")+ .hasAttribute("aria-current", "true", "the chosen preset is marked");+ await click(".btn-primary");+ assert.deepEqual(+ onSelect.firstCall.args,+ [{ url: "/preset.png" }],+ "Save returns the chosen preset to the caller"+ );+ assert.dom(".avatar-selector-modal").doesNotExist("Save closes the modal");+ });++ test("deferred selection can return to the system avatar", async function (assert) {+ const onSelect = sinon.spy();+ const model = {+ deferSave: true,+ canUploadAvatar: true,+ selection: {+ file: new File(["avatar"], "avatar.png", { type: "image/png" }),+ },+ onSelect,+ };++ await showAvatarSelector(this, model);+ assert+ .dom(".avatar-selector__placeholder .d-icon-user")+ .exists("the system avatar is neutral before a username is chosen");+ await click("#system-avatar");+ await click(".btn-primary");++ assert.deepEqual(+ onSelect.firstCall.args,+ [null],+ "Save clears the pending avatar"+ );+ });++ for (const trustLevel of [0, 1, 2, 3, 4]) {+ test(`deferred uploads respect the prospective trust level ${trustLevel}`, async function (assert) {+ this.siteSettings.selectable_avatars_mode = "tl2";+ await showAvatarSelector(this, {+ deferSave: true,+ canUploadAvatar: true,+ trustLevel,+ });++ if (trustLevel >= 2) {+ assert.dom("#deferred-avatar-upload").exists();+ } else {+ assert.dom("#deferred-avatar-upload").doesNotExist();+ }+ });+ }++ test("normal saving persists the selected avatar to the account", async function (assert) {+ const onAvatarChange = sinon.spy();+ const model = {+ user: User.create({+ username: "jane",+ avatar_template: "/custom.png",+ system_avatar_template: "/letter.png",+ }),+ onAvatarChange,+ };+ pretender.put("/u/jane/preferences/avatar/pick", (request) => {+ assert.strictEqual(+ new URLSearchParams(request.requestBody).get("type"),+ "system",+ "the normal picker saves to the account"+ );+ return response({ success: "OK" });+ });++ await showAvatarSelector(this, model);+ await click("#system-avatar");+ await click(".btn-primary");++ assert.true(+ onAvatarChange.calledOnce,+ "the caller is notified after saving"+ );+ assert+ .dom(".avatar-selector-modal")+ .doesNotExist("the picker closes after saving");+ assert+ .dom("#deferred-avatar-upload")+ .doesNotExist("normal mode does not offer a deferred upload");+ });+});diff --git a/lib/random_username_generator.rb b/lib/random_username_generator.rbindex d4fc6f6e9b5..fb6bd56f93a 100644--- a/lib/random_username_generator.rb+++ b/lib/random_username_generator.rb@@ -7,8 +7,8 @@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+ def self.generate(allow_when_disabled: false)+ return nil if !allow_when_disabled && !SiteSetting.enable_random_usernamesadjective = pick(SiteSetting.random_username_adjectives_map)noun = pick(SiteSetting.random_username_nouns_map)diff --git a/plugins/discourse-captcha/assets/javascripts/pre-initializers/h-captcha.js b/plugins/discourse-captcha/assets/javascripts/pre-initializers/h-captcha.jsindex 314afd0d88d..5f09c5977f1 100644--- a/plugins/discourse-captcha/assets/javascripts/pre-initializers/h-captcha.js+++ b/plugins/discourse-captcha/assets/javascripts/pre-initializers/h-captcha.js@@ -20,6 +20,8 @@ function initializeHCaptcha(api, container) {return;}+ api.registerValueTransformer("code-login-auto-create-account", () => false);+api.registerBehaviorTransformer("create-account", async ({ next }) => {const captchaService = container.lookup("service:captcha-service");captchaService.submitted = true;diff --git a/plugins/discourse-captcha/lib/discourse_captcha/session_controller_patch.rb b/plugins/discourse-captcha/lib/discourse_captcha/session_controller_patch.rbindex f5accbb3eb2..31cc7072cdf 100644--- a/plugins/discourse-captcha/lib/discourse_captcha/session_controller_patch.rb+++ b/plugins/discourse-captcha/lib/discourse_captcha/session_controller_patch.rb@@ -39,8 +39,8 @@ module DiscourseCaptchareturn false if matched_user.present? || params[:invite_key].present?return false if !registration_via_login_code_open?- pending_approval_signup?(matched_user) ||- (!signup_user_fields_missing? && !signup_full_name_missing?)+ !pending_approval_signup?(matched_user) && params[:username].present? &&+ !signup_user_fields_missing? && !signup_full_name_missing?endinclude CaptchaVerificationdiff --git a/plugins/discourse-captcha/spec/requests/discourse_captcha/session_controller_spec.rb b/plugins/discourse-captcha/spec/requests/discourse_captcha/session_controller_spec.rbindex 7587956a4b8..8e77e7afbfc 100644--- a/plugins/discourse-captcha/spec/requests/discourse_captcha/session_controller_spec.rb+++ b/plugins/discourse-captcha/spec/requests/discourse_captcha/session_controller_spec.rb@@ -1,7 +1,7 @@# frozen_string_literal: trueRSpec.describe SessionController do- describe "POST /session/login-code/verify" do+ describe "#verify_login_code" dofab!(:existing_user, :user)before do@@ -13,20 +13,66 @@ RSpec.describe SessionController doSiteSetting.hcaptcha_secret_key = "secret-key"end+ it "verifies the email without CAPTCHA and waits for a username before creating an account" do+ email = "[email protected]"+ login_code = EmailLoginCode.generate!(email:)++ expect {+ post "/session/login-code/verify.json", params: { email:, code: login_code.code }+ }.not_to change(User, :count)++ expect(response.status).to eq(200)+ expect(response.parsed_body["username_required"]).to eq(true)+ expect(login_code.reload.consumed_at).to be_nil+ expect(session[:current_user_id]).to be_nil+ end+it "does not create an account without completing CAPTCHA" doemail = "[email protected]"code = EmailLoginCode.generate!(email:).code- expect { post "/session/login-code/verify.json", params: { email:, code: } }.not_to change(- User,- :count,- )+ expect {+ post "/session/login-code/verify.json",+ params: {+ email:,+ code:,+ username: "chosen_username",+ }+ }.not_to change(User, :count)expect(response.status).to eq(200)expect(response.parsed_body["error"]).to eq(I18n.t("captcha_verification_failed"))expect(session[:current_user_id]).to be_nilend+ it "requires CAPTCHA on final generated-username creation without consuming the code" do+ plugin_instance = Plugin::Instance.new+ modifier = proc { |_, _, _| :generated }+ plugin_instance.register_modifier(:email_login_code_username_mode, &modifier)+ email = "[email protected]"+ login_code = EmailLoginCode.generate!(email:)++ post "/session/login-code/verify.json", params: { email:, code: login_code.code }+ username = response.parsed_body["username"]++ expect(response.parsed_body["generated_username"]).to eq(true)+ expect(User.find_by_email(email)).to be_nil++ post "/session/login-code/verify.json", params: { email:, code: login_code.code, username: }++ expect(response.parsed_body["error"]).to eq(I18n.t("captcha_verification_failed"))+ expect(User.find_by_email(email)).to be_nil+ expect(login_code.reload.consumed_at).to be_nil+ ensure+ if plugin_instance && modifier+ DiscoursePluginRegistry.unregister_modifier(+ plugin_instance,+ :email_login_code_username_mode,+ &modifier+ )+ end+ end+it "creates an account after the CAPTCHA provider verifies the challenge" doemail = "[email protected]"code = EmailLoginCode.generate!(email:).code@@ -39,10 +85,14 @@ RSpec.describe SessionController dopost "/captcha/hcaptcha/create.json", params: { token: "captcha-token" }- expect { post "/session/login-code/verify.json", params: { email:, code: } }.to change(- User,- :count,- ).by(1)+ expect {+ post "/session/login-code/verify.json",+ params: {+ email:,+ code:,+ username: "chosen_username",+ }+ }.to change(User, :count).by(1)expect(response.status).to eq(200)expect(response.parsed_body["account_created"]).to eq(true)@@ -58,6 +108,7 @@ RSpec.describe SessionController doparams: {email: invite.email,code:,+ username: "invited_person",invite_key: invite.invite_key,}}.to change(User, :count).by(1)@@ -97,7 +148,7 @@ RSpec.describe SessionController do}end- it "carries verified CAPTCHA proof into the continuation without validating it twice" do+ it "verifies CAPTCHA only when submitting the approval account details" doverification_request =stub_request(:post, DiscourseCaptcha::HcaptchaProvider::CAPTCHA_VERIFICATION_URL).with(body: {@@ -105,7 +156,6 @@ RSpec.describe SessionController doresponse: "captcha-token",},).to_return(status: 200, body: '{"success":true}')- post "/captcha/hcaptcha/create.json", params: { token: "captcha-token" }expect {post "/session/login-code/verify.json", params: { email:, code: login_code.code }@@ -113,9 +163,11 @@ RSpec.describe SessionController dosignup_token = response.parsed_body["signup_token"]expect(signup_token).to be_present- expect(verification_request).to have_been_requested.once+ expect(verification_request).not_to have_been_requestedexpect(login_code.reload.consumed_at).to be_nil+ post "/captcha/hcaptcha/create.json", params: { token: "captcha-token" }+expect {post "/session/login-code/verify.json",params: account_details.merge(signup_token: signup_token)@@ -125,11 +177,9 @@ RSpec.describe SessionController doexpect(verification_request).to have_been_requested.onceend- it "requires CAPTCHA on the final request when the continuation has no CAPTCHA proof" do- SiteSetting.discourse_captcha_enabled = false+ it "requires valid CAPTCHA on the final request before creating the approval account" dopost "/session/login-code/verify.json", params: { email:, code: login_code.code }signup_token = response.parsed_body["signup_token"]- SiteSetting.discourse_captcha_enabled = trueexpect {post "/session/login-code/verify.json",@@ -190,6 +240,7 @@ RSpec.describe SessionController doparams: {email:,code:,+ username: "chosen_username",user_fields: {user_field.id.to_s => "Developer",},diff --git a/plugins/discourse-captcha/spec/system/page_objects/components/captcha.rb b/plugins/discourse-captcha/spec/system/page_objects/components/captcha.rbindex 176c872589e..02c730ce8a9 100644--- a/plugins/discourse-captcha/spec/system/page_objects/components/captcha.rb+++ b/plugins/discourse-captcha/spec/system/page_objects/components/captcha.rb@@ -3,6 +3,12 @@module PageObjectsmodule Componentsclass Captcha < PageObjects::Components::Base+ def complete_hcaptcha+ within_frame(find("#h-captcha-field iframe")) { find("#checkbox").click }+ expect(page).to have_field("h-captcha-response", with: /.+/, visible: :all)+ self+ end+def has_hcaptcha_container?page.has_css?("#h-captcha-field")enddiff --git a/plugins/discourse-captcha/spec/system/signup_with_captcha_spec.rb b/plugins/discourse-captcha/spec/system/signup_with_captcha_spec.rbindex 391ae04f8c3..2f6fa372c59 100644--- a/plugins/discourse-captcha/spec/system/signup_with_captcha_spec.rb+++ b/plugins/discourse-captcha/spec/system/signup_with_captcha_spec.rb@@ -1,7 +1,9 @@# frozen_string_literal: trueRSpec.describe "Signup with captcha" do+ include ThemeScreenshotMarkerlet(:signup_page) { PageObjects::Pages::Signup.new }+ let(:code_signup) { PageObjects::Pages::CodeSignup.new }let(:captcha) { PageObjects::Components::Captcha.new }before do@@ -35,14 +37,25 @@ RSpec.describe "Signup with captcha" doendcontext "with code-based signup" do- before { SiteSetting.enable_local_logins_via_code = true }+ before do+ SiteSetting.enable_local_logins_via_code = true+ Jobs.run_immediately!+ end- it "displays the hCaptcha widget after requesting a signup code" do+ it "shows the hCaptcha widget when choosing a username after email verification" dosignup_page.openfind(".code-login-form__email-step input[type='email']").fill_in(with: "[email protected]")find(".code-login-form__continue").click- expect(captcha).to have_hcaptcha_container+ expect(page).to have_css(".code-login-form__code-step")+ expect(captcha).to have_no_hcaptcha_container++ code = ActionMailer::Base.deliveries.last.subject[/(\d{6})/, 1]+ find(".d-otp-input").fill_in(with: code)++ expect(page).to have_css(".code-login-form__signup-details-step")+ expect(captcha).to have_hcaptcha_widget+ screenshot_marker(label: "deferred-signup-captcha", only: :desktop)endend@@ -55,6 +68,41 @@ RSpec.describe "Signup with captcha" doendend+ it "lets the user complete CAPTCHA and retry signup for approval" do+ SiteSetting.enable_local_logins_via_email = true+ SiteSetting.enable_local_logins_via_code = true+ SiteSetting.must_approve_users = true+ Jobs.run_immediately!+ stub_request(:post, "https://hcaptcha.com/siteverify").to_return(+ status: 200,+ body: { success: true }.to_json,+ headers: {+ "Content-Type" => "application/json",+ },+ )++ code_signup.open.submit_email("[email protected]")+ wait_for { ActionMailer::Base.deliveries.any? }+ code = ActionMailer::Base.deliveries.last.subject[/(\d{6})/, 1]+ code_signup.submit_code(code)++ expect(code_signup).to have_account_details+ expect(captcha).to have_hcaptcha_widget+ code_signup.fill_username("approval-user")+ screenshot_marker(label: "approval-signup-captcha", only: :desktop)++ code_signup.submit_for_approval++ expect(code_signup).to have_error(I18n.t("js.discourse_captcha.missing_token"))+ expect(code_signup).to have_username("approval-user")+ expect(page).to have_current_path("/signup")++ captcha.complete_hcaptcha+ code_signup.submit_for_approval++ expect(code_signup).to have_pending_approval+ end+context "when submitting signup without completing captcha" doit "shows error message when captcha is not completed" dosignup_pagediff --git a/spec/integration/archive_mode_spec.rb b/spec/integration/archive_mode_spec.rbindex 760c2a3ce4f..23463ae2ffa 100644--- a/spec/integration/archive_mode_spec.rb+++ b/spec/integration/archive_mode_spec.rb@@ -118,6 +118,7 @@ RSpec.describe "Site archived" doexpect doUser::Action::CreateFromVerifiedEmail.call(email: "[email protected]",+ username: "new-code-user",ip_address: "127.0.0.1",)end.to raise_error(Discourse::SiteArchived)diff --git a/spec/lib/random_username_generator_spec.rb b/spec/lib/random_username_generator_spec.rbindex b273affc4f9..a37f022dbcc 100644--- a/spec/lib/random_username_generator_spec.rb+++ b/spec/lib/random_username_generator_spec.rb@@ -2,6 +2,8 @@RSpec.describe RandomUsernameGenerator dodescribe ".generate" do+ before { SiteSetting.enable_random_usernames = true }+it "returns a valid, available username built from the word lists and a number" dousername = described_class.generatediff --git a/spec/requests/session_controller_spec.rb b/spec/requests/session_controller_spec.rbindex c62dab29300..cbf921781ff 100644--- a/spec/requests/session_controller_spec.rb+++ b/spec/requests/session_controller_spec.rb@@ -901,7 +901,12 @@ RSpec.describe SessionController donew_code = EmailLoginCode.generate!(email: new_email)expect do- post "/session/login-code/verify.json", params: { email: new_email, code: new_code.code }+ post "/session/login-code/verify.json",+ params: {+ email: new_email,+ code: new_code.code,+ username: "archived-new-user",+ }end.not_to change { User.count }expect(response.status).to eq(503)@@ -933,6 +938,7 @@ RSpec.describe SessionController doinvite_key: invite.invite_key,email: "[email protected]",code:,+ username: "invited-person",}invited_user = User.find_by_email(invite.email)@@ -948,6 +954,28 @@ RSpec.describe SessionController doexpect(login_code.reload.consumed_at).to be_presentend+ it "keeps the invite and code available until a username is chosen" do+ post "/session/login-code/verify.json", params: { invite_key: invite.invite_key, code: }++ expect(response.status).to eq(200)+ expect(response.parsed_body["username_required"]).to eq(true)+ expect(User.find_by_email(invite.email)).to be_nil+ expect(session[:current_user_id]).to be_nil+ expect(invite.reload).not_to be_redeemed+ expect(login_code.reload.consumed_at).to be_nil+ end++ it "returns the invitee trust level for the deferred avatar selector" do+ SiteSetting.default_trust_level = 0+ SiteSetting.default_invitee_trust_level = 2++ post "/session/login-code/verify.json", params: { invite_key: invite.invite_key, code: }++ expect(response.status).to eq(200)+ expect(response.parsed_body["username_required"]).to eq(true)+ expect(response.parsed_body["trust_level"]).to eq(2)+ end+it "activates an existing inactive invitee and keeps them signed in" douser.update!(email: invite.email, active: false)@@ -1099,7 +1127,12 @@ RSpec.describe SessionController doinvite.update!(topics: [Fabricate(:topic)])begin_discourse_connect_provider_handoff- post "/session/login-code/verify.json", params: { invite_key: invite.invite_key, code: }+ post "/session/login-code/verify.json",+ params: {+ invite_key: invite.invite_key,+ code:,+ username: "invited-person",+ }expect(response.status).to eq(200)expect(response.parsed_body["account_created"]).to eq(true)@@ -1172,7 +1205,9 @@ RSpec.describe SessionController dousername:,}- expect(response.parsed_body["error"]).to include(I18n.t("login.reserved_username")),+ expect(response.parsed_body["username_errors"]).to include(+ I18n.t("login.reserved_username"),+ ),usernameexpect(User.find_by_email("[email protected]")).to be_nilexpect(ReviewableUser.count).to eq(0)@@ -1230,7 +1265,7 @@ RSpec.describe SessionController dosignup_token = response.parsed_body["signup_token"]expect(response.status).to eq(200)expect(response.parsed_body["signup_details_required"]).to eq(true)- expect(response.parsed_body["username"]).to be_present+ expect(response.parsed_body["username"]).to be_nilexpect(signup_token).to be_presentexpect(User.find_by_email("[email protected]")).to be_nilexpect(session[:current_user_id]).to be_nil@@ -1369,7 +1404,12 @@ RSpec.describe SessionController doSiteSetting.must_approve_users = trueSiteSetting.auto_approve_email_domains = "example.com"- post "/session/login-code/verify.json", params: { email: " [email protected] ", code: }+ post "/session/login-code/verify.json",+ params: {+ email: " [email protected] ",+ code:,+ username: "newuser",+ }new_user = User.find_by_email("[email protected]")expect(response.parsed_body["account_created"]).to eq(true)@@ -1377,71 +1417,267 @@ RSpec.describe SessionController doexpect(session[:current_user_id]).to eq(new_user.id)end- it "creates and logs in a new user" do+ it "does not allow the client to enable generated username completion" do+ post "/session/login-code/verify.json",+ params: {+ email: "[email protected]",+ code:,+ generated_username: true,+ }++ expect(response.parsed_body["username_required"]).to eq(true)+ expect(response.parsed_body["generated_username"]).to eq(false)+ expect(+ request.server_session[SessionController::GENERATED_USERNAME_SIGNUP_INDEX_KEY],+ ).to be_nil+ expect(User.find_by_email("[email protected]")).to be_nil+ expect(login_code.reload.consumed_at).to be_nil+ end++ it "rejects invalid generated candidates and falls back to manual selection after bounded retries" do+ plugin_instance = Plugin::Instance.new+ modifier = proc { |_, _, _, _, _| :generated }+ plugin_instance.register_modifier(:email_login_code_username_mode, &modifier)+ UserNameSuggester.stubs(:suggest).returns("account-created")+ RandomUsernameGenerator+ .expects(:generate)+ .times(4)+ .returns("moderator", "account-created", "admin", "account-created")+post "/session/login-code/verify.json", params: { email: "[email protected]", code: }- expect(response.status).to eq(200)+ expect(+ response.parsed_body.slice("username_required", "generated_username", "username"),+ ).to eq("username_required" => true, "generated_username" => false, "username" => nil)+ expect(login_code.reload.consumed_at).to be_nil+ ensure+ if plugin_instance && modifier+ DiscoursePluginRegistry.unregister_modifier(+ plugin_instance,+ :email_login_code_username_mode,+ &modifier+ )+ end+ end- new_user = User.find_by_email("[email protected]")- expect(new_user).to be_active- expect(session[:current_user_id]).to eq(new_user.id)+ it "returns a fresh valid candidate when a generated username becomes route-conflicting" do+ plugin_instance = Plugin::Instance.new+ modifier = proc { |_, _, _, _, _| :generated }+ plugin_instance.register_modifier(:email_login_code_username_mode, &modifier)+ UserNameSuggester.stubs(:suggest).returns("first-candidate", "second-candidate")+ UsernameValidator+ .stubs(:clashing_with_existing_route?)+ .with("first-candidate")+ .returns(false, true)+ UsernameValidator+ .stubs(:clashing_with_existing_route?)+ .with("second-candidate")+ .returns(false)++ post "/session/login-code/verify.json", params: { email: "[email protected]", code: }+ post "/session/login-code/verify.json",+ params: {+ email: "[email protected]",+ code:,+ username: "first-candidate",+ }++ expect(+ response.parsed_body.slice("username_required", "generated_username", "username"),+ ).to eq(+ "username_required" => true,+ "generated_username" => true,+ "username" => "second-candidate",+ )+ expect(login_code.reload.consumed_at).to be_nil+ ensure+ if plugin_instance && modifier+ DiscoursePluginRegistry.unregister_modifier(+ plugin_instance,+ :email_login_code_username_mode,+ &modifier+ )+ endend- it "returns the flags the account-ready step needs" do+ it "returns a fresh generated candidate after a collision without consuming the code" do+ plugin_instance = Plugin::Instance.new+ modifier = proc { |_, _, _| :generated }+ plugin_instance.register_modifier(:email_login_code_username_mode, &modifier)+ UserNameSuggester.stubs(:suggest).returns("first-candidate", "second-candidate")+post "/session/login-code/verify.json", params: { email: "[email protected]", code: }+ Fabricate(:user, username: response.parsed_body["username"])- body = response.parsed_body- expect(body["account_created"]).to eq(true)- expect(body["can_edit_username"]).to eq(true)- # The avatar picker needs the upload permission, which isn't on- # 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")+ post "/session/login-code/verify.json",+ params: {+ email: "[email protected]",+ code:,+ username: "first-candidate",+ }++ expect(+ response.parsed_body.slice("username_required", "generated_username", "username"),+ ).to eq(+ "username_required" => true,+ "generated_username" => true,+ "username" => "second-candidate",+ )+ expect(User.find_by_email("[email protected]")).to be_nil+ expect(login_code.reload.consumed_at).to be_nil++ post "/session/login-code/verify.json",+ params: {+ email: "[email protected]",+ code:,+ username: "second-candidate",+ generated_username: false,+ }++ expect(response.parsed_body["account_created"]).to eq(true)+ expect(User.find_by_email("[email protected]").username).to eq("second-candidate")+ expect(+ request.server_session[SessionController::GENERATED_USERNAME_SIGNUP_INDEX_KEY],+ ).to be_nil+ expect(+ request.server_session[+ "#{SessionController::GENERATED_USERNAME_SIGNUP_KEY_PREFIX}#{login_code.id}"+ ],+ ).to be_nil+ ensure+ if plugin_instance && modifier+ DiscoursePluginRegistry.unregister_modifier(+ plugin_instance,+ :email_login_code_username_mode,+ &modifier+ )+ endend- it "defers a pending DiscourseConnect provider handoff to the account-ready step" do- payload = begin_discourse_connect_provider_handoff+ it "clears generated proofs when a different existing account authenticates" do+ plugin_instance = Plugin::Instance.new+ modifier = proc { |_, _, _, _, _| :generated }+ plugin_instance.register_modifier(:email_login_code_username_mode, &modifier)post "/session/login-code/verify.json", params: { email: "[email protected]", code: }+ proof_key = "#{SessionController::GENERATED_USERNAME_SIGNUP_KEY_PREFIX}#{login_code.id}"+ expect(request.server_session[proof_key]).to be_present- body = response.parsed_body- expect(body["account_created"]).to eq(true)- expect(body["redirect_url"]).to end_with("/session/sso_provider?#{payload}")- # Consumed, so a later login isn't sent through this handoff.- expect(cookies[:sso_payload]).to be_blank+ existing_user = Fabricate(:user, email: "[email protected]")+ existing_code = EmailLoginCode.generate!(email: existing_user.email)+ post "/session/login-code/verify.json",+ params: {+ email: existing_user.email,+ code: existing_code.code,+ }++ expect(session[:current_user_id]).to eq(existing_user.id)+ expect(request.server_session[proof_key]).to be_nil+ expect(+ request.server_session[SessionController::GENERATED_USERNAME_SIGNUP_INDEX_KEY],+ ).to be_nil+ ensure+ if plugin_instance && modifier+ DiscoursePluginRegistry.unregister_modifier(+ plugin_instance,+ :email_login_code_username_mode,+ &modifier+ )+ endend- 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+ it "returns the default trust level for the deferred avatar selector" do+ SiteSetting.default_trust_level = 1+ SiteSetting.default_invitee_trust_level = 2++ post "/session/login-code/verify.json", params: { email: "[email protected]", code: }++ expect(response.status).to eq(200)+ expect(response.parsed_body["username_required"]).to eq(true)+ expect(response.parsed_body["trust_level"]).to eq(1)+ end++ it "waits for username selection before creating or authenticating an account" do+ User.set_callback(:create, :after, :ensure_in_trust_level_group)post "/session/login-code/verify.json", params: { email: "[email protected]", code: }+ expect(response.status).to eq(200)+ expect(response.parsed_body["username_required"]).to eq(true)+ expect(response.parsed_body["username"]).to be_nil+ expect(response.parsed_body["avatar_template"]).to be_nil+ expect(User.find_by_email("[email protected]")).to be_nil+ expect(session[:current_user_id]).to be_nil+ expect(login_code.reload.consumed_at).to be_nil++ post "/session/login-code/verify.json",+ params: {+ email: "[email protected]",+ code:,+ username: "chosen-name",+ }++ expect(response.status).to eq(200)+ expect(response.parsed_body["account_created"]).to eq(true)+ expect(response.parsed_body["can_upload_avatar"]).to eq(true)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/)+ expect(new_user).to be_active+ expect(new_user.username).to eq("chosen-name")+ expect(session[:current_user_id]).to eq(new_user.id)+ ensure+ User.skip_callback(:create, :after, :ensure_in_trust_level_group)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+ it "rejects a taken username without creating an account or consuming the code" do+ Fabricate(:user, username: "chosen-name")++ post "/session/login-code/verify.json",+ params: {+ email: "[email protected]",+ code:,+ username: "chosen-name",+ }++ expect(response.status).to eq(200)+ expect(response.parsed_body["username_errors"]).to be_present+ expect(User.find_by_email("[email protected]")).to be_nil+ expect(session[:current_user_id]).to be_nil+ expect(login_code.reload.consumed_at).to be_nil+ end++ it "defers a pending DiscourseConnect provider handoff until signup is complete" do+ payload = begin_discourse_connect_provider_handoffpost "/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)+ expect(response.parsed_body["username_required"]).to eq(true)+ expect(cookies[:sso_payload]).to be_present+ expect(session[:current_user_id]).to be_nil++ post "/session/login-code/verify.json",+ params: {+ email: "[email protected]",+ code:,+ username: "chosen-name",+ }++ body = response.parsed_body+ expect(body["account_created"]).to eq(true)+ expect(body["redirect_url"]).to end_with("/session/sso_provider?#{payload}")+ expect(cookies[:sso_payload]).to be_blankend- it "flags a randomly generated username for prefill" do+ it "does not derive the username from the email when email-based suggestions are off" do+ SiteSetting.enable_random_usernames = trueSiteSetting.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)+ expect(response.parsed_body["username"]).to match(/\A[A-Z][a-z]+[A-Z][a-z]+\d+\z/)end- it "does not flag the fallback for prefill when generation is on but yields nothing" do+ it "leaves the suggestion blank when random generation yields nothing" do+ SiteSetting.enable_random_usernames = trueSiteSetting.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.@@ -1452,8 +1688,9 @@ RSpec.describe SessionController dopost "/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)+ expect(response.parsed_body["username_required"]).to eq(true)+ expect(response.parsed_body["username"]).to be_nil+ expect(User.find_by_email("[email protected]")).to be_nilendit "derives the username from the email when email-based suggestions are on" do@@ -1461,7 +1698,7 @@ RSpec.describe SessionController dopost "/session/login-code/verify.json", params: { email: "[email protected]", code: }- expect(User.find_by_email("[email protected]").username).to eq("newuser")+ expect(response.parsed_body["username"]).to eq("newuser")endit "appends a numeric suffix when the email-derived name is taken" do@@ -1470,21 +1707,20 @@ RSpec.describe SessionController dopost "/session/login-code/verify.json", params: { email: "[email protected]", code: }- expect(User.find_by_email("[email protected]").username).to eq("newuser1")+ expect(response.parsed_body["username"]).to eq("newuser1")endcontext "when the email can't produce a username suggestion" dolet(:login_code) { EmailLoginCode.generate!(email: "[email protected]") }- it "assigns a random username instead of the generic fallback" do+ it "suggests a random username instead of the generic fallback" do+ SiteSetting.enable_random_usernames = trueSiteSetting.use_email_for_username_and_name_suggestions = truepost "/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/,- )+ expect(response.parsed_body["username_required"]).to eq(true)+ expect(response.parsed_body["username"]).to match(/\A[A-Z][a-z]+[A-Z][a-z]+\d+\z/)endend@@ -1507,6 +1743,7 @@ RSpec.describe SessionController doparams: {email: "[email protected]",code:,+ username: "chosen-name",},env: {REMOTE_ADDR: ip_address,@@ -1543,6 +1780,20 @@ RSpec.describe SessionController do},}+ expect(response.parsed_body["username_required"]).to eq(true)+ expect(User.find_by_email("[email protected]")).to be_nil+ expect(login_code.reload.consumed_at).to be_nil++ post "/session/login-code/verify.json",+ params: {+ email: "[email protected]",+ code:,+ username: "chosen-name",+ user_fields: {+ user_field.id.to_s => "Dev",+ },+ }+new_user = User.find_by_email("[email protected]")expect(new_user.custom_fields["user_field_#{user_field.id}"]).to eq("Dev")expect(session[:current_user_id]).to eq(new_user.id)@@ -1553,6 +1804,7 @@ RSpec.describe SessionController doparams: {email: "[email protected]",code:,+ username: "chosen-name",user_fields: {"0" => "",},@@ -1583,6 +1835,18 @@ RSpec.describe SessionController doname: "Jane Doe",}+ expect(response.parsed_body["username_required"]).to eq(true)+ expect(User.find_by_email("[email protected]")).to be_nil+ expect(login_code.reload.consumed_at).to be_nil++ post "/session/login-code/verify.json",+ params: {+ email: "[email protected]",+ code:,+ username: "chosen-name",+ name: "Jane Doe",+ }+new_user = User.find_by_email("[email protected]")expect(new_user.name).to eq("Jane Doe")expect(session[:current_user_id]).to eq(new_user.id)@@ -1593,6 +1857,7 @@ RSpec.describe SessionController doparams: {email: "[email protected]",code:,+ username: "chosen-name",name: "a" * 256,}@@ -1607,6 +1872,7 @@ RSpec.describe SessionController doparams: {email: "[email protected]",code:,+ username: "chosen-name",name: " ",}diff --git a/spec/requests/users_controller_spec.rb b/spec/requests/users_controller_spec.rbindex 05f1777a785..1a5406a006f 100644--- a/spec/requests/users_controller_spec.rb+++ b/spec/requests/users_controller_spec.rb@@ -2237,6 +2237,39 @@ RSpec.describe UsersController doenddescribe "#check_username" do+ it "rejects anonymous checks against another account" do+ get "/u/check_username.json", params: { username: "AvailableName", for_user_id: user1.id }++ expect(response.status).to eq(403)+ end++ it "rejects checks against another account by a regular user" do+ sign_in(user1)++ get "/u/check_username.json", params: { username: "AvailableName", for_user_id: admin.id }++ expect(response.status).to eq(403)+ end++ it "allows a new account to check its own username and avatar" do+ sign_in(user1)++ get "/u/check_username.json", params: { username: user1.username, for_user_id: user1.id }++ expect(response.status).to eq(200)+ expect(response.parsed_body["available"]).to eq(true)+ expect(response.parsed_body["avatar_template"]).to eq(User.default_template(user1.username))+ end++ it "rejects account-specific checks when username editing is forbidden" do+ sign_in(user1)+ SiteSetting.username_change_period = 0++ get "/u/check_username.json", params: { username: "AvailableName", for_user_id: user1.id }++ expect(response.status).to eq(403)+ end+it "raises an error without any parameters" doget "/u/check_username.json"expect(response.status).to eq(400)@@ -2307,6 +2340,9 @@ RSpec.describe UsersController doit "returns the username's availability" doexpect(response.status).to eq(200)expect(response.parsed_body["available"]).to eq(true)+ expect(response.parsed_body["avatar_template"]).to eq(+ User.default_template(request.params[:username]),+ )endend@@ -2359,6 +2395,7 @@ RSpec.describe UsersController doexpect(response.status).to eq(200)expect(response.parsed_body["available"]).to eq(nil)expect(response.parsed_body["errors"]).to be_present+ expect(response.parsed_body).not_to have_key("avatar_template")endend@@ -2429,6 +2466,8 @@ RSpec.describe UsersController doenddescribe "#generate_random_username" do+ before { SiteSetting.enable_random_usernames = true }+it "returns a generated username" doget "/u/random-username.json"diff --git a/spec/services/email_login_code/redeem_spec.rb b/spec/services/email_login_code/redeem_spec.rbindex 4dafe353ea7..f689d75dcc9 100644--- a/spec/services/email_login_code/redeem_spec.rb+++ b/spec/services/email_login_code/redeem_spec.rb@@ -11,7 +11,8 @@ RSpec.describe EmailLoginCode::Redeem dodescribe ".call" dosubject(:result) { described_class.call(params:, **dependencies) }- let(:params) { { email:, code: } }+ let(:params) { { email:, code:, username: } }+ let(:username) { "chosen_username" }let(:dependencies) { { ip_address: "127.0.0.1" } }let(:email) { "[email protected]" }@@ -104,58 +105,6 @@ RSpec.describe EmailLoginCode::Redeem doendend- context "when the email is unknown" do- let(:email) { "[email protected]" }-- it { is_expected.to run_successfully }-- it "consumes the code" do- expect { result }.to change { login_code.reload.consumed_at }.from(nil)- end-- it "creates an active user with a confirmed email and no password" do- user = result[:user]-- expect(user).to be_active- expect(user.email).to eq(email)- expect(user).to be_email_confirmed- expect(user.password_hash).to be_nil- expect(user.registration_ip_address.to_s).to eq("127.0.0.1")- end-- it "does not derive the username from the email by default" do- expect(result[:user].username).not_to include("jane")- end-- it "derives the username from the email when email-based suggestions are enabled" do- SiteSetting.use_email_for_username_and_name_suggestions = true-- expect(result[:user].username).to eq("jane")- end-- it "leaves the name blank rather than reusing the generated username" do- expect(result[:user].name).to be_blank- end-- context "when a name is provided" do- let(:params) { { email:, code:, name: "Jane Doe" } }-- it "saves the name even though it isn't required" do- expect(result[:user].name).to eq("Jane Doe")- end- end-- it "enqueues the welcome message" do- SiteSetting.send_welcome_message = true-- expect { result }.to change {- Jobs::SendSystemMessage.jobs.count do |job|- job["args"][0]["message_type"] == "welcome_user"- end- }.by(1)- end- end-context "when required signup fields exist" dofab!(:user_field)@@ -168,7 +117,7 @@ RSpec.describe EmailLoginCode::Redeem doendcontext "when the field values are provided" do- let(:params) { { email:, code:, user_fields: { user_field.id.to_s => "Dev" } } }+ let(:params) { { email:, code:, username:, user_fields: { user_field.id.to_s => "Dev" } } }it { is_expected.to run_successfully }@@ -185,6 +134,7 @@ RSpec.describe EmailLoginCode::Redeem do{email:,code:,+ username:,user_fields: {user_field.id.to_s => "Dev",hidden_field.id.to_s => "Secret",@@ -206,7 +156,7 @@ RSpec.describe EmailLoginCode::Redeem doFabricate(:user_field, requirement: "for_all_users", show_on_signup: false)end- let(:params) { { email:, code:, user_fields: { user_field.id.to_s => "Dev" } } }+ let(:params) { { email:, code:, username:, user_fields: { user_field.id.to_s => "Dev" } } }it "does not require fields the signup form can't collect" doexpect(result).to run_successfully@@ -214,7 +164,7 @@ RSpec.describe EmailLoginCode::Redeem doendcontext "when user_fields is malformed" do- let(:params) { { email:, code:, user_fields: "not-a-hash" } }+ let(:params) { { email:, code:, username:, user_fields: "not-a-hash" } }it "fails as a missing field instead of raising" doexpect { result }.not_to raise_error@@ -243,13 +193,13 @@ RSpec.describe EmailLoginCode::Redeem doendcontext "when the name is only whitespace" do- let(:params) { { email:, code:, name: " " } }+ let(:params) { { email:, code:, username:, name: " " } }it { is_expected.to fail_a_policy(:required_full_name_provided) }endcontext "when a name is provided" do- let(:params) { { email:, code:, name: "Jane Doe" } }+ let(:params) { { email:, code:, username:, name: "Jane Doe" } }it { is_expected.to run_successfully }@@ -267,6 +217,128 @@ RSpec.describe EmailLoginCode::Redeem doendend+ context "when the username is missing" do+ before { params.delete(:username) }++ it "requires a username without consuming the code or creating an account" do+ expect(result).to fail_a_policy(:required_username_provided)+ expect(login_code.reload.consumed_at).to be_nil+ expect(User.find_by_email(email)).to be_nil+ end+ end++ context "when the username is only whitespace" do+ let(:username) { " " }++ it "requires a username without consuming the code or creating an account" do+ expect(result).to fail_a_policy(:required_username_provided)+ expect(login_code.reload.consumed_at).to be_nil+ expect(User.find_by_email(email)).to be_nil+ end+ end++ context "when the username is reserved" do+ let(:username) { "reserved_name" }++ before { SiteSetting.reserved_usernames = "reserved_name" }++ it "rejects the username without consuming the code or creating an account" do+ expect(result).to fail_a_policy(:username_allowed)+ expect(login_code.reload.consumed_at).to be_nil+ expect(User.find_by_email(email)).to be_nil+ end+ end++ context "when the username has surrounding whitespace" do+ let(:username) { " chosen_username " }++ it "creates the account with the trimmed username" do+ expect(result).to run_successfully+ expect(result[:user].username).to eq(username.strip)+ end+ end++ context "when the username is invalid" do+ let(:username) { "invalid username" }++ it "rejects the username without consuming the code or creating an account" do+ expect(result).to fail_with_an_invalid_model(:user)+ expect(login_code.reload.consumed_at).to be_nil+ expect(User.find_by_email(email)).to be_nil+ end+ end++ context "when the username is already taken" do+ fab!(:other_user) { Fabricate(:user, username: "taken_username") }++ let(:username) { "taken_username" }++ it "rejects the username without consuming the code or creating an account" do+ expect(result).to fail_with_an_invalid_model(:user)+ expect(login_code.reload.consumed_at).to be_nil+ expect(User.find_by_email(email)).to be_nil+ end+ end++ context "when the email is unknown" do+ let(:email) { "[email protected]" }++ it { is_expected.to run_successfully }++ it "consumes the code" do+ expect { result }.to change { login_code.reload.consumed_at }.from(nil)+ end++ it "creates an active user with a confirmed email and no password" do+ user = result[:user]++ expect(user).to be_active+ expect(user.email).to eq(email)+ expect(user).to be_email_confirmed+ expect(user.password_hash).to be_nil+ expect(user.registration_ip_address.to_s).to eq("127.0.0.1")+ end++ it "uses the chosen username and leaves the optional name blank" do+ expect(result[:user].username).to eq(username)+ expect(result[:user].name).to be_blank+ end++ context "when a name is provided" do+ let(:params) { { email:, code:, username:, name: "Jane Doe" } }++ it "saves the name even though it isn't required" do+ expect(result[:user].name).to eq("Jane Doe")+ end+ end++ it "enqueues the welcome message" do+ SiteSetting.send_welcome_message = true++ expect { result }.to change {+ Jobs::SendSystemMessage.jobs.count do |job|+ job["args"][0]["message_type"] == "welcome_user"+ end+ }.by(1)+ end+ end++ context "when a staged user chooses an invalid username" do+ fab!(:staged_user) { Fabricate(:staged, email: "[email protected]", active: false) }++ let(:email) { staged_user.email }+ let(:username) { "invalid username" }++ it "preserves the staged account and code for another attempt" do+ expect { result }.to not_change { staged_user.reload.username }.and(+ not_change { staged_user.reload.staged },+ )+ expect(result).to fail_with_an_invalid_model(:user)+ expect(staged_user.reload).not_to be_active+ expect(login_code.reload.consumed_at).to be_nil+ end+ end+context "when the email belongs to a staged user" dofab!(:staged_user) { Fabricate(:staged, active: false) }@@ -305,6 +377,7 @@ RSpec.describe EmailLoginCode::Redeem dofab!(:user)let(:email) { user.email }+ let(:username) { nil }it { is_expected.to run_successfully }@@ -320,6 +393,13 @@ RSpec.describe EmailLoginCode::Redeem doendend+ it "ignores a supplied username when logging in" do+ params[:username] = "replacement_name"++ expect { result }.not_to change { user.reload.username }+ expect(result).to run_successfully+ end+it "returns the user and consumes the code" doexpect(result[:user]).to eq(user)expect(login_code.reload.consumed_at).to be_presentdiff --git a/spec/services/invite/redeem_with_email_code_spec.rb b/spec/services/invite/redeem_with_email_code_spec.rbindex d04898cbc76..4f6b156a554 100644--- a/spec/services/invite/redeem_with_email_code_spec.rb+++ b/spec/services/invite/redeem_with_email_code_spec.rb@@ -14,7 +14,8 @@ RSpec.describe Invite::RedeemWithEmailCode dofab!(:invite) { Fabricate(:invite, email: "[email protected]") }- let(:params) { { invite_key: invite.invite_key, email:, code: } }+ let(:params) { { invite_key: invite.invite_key, email:, code:, username: } }+ let(:username) { "chosen_username" }let(:dependencies) { { ip_address: "127.0.0.1", server_session: {} } }let(:email) { invite.email }let(:login_code) { EmailLoginCode.generate!(email:) }@@ -27,7 +28,7 @@ RSpec.describe Invite::RedeemWithEmailCode doendcontext "when the invite cannot be found" do- let(:params) { { invite_key: "missing", email:, code: } }+ let(:params) { { invite_key: "missing", email:, code:, username: } }it { is_expected.to fail_to_find_a_model(:invite) }end@@ -127,6 +128,7 @@ RSpec.describe Invite::RedeemWithEmailCode doinvite_key: invite.invite_key,email:,code:,+ username:,user_fields: {user_field.id.to_s => "Engineer",},@@ -153,7 +155,9 @@ RSpec.describe Invite::RedeemWithEmailCode doendcontext "when a required full name is provided" do- let(:params) { { invite_key: invite.invite_key, email:, code:, name: "Invited Person" } }+ let(:params) do+ { invite_key: invite.invite_key, email:, code:, username:, name: "Invited Person" }+ endbefore { SiteSetting.full_name_requirement = "required_at_signup" }@@ -164,6 +168,102 @@ RSpec.describe Invite::RedeemWithEmailCode doendend+ context "when the username is missing" do+ before { params.delete(:username) }++ it "requires a username without consuming the code or creating an account" do+ expect(result).to fail_a_policy(:required_username_provided)+ expect(login_code.reload.consumed_at).to be_nil+ expect(User.find_by_email(email)).to be_nil+ expect(invite.reload.redemption_count).to eq(0)+ end+ end++ context "when the username is only whitespace" do+ let(:username) { " " }++ it "requires a username without consuming the code or creating an account" do+ expect(result).to fail_a_policy(:required_username_provided)+ expect(login_code.reload.consumed_at).to be_nil+ expect(User.find_by_email(email)).to be_nil+ expect(invite.reload.redemption_count).to eq(0)+ end+ end++ context "when the username is reserved" do+ let(:username) { "reserved_name" }++ before { SiteSetting.reserved_usernames = "reserved_name" }++ it "rejects the username without consuming the code or creating an account" do+ expect(result).to fail_a_policy(:username_allowed)+ expect(login_code.reload.consumed_at).to be_nil+ expect(User.find_by_email(email)).to be_nil+ expect(invite.reload.redemption_count).to eq(0)+ end+ end++ context "when the username conflicts with a route" do+ let(:username) { "ACCOUNT-CREATED" }++ it "rejects the username without consuming the code or redeeming the invite" do+ expect(result).to fail_a_policy(:username_allowed)+ expect(login_code.reload.consumed_at).to be_nil+ expect(User.find_by_email(email)).to be_nil+ expect(invite.reload.redemption_count).to eq(0)+ end+ end++ context "when the username has surrounding whitespace" do+ let(:username) { " chosen_username " }++ it "creates the account with the trimmed username" do+ expect(result).to run_successfully+ expect(result[:user].username).to eq(username.strip)+ end+ end++ context "when the username is invalid" do+ let(:username) { "invalid username" }++ it "rejects the username without consuming the code or creating an account" do+ expect(result).to fail_to_find_a_model(:user)+ expect(login_code.reload.consumed_at).to be_nil+ expect(User.find_by_email(email)).to be_nil+ expect(invite.reload.redemption_count).to eq(0)+ end+ end++ context "when the username is already taken" do+ fab!(:other_user) { Fabricate(:user, username: "taken_username") }++ let(:username) { "taken_username" }++ it "rejects the username without consuming the code or creating an account" do+ expect(result).to fail_to_find_a_model(:user)+ expect(login_code.reload.consumed_at).to be_nil+ expect(User.find_by_email(email)).to be_nil+ expect(invite.reload.redemption_count).to eq(0)+ end+ end++ context "when a staged user chooses an invalid username" do+ fab!(:staged_user) { Fabricate(:staged, email: "[email protected]", active: false) }++ let(:email) { staged_user.email }+ let(:username) { "invalid username" }++ it "preserves the staged account and code for another attempt" do+ expect { result }.to not_change { staged_user.reload.username }.and(+ not_change { staged_user.reload.staged },+ )+ expect(result).to fail_to_find_a_model(:user)+ expect(staged_user.reload).not_to be_active+ expect(login_code.reload.consumed_at).to be_nil+ expect(invite.reload.redemption_count).to eq(0)+ end+ end+context "when a new user redeems the invite" doit { is_expected.to run_successfully }@@ -179,6 +279,7 @@ RSpec.describe Invite::RedeemWithEmailCode doexpect(user).to be_activeexpect(user).to be_email_confirmedexpect(user.email).to eq(email)+ expect(user.username).to eq(username)expect(user.user_password).to be_nilexpect(user.registration_ip_address.to_s).to eq(dependencies[:ip_address])end@@ -193,6 +294,15 @@ RSpec.describe Invite::RedeemWithEmailCode docontext "when an existing user redeems the invite" dofab!(:existing_user) { Fabricate(:user, email: "[email protected]") }+ let(:username) { nil }++ it "ignores a supplied username when redeeming for an existing user" do+ params[:username] = "replacement_name"++ expect { result }.not_to change { existing_user.reload.username }+ expect(result).to run_successfully+ end+it { is_expected.to run_successfully }it "returns the existing user and consumes the code" dodiff --git a/spec/system/code_login_spec.rb b/spec/system/code_login_spec.rbindex 594e0823155..4bf6f8c6660 100644--- a/spec/system/code_login_spec.rb+++ b/spec/system/code_login_spec.rb@@ -132,7 +132,13 @@ describe "Login via email code" dofind(".code-login-form__user-fields-step .code-login-form__verify").click- expect(page).to have_css(".code-login-form__complete-step")+ expect(page).to have_css(".code-login-form__signup-details-step")++ fill_in("code-login-username", with: "new-person")+ expect(page).to have_no_css(".code-login-form__continue-to-site[disabled]")+ find(".code-login-form__continue-to-site").click++ expect(page).to have_css(".header-dropdown-toggle.current-user")user = User.find_by_email(new_email)expect(user.custom_fields["user_field_#{user_field.id}"]).to eq("true")diff --git a/spec/system/code_signup_spec.rb b/spec/system/code_signup_spec.rbindex d625f794d6e..25f0dfda812 100644--- a/spec/system/code_signup_spec.rb+++ b/spec/system/code_signup_spec.rb@@ -38,6 +38,8 @@ describe "Sign up via email code" doendit "creates a passwordless account, picks a username, and logs in" do+ SiteSetting.enable_random_usernames = true+open_code_signupexpect(page).to have_css(".code-login-form__email-step")expect(page).to have_content(I18n.t("js.code_login.signup_title"))@@ -48,11 +50,9 @@ describe "Sign up via email code" dofill_code(latest_emailed_code("[email protected]"))- expect(page).to have_css(".code-login-form__complete-step")+ expect(page).to have_css(".code-login-form__signup-details-step")screenshot_marker(label: "code-signup-complete-step")- # 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").valueexpect(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]")@@ -94,9 +94,9 @@ describe "Sign up via email code" dofill_code(latest_emailed_code("[email protected]"))- expect(page).to have_css(".code-login-form__complete-step")+ expect(page).to have_css(".code-login-form__signup-details-step")expect(page).to have_css(".login-welcome-header", count: 1)- expect(page).to have_css(".login-title", text: I18n.t("js.code_login.account_ready_title"))+ expect(page).to have_css(".login-title", text: I18n.t("js.code_login.signup_details_title"))expect(page).to have_no_css(".code-login-form__title")end@@ -107,7 +107,7 @@ describe "Sign up via email code" dosubmit_email("[email protected]")fill_code(latest_emailed_code("[email protected]"))- expect(page).to have_css(".code-login-form__complete-step")+ expect(page).to have_css(".code-login-form__signup-details-step")fill_in("code-login-username", with: "takenname")expect(page).to have_css(".code-login-form__error", text: "username")@@ -121,56 +121,90 @@ describe "Sign up via email code" dosubmit_email("[email protected]")fill_code(latest_emailed_code("[email protected]"))- expect(page).to have_css(".code-login-form__complete-step")+ expect(page).to have_css(".code-login-form__signup-details-step")expect(find("#code-login-username").value).to eq("jane")end- it "makes the user pick a username when random usernames are disabled" do+ it "makes the user pick a username by default" doSiteSetting.use_email_for_username_and_name_suggestions = false- SiteSetting.enable_random_usernames = falseopen_code_signupsubmit_email("[email protected]")fill_code(latest_emailed_code("[email protected]"))- expect(page).to have_css(".code-login-form__complete-step")+ expect(page).to have_css(".code-login-form__signup-details-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]")+ expect(page).to have_css(".code-login-form__avatar .d-icon-user")+ expect(page).to have_no_css(".code-login-form__avatar img")+ screenshot_marker(label: "deferred-signup-neutral-avatar")pick_username("no-random")+ expect(page).to have_css(".code-login-form__avatar img")+ expect(page).to have_no_css(".code-login-form__avatar .d-icon-user")find(".code-login-form__continue-to-site").clickexpect(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" do+ it "lets the user choose their initial username when later changes are disabled" doSiteSetting.username_change_period = 0open_code_signupsubmit_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-username")+ expect(page).to have_css(".code-login-form__signup-details-step")+ pick_username("locked-name")find(".code-login-form__continue-to-site").clickexpect(page).to have_css(".header-dropdown-toggle.current-user")- expect(User.find_by_email("[email protected]")).to be_present+ expect(User.find_by_email("[email protected]").username).to eq("locked-name")+ end++ it "stays logged out when the user leaves without choosing a username" do+ open_code_signup+ submit_email("[email protected]")+ fill_code(latest_emailed_code("[email protected]"))++ expect(page).to have_css(".code-login-form__signup-details-step")+ expect(page).to have_css(".code-login-form__continue-to-site[disabled]")++ visit("/")++ expect(page).to have_no_css(".header-dropdown-toggle.current-user")+ expect(page).to have_css(".login-button")end- it "opens the avatar picker before continuing" do+ it "previews a chosen avatar and applies it after creating the account" do+ User.set_callback(:create, :after, :ensure_in_trust_level_group)+open_code_signupsubmit_email("[email protected]")fill_code(latest_emailed_code("[email protected]"))- expect(page).to have_css(".code-login-form__complete-step")+ expect(page).to have_css(".code-login-form__signup-details-step")find(".code-login-form__avatar").click+ attach_file(+ "deferred-avatar-upload",+ File.absolute_path(file_from_fixtures("logo.jpg")),+ make_visible: true,+ )++ expect(page).to have_css(".avatar-choice--upload img[src^='blob:']")+ screenshot_marker(label: "deferred-signup-avatar-picker")+ find(".avatar-selector-modal .btn-primary").click++ expect(page).to have_css(".code-login-form__avatar img[src^='blob:']")+ pick_username("avatar-person")+ screenshot_marker(label: "deferred-signup-avatar-preview")+ find(".code-login-form__continue-to-site").click- expect(page).to have_css(".avatar-selector-modal")+ expect(page).to have_css(".header-dropdown-toggle.current-user img[src*='/user_avatar/']")+ ensure+ User.skip_callback(:create, :after, :ensure_in_trust_level_group)endit "shows an error for an incorrect code" do@@ -203,6 +237,7 @@ describe "Sign up via email code" doendit "collects account details before approval and requires a fresh code afterward" do+ SiteSetting.enable_random_usernames = trueSiteSetting.login_required = trueSiteSetting.must_approve_users = trueSiteSetting.full_name_requirement = "required_at_signup"@@ -326,6 +361,8 @@ describe "Sign up via email code" doexpect(page).to have_field("new-account-password", type: "password")screenshot_marker(label: "code-signup-account-details-password-expanded")+ pick_username("password-approval")+fill_in("new-account-password", with: "short")expect(page).to have_css(".code-login-form__submit-approval[disabled]")@@ -380,7 +417,7 @@ describe "Sign up via email code" dofind(".user-field-occupation input").fill_in(with: "Dev")find(".code-login-form__user-fields-step .code-login-form__verify").click- expect(page).to have_css(".code-login-form__complete-step")+ expect(page).to have_css(".code-login-form__signup-details-step")pick_username("fields-person")find(".code-login-form__continue-to-site").click@@ -413,7 +450,11 @@ describe "Sign up via email code" dofill_in("code-login-name", with: "Jane Doe")find(".code-login-form__user-fields-step .code-login-form__verify").click- expect(page).to have_css(".code-login-form__complete-step")+ expect(page).to have_css(".code-login-form__signup-details-step")+ pick_username("named-person")+ 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]").name).to eq("Jane Doe")endenddiff --git a/spec/system/discourse_connect_provider_spec.rb b/spec/system/discourse_connect_provider_spec.rbindex 9ec0870282a..b6eed4eca5f 100644--- a/spec/system/discourse_connect_provider_spec.rb+++ b/spec/system/discourse_connect_provider_spec.rb@@ -56,7 +56,7 @@ describe "Discourse Connect Provider" do# The handoff waits here rather than redirecting as soon as the session# exists, so the generated placeholder username can be replaced.- expect(page).to have_css(".code-login-form__complete-step")+ expect(page).to have_css(".code-login-form__signup-details-step")find("#code-login-username").fill_in(with: "janedoe")expect(page).to have_no_css(".code-login-form__continue-to-site[disabled]")find(".code-login-form__continue-to-site").clickdiff --git a/spec/system/page_objects/pages/code_signup.rb b/spec/system/page_objects/pages/code_signup.rbnew file mode 100644index 00000000000..b0fa930e4c4--- /dev/null+++ b/spec/system/page_objects/pages/code_signup.rb@@ -0,0 +1,49 @@+# frozen_string_literal: true++module PageObjects+ module Pages+ class CodeSignup < PageObjects::Pages::Base+ def open+ visit("/signup")+ self+ end++ def submit_email(email)+ find(".code-login-form__email-step input[type='email']").fill_in(with: email)+ find(".code-login-form__continue").click+ self+ end++ def submit_code(code)+ find(".d-otp-input").fill_in(with: code)+ self+ end++ def fill_username(username)+ fill_in("code-login-username", with: username)+ self+ end++ def submit_for_approval+ find(".code-login-form__submit-approval:not([disabled])").click+ self+ end++ def has_account_details?+ has_css?(".code-login-form__account-details-step")+ end++ def has_username?(username)+ has_field?("code-login-username", with: username)+ end++ def has_error?(message)+ has_css?(".code-login-form__error", text: message)+ end++ def has_pending_approval?+ has_css?(".code-login-form__pending-approval-step")+ end+ end+ end+enddiff --git a/spec/system/page_objects/pages/invite_form.rb b/spec/system/page_objects/pages/invite_form.rbindex 37ed6a6126f..2849f0671d2 100644--- a/spec/system/page_objects/pages/invite_form.rb+++ b/spec/system/page_objects/pages/invite_form.rb@@ -70,7 +70,7 @@ module PageObjectsenddef has_account_ready_step?- has_css?(".code-login-form__complete-step")+ has_css?(".code-login-form__signup-details-step")enddef choose_code_signup_username(username)