Skip to content

A platform for community discussion. Free, open, simple.

Revert "FIX: Require a username before creating email-code accounts (#43783)" (#43838)

Keegan George64358ac0d0c1
diff --git a/app/assets/stylesheets/common/base/user.scss b/app/assets/stylesheets/common/base/user.scss
index 20ac5772934..ffb86086bc9 100644
--- a/app/assets/stylesheets/common/base/user.scss
+++ b/app/assets/stylesheets/common/base/user.scss
@@ -565,23 +565,6 @@
.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.scss
index b1c308d48ae..bdaced03143 100644
--- a/app/assets/stylesheets/common/login/code-login-form.scss
+++ b/app/assets/stylesheets/common/login/code-login-form.scss
@@ -153,22 +153,6 @@
}
}
- &__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.rb
index 1e061f25f57..c728b64cde4 100644
--- a/app/controllers/session_controller.rb
+++ b/app/controllers/session_controller.rb
@@ -985,7 +985,7 @@ class SessionController < ApplicationController
render json: login_code_registration_ip_limit_error
end
on_failed_policy(:username_allowed) do
- render json: { username_errors: [I18n.t("login.reserved_username")] }
+ render json: { error: I18n.t("login.reserved_username") }
end
on_failed_policy(:required_fields_provided) do
render json: { error: I18n.t("login.missing_user_field") }
@@ -993,9 +993,6 @@ class SessionController < ApplicationController
on_failed_policy(:required_full_name_provided) do
render json: { error: I18n.t("login.missing_full_name") }
end
- on_failed_policy(:required_username_provided) do
- render_signup_username_required(result[:params].email)
- end
on_model_errors(:user) { |user| render json: login_code_account_error(user) }
on_failed_contract do |contract|
render json: failed_json.merge(errors: contract.errors.full_messages), status: :bad_request
@@ -1143,6 +1140,9 @@ class SessionController < ApplicationController
elsif payload = login_error_check(user)
render json: payload
elsif 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)
@@ -1150,6 +1150,19 @@ class SessionController < ApplicationController
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
@@ -1222,17 +1235,9 @@ class SessionController < ApplicationController
on_failed_policy(:required_full_name_provided) do
render 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])
- end
- on_failed_policy(:username_allowed) do
- render json: { username_errors: [I18n.t("login.reserved_username")] }
- end
on_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?(ActiveRecord::RecordInvalid)
- render json: login_code_account_error(model_result.exception.record)
- elsif model_result.exception.is_a?(Invite::UserExists)
+ if model_result.exception.is_a?(Invite::UserExists)
render json: { error: model_result.exception.message }
else
render json: invalid_login_code
@@ -1250,33 +1255,9 @@ class SessionController < ApplicationController
topic && user.guardian.can_see?(topic) ? path(topic.relative_url) : path("/")
end
- def render_signup_username_required(email, invite: nil)
- username =
- UserNameSuggester.suggest(email, allow_generic_fallback: false) ||
- RandomUsernameGenerator.generate
- username = nil if UserNameSuggester.generic_username?(username)
-
- 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,
- trust_level: trust_level,
- avatar_template: username && User.default_template(username),
- can_upload_avatar:
- group_ids.intersect?(SiteSetting.uploaded_avatars_allowed_groups_map),
- }
- end
-
# A pending provider handoff would redirect as soon as the session exists,
- # skipping the pending avatar upload, so the client follows the URL once
- # signup is finished (as account activation does). Consumes the
+ # 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
# payload so a later login isn't sent through a handoff it didn't start.
def deferred_sso_provider_url
return if !SiteSetting.enable_discourse_connect_provider
@@ -1308,10 +1289,6 @@ class SessionController < ApplicationController
end
def 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.rb
index 271a651e8d2..696b497cbf8 100644
--- a/app/controllers/users_controller.rb
+++ b/app/controllers/users_controller.rb
@@ -610,10 +610,8 @@ class UsersController < ApplicationController
end
end
- def render_available_true(username = nil)
- result = { available: true }
- result[:avatar_template] = User.default_template(username) if username
- render json: result
+ def render_available_true
+ render(json: { available: true })
end
def changing_case_of_own_username(target_user, username)
@@ -647,13 +645,11 @@ class UsersController < ApplicationController
target_user = user_from_params_or_current_user
# The special case where someone is changing the case of their own username
- return render_available_true(username) if changing_case_of_own_username(target_user, username)
+ return render_available_true 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)
- result = checker.check_username(username, email)
- result[:avatar_template] = User.default_template(username) if result[:available]
- render json: result
+ render json: checker.check_username(username, email)
end
def generate_random_username
@@ -712,12 +708,7 @@ class UsersController < ApplicationController
end
def user_from_params_or_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)
- user
+ params[:for_user_id] ? User.find(params[:for_user_id]) : current_user
end
def create
diff --git a/app/models/invite_redeemer.rb b/app/models/invite_redeemer.rb
index d30e7de02e9..aede3b95b6c 100644
--- a/app/models/invite_redeemer.rb
+++ b/app/models/invite_redeemer.rb
@@ -99,10 +99,8 @@ class InviteRedeemer
)
raise Discourse::SiteArchived if SiteSetting.site_archived
- if email_verified && username.present?
- available_username = username
- elsif username && UsernameValidator.new(username).valid_format? &&
- User.username_available?(username, email)
+ if username && UsernameValidator.new(username).valid_format? &&
+ User.username_available?(username, email)
available_username = username
elsif email_verified
available_username =
diff --git a/app/services/email_login_code/redeem.rb b/app/services/email_login_code/redeem.rb
index fc697ec573a..b7afb21c430 100644
--- a/app/services/email_login_code/redeem.rb
+++ b/app/services/email_login_code/redeem.rb
@@ -38,10 +38,10 @@ class EmailLoginCode::Redeem
policy :email_available_for_new_account
policy :can_register_new_account
policy :can_register_from_ip
+ policy :required_username_provided
policy :username_allowed
policy :required_fields_provided
policy :required_full_name_provided
- policy :required_username_provided
lock(:email) do
transaction do
@@ -98,6 +98,10 @@ class EmailLoginCode::Redeem
existing_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?
@@ -128,10 +132,6 @@ 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.
diff --git a/app/services/invite/redeem_with_email_code.rb b/app/services/invite/redeem_with_email_code.rb
index 130a5959719..adc94b39837 100644
--- a/app/services/invite/redeem_with_email_code.rb
+++ b/app/services/invite/redeem_with_email_code.rb
@@ -7,7 +7,6 @@ class Invite::RedeemWithEmailCode
attribute :invite_key, :string
attribute :user_fields
attribute :name, :string
- attribute :username, :string
before_validation do
self.invite_key = invite_key.to_s.strip
@@ -18,7 +17,6 @@ class Invite::RedeemWithEmailCode
{}
end
self.name = name.to_s.strip.presence
- self.username = username.to_s.strip.presence
end
validates :invite_key, presence: true
@@ -34,8 +32,6 @@ class Invite::RedeemWithEmailCode
policy :can_register_new_account
policy :required_fields_provided
policy :required_full_name_provided
- policy :required_username_provided
- policy :username_allowed
try(
ActiveRecord::RecordInvalid,
@@ -114,17 +110,6 @@ 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
@@ -137,7 +122,6 @@ 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.rb
index 8f1051ac1b8..c4644e37369 100644
--- a/app/services/user/action/create_from_verified_email.rb
+++ b/app/services/user/action/create_from_verified_email.rb
@@ -2,22 +2,31 @@
class User::Action::CreateFromVerifiedEmail < Service::ActionBase
option :email
- option :username
option :ip_address, optional: true
option :user_fields, optional: true
option :name, optional: true
option :password, optional: true
+ option :username, optional: true
def call
raise 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).first
user&.unstage!
user ||= User.new
user.attributes = {
email: email,
- username: username,
+ 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.
name: name.presence || user.name,
active: false,
locale: I18n.locale,
diff --git a/config/locales/client.en.yml b/config/locales/client.en.yml
index 8b239a85e24..fb428dd6f13 100644
--- a/config/locales/client.en.yml
+++ b/config/locales/client.en.yml
@@ -3152,7 +3152,8 @@ 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."
- signup_details_title: "Choose your username and avatar"
+ account_ready_title: "Your account is ready! 🎉"
+ account_ready_edit: "Pick 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.yml
index 78ba1bf4cc3..b7392f21b42 100644
--- a/config/site_settings.yml
+++ b/config/site_settings.yml
@@ -696,7 +696,7 @@ login:
- everyone
enable_random_usernames:
client: true
- default: false
+ default: true
area: "login"
depends_on:
- enable_local_logins_via_code
diff --git a/frontend/discourse/app/components/code-login-form.gjs b/frontend/discourse/app/components/code-login-form.gjs
index 37dcfc964fa..23e45ceccd2 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, updateCsrfToken } from "discourse/lib/ajax";
+import { ajax } 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,9 +59,8 @@ export default class CodeLoginForm extends Component {
@tracked notice;
@tracked resendCooldown = 0;
@tracked otpGeneration = 0;
- @tracked canUploadAvatar = false;
- @tracked pendingAvatar;
- @tracked pendingAvatarUrl;
+ @tracked newAccount;
+ @tracked accountUser;
@tracked name = "";
@tracked accountPassword = "";
@tracked showOptionalPassword = false;
@@ -74,8 +73,10 @@ export default class CodeLoginForm extends Component {
@tracked usernameAvailable = false;
@tracked usernameChecking = false;
@tracked usernameError;
+ @tracked usernameEditable = true;
@tracked regenerating = false;
@tracked avatarTemplate;
+ @tracked avatarDetailsLoaded = false;
@tracked secondFactorMethod = SECOND_FACTOR_METHODS.TOTP;
@tracked secondFactorToken;
@tracked securityKeyCredential;
@@ -94,9 +95,8 @@ export default class CodeLoginForm extends Component {
});
#cooldownTimer;
#draftEmail;
- #collectedUserFields = false;
+ #postSignupRedirectUrl;
#usernameCheckSeq = 0;
- @tracked _signupTrustLevel = 0;
@tracked _step;
constructor() {
@@ -114,7 +114,6 @@ export default class CodeLoginForm extends Component {
willDestroy() {
super.willDestroy(...arguments);
cancel(this.#cooldownTimer);
- this.#clearPendingAvatarUrl();
}
// Tracked-backed so the parent can react to step transitions via onStepChange.
@@ -209,7 +208,10 @@ export default class CodeLoginForm extends Component {
};
case "complete":
return {
- title: i18n("code_login.signup_details_title"),
+ title: i18n("code_login.account_ready_title"),
+ subtitle: this.usernameEditable
+ ? i18n("code_login.account_ready_edit")
+ : null,
};
case "second-factor":
return { title: i18n("login.second_factor_title"), subtitle: null };
@@ -222,17 +224,13 @@ 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;
}
@@ -350,12 +348,6 @@ export default class CodeLoginForm extends Component {
this.code = "";
this.codeError = null;
this.notice = null;
- this.username = "";
- this.usernameAvailable = false;
- this.usernameError = null;
- this.avatarTemplate = null;
- this.pendingAvatar = null;
- this.#clearPendingAvatarUrl();
this.otpGeneration++;
this.#clearSignupContinuation();
this.step = "email";
@@ -400,9 +392,7 @@ export default class CodeLoginForm extends Component {
if (
!this.isPasswordReset &&
- (this.#collectedUserFields ||
- this.isUserFieldsStep ||
- this.#prefillUserFields())
+ (this.isUserFieldsStep || this.#prefillUserFields())
) {
data.user_fields = {};
this.userFields.forEach((f) => (data.user_fields[f.field.id] = f.value));
@@ -411,10 +401,6 @@ export default class CodeLoginForm extends Component {
}
}
- if (this.isCompleteStep) {
- data.username = this.username.trim();
- }
-
try {
const endpoint = this.isPasswordReset
? "/session/password-reset-code/verify"
@@ -425,27 +411,10 @@ export default class CodeLoginForm extends Component {
data,
});
const result =
- this.isCompleteStep && !this.isInvite
+ this.isSignup && this.isCodeStep
? await applyBehaviorTransformer("create-account", verify)
: await verify();
- if (result?.success === false && result.message) {
- this.codeError = result.message;
- return;
- }
-
- if (result?.username_required) {
- this.setupSignupDetails(result);
- this.step = "complete";
- 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
@@ -472,7 +441,7 @@ export default class CodeLoginForm extends Component {
if (this.isSecondFactorStep) {
this.securityKeyCredential = null;
this.codeError = result.error;
- } else if (this.isUserFieldsStep || this.isCompleteStep) {
+ } else if (this.isUserFieldsStep) {
this.codeError = result.error;
} else {
this.codeError = result.error;
@@ -500,8 +469,8 @@ export default class CodeLoginForm extends Component {
}
if (result?.account_created) {
- await this.#savePendingAvatar(result);
- this.redirectAfterLogin(result.redirect_url);
+ this.setupNewAccount(result);
+ this.step = "complete";
return;
}
@@ -551,17 +520,28 @@ export default class CodeLoginForm extends Component {
) {
return;
}
- this.#collectedUserFields = true;
return this.verifyCode();
}
- setupSignupDetails(result) {
- this.username = result.username || "";
- this.avatarTemplate = result.avatar_template;
- this._signupTrustLevel = result.trust_level ?? 0;
- this.canUploadAvatar =
- result.can_upload_avatar && allowsImages(false, this.siteSettings);
- if (this.username) {
+ // 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) {
this.checkUsernameAvailability();
}
}
@@ -608,7 +588,6 @@ export default class CodeLoginForm extends Component {
this.username = event.target.value;
this.usernameAvailable = false;
this.usernameError = null;
- this.avatarTemplate = null;
discourseDebounce(this, this.checkUsernameAvailability, 350);
}
@@ -624,18 +603,19 @@ export default class CodeLoginForm extends Component {
const seq = ++this.#usernameCheckSeq;
this.usernameChecking = true;
try {
- const result = await User.checkUsername(username, this.email);
+ const result = await User.checkUsername(
+ username,
+ this.email,
+ this.newAccount?.id
+ );
- if (seq !== this.#usernameCheckSeq || username !== this.username.trim()) {
+ if (seq !== this.#usernameCheckSeq) {
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 =
@@ -658,25 +638,32 @@ export default class CodeLoginForm extends Component {
}
@action
- changeAvatar() {
+ 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);
+ }
+
this.modal.show(AvatarSelectorModal, {
model: {
- deferSave: true,
- avatarTemplate: this.avatarTemplate,
- canUploadAvatar: this.canUploadAvatar,
- trustLevel: this._signupTrustLevel,
- selection: this.pendingAvatar,
- onSelect: this.selectPendingAvatar,
+ user: this.accountUser,
+ onAvatarChange: () => this.avatarChanged(),
},
});
}
- @action
- selectPendingAvatar(selection) {
- this.#clearPendingAvatarUrl();
- this.pendingAvatar = selection;
- if (selection?.file) {
- this.pendingAvatarUrl = URL.createObjectURL(selection.file);
+ 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);
}
}
@@ -713,12 +700,10 @@ export default class CodeLoginForm extends Component {
});
try {
- const result = await applyBehaviorTransformer("create-account", () =>
- ajax("/session/login-code/verify", {
- type: "POST",
- data,
- })
- );
+ const result = await ajax("/session/login-code/verify", {
+ type: "POST",
+ data,
+ });
if (result?.pending_approval) {
this.accountPassword = "";
@@ -751,9 +736,29 @@ export default class CodeLoginForm extends Component {
@action
async continueAfterSignup() {
- if (!this.continueDisabled) {
- await this.verifyCode();
+ if (this.continueDisabled) {
+ return;
}
+
+ 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
@@ -836,12 +841,12 @@ export default class CodeLoginForm extends Component {
redirectAfterLogin(redirectUrl) {
const destinationUrl = cookie("destination_url");
if (redirectUrl) {
- DiscourseURL.redirectTo(redirectUrl);
+ window.location.assign(redirectUrl);
} else if (destinationUrl) {
removeCookie("destination_url");
- DiscourseURL.redirectTo(destinationUrl);
+ window.location.assign(destinationUrl);
} else {
- DiscourseURL.redirectTo("/");
+ window.location.assign(getURL("/"));
}
}
@@ -917,46 +922,6 @@ 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.
@@ -1127,6 +1092,13 @@ 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|}}
<DOtp
id="code-login-otp-{{generation}}"
@@ -1336,88 +1308,75 @@ export default class CodeLoginForm extends Component {
<div class="code-login-form__complete-step">
{{#unless this.isSignup}}
<h2 class="code-login-form__title">
- {{i18n "code_login.signup_details_title"}}
+ {{i18n "code_login.account_ready_title"}}
</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
- 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}}
+ {{dBoundAvatarTemplate this.avatarTemplate "huge"}}
<span class="code-login-form__avatar-edit">
{{dIcon "pencil"}}
</span>
</button>
- <div class="code-login-form__username-field">
- <label for="code-login-username">
- {{i18n "code_login.username_label"}}
- </label>
- <div class="code-login-form__username-input">
- <input
- aria-describedby="code-login-username-error"
- aria-invalid={{if this.usernameError "true"}}
- 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"}}
- type="text"
- value={{this.username}}
- {{on "input" this.usernameChanged}}
- />
- {{#if this.siteSettings.enable_random_usernames}}
- <DButton
- aria-busy={{if this.regenerating "true"}}
- class="btn-default code-login-form__username-regen
- {{if this.regenerating '--rolling'}}"
- @action={{this.regenerateUsername}}
- @ariaLabel="code_login.regenerate_username"
- @disabled={{this.verifying}}
- @icon="dice"
- @title="code_login.regenerate_username"
+ {{#if this.usernameEditable}}
+ <div class="code-login-form__username-field">
+ <label for="code-login-username">
+ {{i18n "code_login.username_label"}}
+ </label>
+ <div class="code-login-form__username-input">
+ <input
+ aria-describedby="code-login-username-error"
+ aria-invalid={{if this.usernameError "true"}}
+ autocomplete="off"
+ class="code-login-form__new-account-username
+ {{if this.regenerating '--swapping'}}"
+ id="code-login-username"
+ name="username"
+ placeholder={{i18n "code_login.username_placeholder"}}
+ type="text"
+ value={{this.username}}
+ {{on "input" this.usernameChanged}}
/>
- {{/if}}
+ {{#if this.siteSettings.enable_random_usernames}}
+ <DButton
+ aria-busy={{if this.regenerating "true"}}
+ class="btn-default code-login-form__username-regen
+ {{if this.regenerating '--rolling'}}"
+ @action={{this.regenerateUsername}}
+ @ariaLabel="code_login.regenerate_username"
+ @icon="dice"
+ @title="code_login.regenerate_username"
+ />
+ {{/if}}
+ </div>
+ <div
+ aria-live="polite"
+ class="code-login-form__error"
+ id="code-login-username-error"
+ role="alert"
+ >
+ {{this.usernameError}}
+ </div>
</div>
- <div
- aria-live="polite"
- class="code-login-form__error"
- id="code-login-username-error"
- role="alert"
- >
- {{this.usernameError}}
+ {{else}}
+ <div class="code-login-form__new-account-username">
+ {{this.newAccount.username}}
</div>
- </div>
+ {{/if}}
</div>
- {{#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}}
-
<DButton
class="btn-large btn-primary code-login-form__continue-to-site"
@action={{this.continueAfterSignup}}
diff --git a/frontend/discourse/app/components/modal/avatar-selector.gjs b/frontend/discourse/app/components/modal/avatar-selector.gjs
index 081daf92aff..fc6699f81fd 100644
--- a/frontend/discourse/app/components/modal/avatar-selector.gjs
+++ b/frontend/discourse/app/components/modal/avatar-selector.gjs
@@ -1,23 +1,20 @@
import Component from "@glimmer/component";
import { tracked } from "@glimmer/tracking";
-import { fn, hash } from "@ember/helper";
+import { fn } from "@ember/helper";
import { on } from "@ember/modifier";
-import { action, get } from "@ember/object";
+import { action } 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, validateUploadedFile } from "discourse/lib/uploads";
-import { eq, or } from "discourse/truth-helpers";
+import { allowsImages } from "discourse/lib/uploads";
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 {
@@ -27,26 +24,6 @@ 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;
@@ -56,31 +33,12 @@ 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" ||
- (this.deferSave && this.selected === "custom" && !this._pendingFile)
- );
+ return this.selected === "logo";
}
get selectableAvatars() {
@@ -99,9 +57,6 @@ 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;
@@ -111,12 +66,12 @@ export default class AvatarSelectorModal extends Component {
case "tl4":
const allowedTl = parseInt(mode.replace("tl", ""), 10);
return (
- this.user?.admin ||
- this.user?.moderator ||
- (trustLevel ?? 0) >= allowedTl
+ this.user.admin ||
+ this.user.moderator ||
+ this.user.trust_level >= allowedTl
);
case "staff":
- return this.user?.admin || this.user?.moderator;
+ return this.user.admin || this.user.moderator;
case "everyone":
default:
return true;
@@ -124,9 +79,7 @@ export default class AvatarSelectorModal extends Component {
}
get defaultSelection() {
- if (this.deferSave) {
- return "system";
- } else if (this.user.use_logo_small_as_avatar) {
+ if (this.user.use_logo_small_as_avatar) {
return "logo";
} else if (this.user.avatar_template === this.user.system_avatar_template) {
return "system";
@@ -152,12 +105,8 @@ export default class AvatarSelectorModal extends Component {
}
get allowAvatarUpload() {
- if (this.deferSave) {
- return (
- this.args.model.canUploadAvatar &&
- allowsImages(false, this.siteSettings)
- );
- }
+ // 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.
const user = this.currentUser ?? this.user;
return (
user.can_upload_avatar && allowsImages(user.staff, this.siteSettings)
@@ -165,11 +114,7 @@ export default class AvatarSelectorModal extends Component {
}
get allowGravatar() {
- return (
- !this.deferSave &&
- this.allowAvatarUpload &&
- this.siteSettings.gravatar_enabled
- );
+ return this.allowAvatarUpload && this.siteSettings.gravatar_enabled;
}
@action
@@ -177,6 +122,8 @@ 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();
@@ -189,10 +136,6 @@ export default class AvatarSelectorModal extends Component {
@action
async selectAvatar(url, event) {
event?.preventDefault();
- if (this.deferSave) {
- this.selected = url;
- return;
- }
try {
await this.user.selectAvatar(url);
this.afterAvatarSaved();
@@ -201,23 +144,6 @@ 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";
- }
-
@action
uploadComplete() {
this.selected = "custom";
@@ -251,17 +177,6 @@ export default class AvatarSelectorModal extends Component {
@action
async 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 });
@@ -270,13 +185,6 @@ export default class AvatarSelectorModal extends Component {
}
}
- #clearFilePreview() {
- if (this._filePreview) {
- URL.revokeObjectURL(this._filePreview);
- this._filePreview = null;
- }
- }
-
<template>
<DModal
class="avatar-selector-modal"
@@ -289,7 +197,6 @@ 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)}}
@@ -330,13 +237,7 @@ export default class AvatarSelectorModal extends Component {
@value="system"
/>
<label class="radio" for="system-avatar">
- {{#if this.systemAvatarTemplate}}
- {{dBoundAvatarTemplate this.systemAvatarTemplate "large"}}
- {{else}}
- <span class="avatar-selector__placeholder">{{dIcon
- "user"
- }}</span>
- {{/if}}
+ {{dBoundAvatarTemplate this.user.system_avatar_template "large"}}
{{i18n "user.change_avatar.letter_based"}}
</label>
</div>
@@ -398,41 +299,31 @@ export default class AvatarSelectorModal extends Component {
@value="custom"
/>
<label class="radio" for="uploaded-avatar">
- {{#if this.customAvatarTemplate}}
- {{dBoundAvatarTemplate this.customAvatarTemplate "large"}}
+ {{#if this.user.custom_avatar_template}}
+ {{dBoundAvatarTemplate
+ this.user.custom_avatar_template
+ "large"
+ }}
{{i18n "user.change_avatar.uploaded_avatar"}}
{{else}}
{{i18n "user.change_avatar.uploaded_avatar_empty"}}
{{/if}}
</label>
- {{#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}}
+ <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}}
+ />
</div>
{{/if}}
{{/if}}
</:body>
<:footer>
- {{#if (or this.showCustomAvatarSelector this.deferSave)}}
+ {{#if this.showCustomAvatarSelector}}
<DButton
class="btn-primary"
@action={{this.saveAvatarSelection}}
diff --git a/frontend/discourse/tests/integration/components/code-login-form-test.gjs b/frontend/discourse/tests/integration/components/code-login-form-test.gjs
index 7144c91885a..f332b4b6900 100644
--- a/frontend/discourse/tests/integration/components/code-login-form-test.gjs
+++ b/frontend/discourse/tests/integration/components/code-login-form-test.gjs
@@ -1,17 +1,7 @@
-import {
- click,
- fillIn,
- find,
- render,
- triggerEvent,
- waitFor,
-} from "@ember/test-helpers";
+import { click, fillIn, render, waitFor } 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";
@@ -25,7 +15,7 @@ function stubCodeRequest() {
}
async function goToCodeStep() {
- await render(<template><CodeLoginForm /><ModalContainer /></template>);
+ await render(<template><CodeLoginForm /></template>);
await fillIn(
".code-login-form__email-step .form-kit__control-input",
@@ -33,17 +23,6 @@ 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);
@@ -150,7 +129,7 @@ module("Integration | Component | CodeLoginForm", function (hooks) {
.doesNotExist("the scoped invitation address cannot be changed");
});
- test("runs create-account behavior transformers only when submitting the chosen username", async function (assert) {
+ test("runs create-account behavior transformers before verifying a signup code", async function (assert) {
stubCodeRequest();
let transformed = false;
@@ -161,18 +140,9 @@ module("Integration | Component | CodeLoginForm", function (hooks) {
return next();
})
);
- pretender.post("/session/login-code/verify", (request) => {
+ pretender.post("/session/login-code/verify", () => {
verificationRequests++;
- 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",
- }
- );
+ return response({ error: i18n("email_login_code.invalid_code") });
});
await render(<template><CodeLoginForm @context="signup" /></template>);
@@ -181,29 +151,17 @@ module("Integration | Component | CodeLoginForm", function (hooks) {
);
await formKit().submit();
- await fillIn(".d-otp-input", "123456");
+ await fillIn(".d-otp-input", "000000");
- assert.false(
+ assert.true(
transformed,
- "checking the email code does not run account creation challenges"
+ "the signup verification passes through the transformer"
);
- 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"
+ 1,
+ "the transformer continues to code verification"
);
- assert
- .dom(".code-login-form__complete-step")
- .exists("signup remains on the username step after rejection");
- assert
- .dom(".code-login-form__complete-step > p.code-login-form__error")
- .hasText(
- "Signup verification failed",
- "the account creation rejection is shown"
- );
});
test("shows a request error without advancing to the code step", async function (assert) {
@@ -530,10 +488,10 @@ module("Integration | Component | CodeLoginForm", function (hooks) {
verifyParams = new URLSearchParams(request.requestBody);
return response({
- username_required: true,
- username: "jane",
- avatar_template: "/letter/j.png",
- can_upload_avatar: true,
+ account_created: true,
+ user: { id: 1, username: "jane", avatar_template: "/letter/j.png" },
+ can_edit_username: true,
+ prefill_username: true,
});
});
@@ -548,19 +506,6 @@ 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) {
@@ -597,31 +542,18 @@ 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("username")) {
- return response({
- account_created: 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,
+ account_created: true,
+ user: { id: 1, username: "jane", avatar_template: "/letter/j.png" },
+ can_edit_username: true,
+ prefill_username: true,
});
}
@@ -660,39 +592,17 @@ module("Integration | Component | CodeLoginForm", function (hooks) {
assert.dom(".code-login-form__complete-step").exists();
assert
.dom("#code-login-username")
- .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"
- );
+ .hasValue("jane", "the assigned username is prefilled");
});
- test("regenerates a random username suggestion before creating the account", async function (assert) {
- this.siteSettings.enable_random_usernames = true;
+ test("regenerates a random username suggestion on the account-ready step", async function (assert) {
stubCodeRequest();
pretender.post("/session/login-code/verify", () =>
response({
- username_required: true,
- username: "jane",
- avatar_template: "/letter/j.png",
- can_upload_avatar: true,
+ account_created: true,
+ user: { id: 1, username: "jane", avatar_template: "/letter/j.png" },
+ can_edit_username: true,
+ prefill_username: true,
})
);
pretender.get("/u/random-username.json", () =>
@@ -718,14 +628,13 @@ 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({
- username_required: true,
- username: "jane",
- avatar_template: "/letter/j.png",
- can_upload_avatar: true,
+ account_created: true,
+ user: { id: 1, username: "jane", avatar_template: "/letter/j.png" },
+ can_edit_username: true,
+ prefill_username: true,
})
);
// The default pretender handler reports the username "taken" as
@@ -748,72 +657,15 @@ module("Integration | Component | CodeLoginForm", function (hooks) {
assert.dom(".code-login-form__continue-to-site").isDisabled();
});
- test("previews the avatar for a valid username and uses a person icon otherwise", async function (assert) {
+ test("hides the regenerate button and makes the user pick when random usernames are disabled", async function (assert) {
+ this.siteSettings.enable_random_usernames = false;
stubCodeRequest();
pretender.post("/session/login-code/verify", () =>
response({
- 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({
- username_required: true,
- username: null,
- avatar_template: null,
- can_upload_avatar: true,
+ account_created: true,
+ user: { id: 1, username: "user1", avatar_template: "/letter/u.png" },
+ can_edit_username: true,
+ prefill_username: false,
})
);
@@ -827,150 +679,26 @@ module("Integration | Component | CodeLoginForm", function (hooks) {
assert.dom(".code-login-form__continue-to-site").isDisabled();
});
- test("keeps a local avatar preview without uploading before account creation", async function (assert) {
+ test("shows a fixed username without editing controls when it can't be changed", 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({
- username_required: true,
- can_upload_avatar: true,
- trust_level: 2,
+ account_created: true,
+ user: { id: 1, username: "jane", avatar_template: "/letter/j.png" },
+ can_edit_username: false,
+ prefill_username: true,
})
);
- pretender.get("/u/check_username", () =>
- response({ available: true, avatar_template: "/letter/j.png" })
- );
await goToCodeStep();
await fillIn(".d-otp-input", "123456");
- await selectLocalAvatar();
-
- 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");
+ 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();
});
- 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.gjs
deleted file mode 100644
index cb76355b0b4..00000000000
--- a/frontend/discourse/tests/integration/components/modal/avatar-selector-test.gjs
+++ /dev/null
@@ -1,173 +0,0 @@
-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/plugins/discourse-captcha/lib/discourse_captcha/session_controller_patch.rb b/plugins/discourse-captcha/lib/discourse_captcha/session_controller_patch.rb
index 31cc7072cdf..f5accbb3eb2 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 DiscourseCaptcha
return false if matched_user.present? || params[:invite_key].present?
return false if !registration_via_login_code_open?
- !pending_approval_signup?(matched_user) && params[:username].present? &&
- !signup_user_fields_missing? && !signup_full_name_missing?
+ pending_approval_signup?(matched_user) ||
+ (!signup_user_fields_missing? && !signup_full_name_missing?)
end
include CaptchaVerification
diff --git a/plugins/discourse-captcha/spec/requests/discourse_captcha/session_controller_spec.rb b/plugins/discourse-captcha/spec/requests/discourse_captcha/session_controller_spec.rb
index 1cdff9795cc..7587956a4b8 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: true
RSpec.describe SessionController do
- describe "#verify_login_code" do
+ describe "POST /session/login-code/verify" do
fab!(:existing_user, :user)
before do
@@ -13,32 +13,14 @@ RSpec.describe SessionController do
SiteSetting.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" do
code = EmailLoginCode.generate!(email:).code
- expect {
- post "/session/login-code/verify.json",
- params: {
- email:,
- code:,
- username: "chosen_username",
- }
- }.not_to change(User, :count)
+ expect { post "/session/login-code/verify.json", params: { email:, code: } }.not_to change(
+ User,
+ :count,
+ )
expect(response.status).to eq(200)
expect(response.parsed_body["error"]).to eq(I18n.t("captcha_verification_failed"))
@@ -57,14 +39,10 @@ RSpec.describe SessionController do
post "/captcha/hcaptcha/create.json", params: { token: "captcha-token" }
- expect {
- post "/session/login-code/verify.json",
- params: {
- email:,
- code:,
- username: "chosen_username",
- }
- }.to change(User, :count).by(1)
+ expect { post "/session/login-code/verify.json", params: { email:, code: } }.to change(
+ User,
+ :count,
+ ).by(1)
expect(response.status).to eq(200)
expect(response.parsed_body["account_created"]).to eq(true)
@@ -80,7 +58,6 @@ RSpec.describe SessionController do
params: {
email: invite.email,
code:,
- username: "invited_person",
invite_key: invite.invite_key,
}
}.to change(User, :count).by(1)
@@ -120,7 +97,7 @@ RSpec.describe SessionController do
}
end
- it "verifies CAPTCHA only when submitting the approval account details" do
+ it "carries verified CAPTCHA proof into the continuation without validating it twice" do
verification_request =
stub_request(:post, DiscourseCaptcha::HcaptchaProvider::CAPTCHA_VERIFICATION_URL).with(
body: {
@@ -128,6 +105,7 @@ RSpec.describe SessionController do
response: "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 }
@@ -135,11 +113,9 @@ RSpec.describe SessionController do
signup_token = response.parsed_body["signup_token"]
expect(signup_token).to be_present
- expect(verification_request).not_to have_been_requested
+ expect(verification_request).to have_been_requested.once
expect(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)
@@ -149,9 +125,11 @@ RSpec.describe SessionController do
expect(verification_request).to have_been_requested.once
end
- it "requires valid CAPTCHA on the final request before creating the approval account" do
+ it "requires CAPTCHA on the final request when the continuation has no CAPTCHA proof" do
+ SiteSetting.discourse_captcha_enabled = false
post "/session/login-code/verify.json", params: { email:, code: login_code.code }
signup_token = response.parsed_body["signup_token"]
+ SiteSetting.discourse_captcha_enabled = true
expect {
post "/session/login-code/verify.json",
@@ -212,7 +190,6 @@ RSpec.describe SessionController do
params: {
email:,
code:,
- username: "chosen_username",
user_fields: {
user_field.id.to_s => "Developer",
},
diff --git a/plugins/discourse-captcha/spec/system/signup_with_captcha_spec.rb b/plugins/discourse-captcha/spec/system/signup_with_captcha_spec.rb
index f98e6c771e0..391ae04f8c3 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,6 @@
# frozen_string_literal: true
RSpec.describe "Signup with captcha" do
- include ThemeScreenshotMarker
let(:signup_page) { PageObjects::Pages::Signup.new }
let(:captcha) { PageObjects::Components::Captcha.new }
@@ -36,25 +35,14 @@ RSpec.describe "Signup with captcha" do
end
context "with code-based signup" do
- before do
- SiteSetting.enable_local_logins_via_code = true
- Jobs.run_immediately!
- end
+ before { SiteSetting.enable_local_logins_via_code = true }
- it "shows the hCaptcha widget when choosing a username after email verification" do
+ it "displays the hCaptcha widget after requesting a signup code" do
signup_page.open
find(".code-login-form__email-step input[type='email']").fill_in(with: "[email protected]")
find(".code-login-form__continue").click
- 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__complete-step")
- expect(captcha).to have_hcaptcha_widget
- screenshot_marker(label: "deferred-signup-captcha", only: :desktop)
+ expect(captcha).to have_hcaptcha_container
end
end
diff --git a/spec/integration/archive_mode_spec.rb b/spec/integration/archive_mode_spec.rb
index 23463ae2ffa..760c2a3ce4f 100644
--- a/spec/integration/archive_mode_spec.rb
+++ b/spec/integration/archive_mode_spec.rb
@@ -118,7 +118,6 @@ RSpec.describe "Site archived" do
expect do
User::Action::CreateFromVerifiedEmail.call(
- 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.rb
index a37f022dbcc..b273affc4f9 100644
--- a/spec/lib/random_username_generator_spec.rb
+++ b/spec/lib/random_username_generator_spec.rb
@@ -2,8 +2,6 @@
RSpec.describe RandomUsernameGenerator do
describe ".generate" do
- before { SiteSetting.enable_random_usernames = true }
-
it "returns a valid, available username built from the word lists and a number" do
username = described_class.generate
diff --git a/spec/requests/session_controller_spec.rb b/spec/requests/session_controller_spec.rb
index f4ef29a94b6..c62dab29300 100644
--- a/spec/requests/session_controller_spec.rb
+++ b/spec/requests/session_controller_spec.rb
@@ -901,12 +901,7 @@ RSpec.describe SessionController do
new_code = EmailLoginCode.generate!(email: new_email)
expect do
- post "/session/login-code/verify.json",
- params: {
- email: new_email,
- code: new_code.code,
- username: "archived-new-user",
- }
+ post "/session/login-code/verify.json", params: { email: new_email, code: new_code.code }
end.not_to change { User.count }
expect(response.status).to eq(503)
@@ -938,7 +933,6 @@ RSpec.describe SessionController do
invite_key: invite.invite_key,
code:,
- username: "invited-person",
}
invited_user = User.find_by_email(invite.email)
@@ -954,28 +948,6 @@ RSpec.describe SessionController do
expect(login_code.reload.consumed_at).to be_present
end
- 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" do
user.update!(email: invite.email, active: false)
@@ -1127,12 +1099,7 @@ RSpec.describe SessionController do
invite.update!(topics: [Fabricate(:topic)])
begin_discourse_connect_provider_handoff
- post "/session/login-code/verify.json",
- params: {
- invite_key: invite.invite_key,
- code:,
- username: "invited-person",
- }
+ post "/session/login-code/verify.json", params: { invite_key: invite.invite_key, code: }
expect(response.status).to eq(200)
expect(response.parsed_body["account_created"]).to eq(true)
@@ -1205,9 +1172,7 @@ RSpec.describe SessionController do
username:,
}
- expect(response.parsed_body["username_errors"]).to include(
- I18n.t("login.reserved_username"),
- ),
+ expect(response.parsed_body["error"]).to include(I18n.t("login.reserved_username")),
username
expect(User.find_by_email("[email protected]")).to be_nil
expect(ReviewableUser.count).to eq(0)
@@ -1265,7 +1230,7 @@ RSpec.describe SessionController do
signup_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_nil
+ expect(response.parsed_body["username"]).to be_present
expect(signup_token).to be_present
expect(User.find_by_email("[email protected]")).to be_nil
expect(session[:current_user_id]).to be_nil
@@ -1404,12 +1369,7 @@ RSpec.describe SessionController do
SiteSetting.must_approve_users = true
SiteSetting.auto_approve_email_domains = "example.com"
- post "/session/login-code/verify.json",
- params: {
- email: " [email protected] ",
- code:,
- username: "newuser",
- }
+ post "/session/login-code/verify.json", params: { email: " [email protected] ", code: }
new_user = User.find_by_email("[email protected]")
expect(response.parsed_body["account_created"]).to eq(true)
@@ -1417,98 +1377,71 @@ RSpec.describe SessionController do
expect(session[:current_user_id]).to eq(new_user.id)
end
- 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)
-
+ it "creates and logs in a new user" do
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).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 "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",
- }
+ it "returns the flags the account-ready step needs" do
+ post "/session/login-code/verify.json", params: { email: "[email protected]", code: }
- 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
+ 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")
end
- it "defers a pending DiscourseConnect provider handoff until signup is complete" do
+ it "defers a pending DiscourseConnect provider handoff to the account-ready step" do
payload = begin_discourse_connect_provider_handoff
post "/session/login-code/verify.json", params: { email: "[email protected]", code: }
- 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}")
+ # Consumed, so a later login isn't sent through this handoff.
expect(cookies[:sso_payload]).to be_blank
end
it "does not derive the username from the email when email-based suggestions are off" do
- SiteSetting.enable_random_usernames = true
SiteSetting.use_email_for_username_and_name_suggestions = false
post "/session/login-code/verify.json", params: { email: "[email protected]", code: }
- expect(response.parsed_body["username"]).to match(/\A[A-Z][a-z]+[A-Z][a-z]+\d+\z/)
+ new_user = User.find_by_email("[email protected]")
+ expect(new_user.username).not_to include("newuser")
+ expect(new_user.username).to match(/\A[A-Z][a-z]+[A-Z][a-z]+\d+\z/)
+ end
+
+ it "falls back to the generic username when random usernames are disabled" do
+ SiteSetting.use_email_for_username_and_name_suggestions = false
+ SiteSetting.enable_random_usernames = false
+
+ post "/session/login-code/verify.json", params: { email: "[email protected]", code: }
+
+ expect(User.find_by_email("[email protected]").username).to match(/\Auser\d*\z/)
+ # A generic placeholder isn't worth prefilling, so the client makes the
+ # user pick a username instead.
+ expect(response.parsed_body["prefill_username"]).to eq(false)
+ end
+
+ it "flags a randomly generated username for prefill" do
+ SiteSetting.use_email_for_username_and_name_suggestions = false
+
+ post "/session/login-code/verify.json", params: { email: "[email protected]", code: }
+
+ expect(response.parsed_body["prefill_username"]).to eq(true)
end
- it "leaves the suggestion blank when random generation yields nothing" do
- SiteSetting.enable_random_usernames = true
+ it "does not flag the fallback for prefill when generation is on but yields nothing" do
SiteSetting.use_email_for_username_and_name_suggestions = false
# Unicode words pass validation while unicode usernames are on, then
# stop being usable once the site turns them off.
@@ -1519,9 +1452,8 @@ RSpec.describe SessionController do
post "/session/login-code/verify.json", params: { email: "[email protected]", code: }
- 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_nil
+ expect(User.find_by_email("[email protected]").username).to match(/\Auser\d*\z/)
+ expect(response.parsed_body["prefill_username"]).to eq(false)
end
it "derives the username from the email when email-based suggestions are on" do
@@ -1529,7 +1461,7 @@ RSpec.describe SessionController do
post "/session/login-code/verify.json", params: { email: "[email protected]", code: }
- expect(response.parsed_body["username"]).to eq("newuser")
+ expect(User.find_by_email("[email protected]").username).to eq("newuser")
end
it "appends a numeric suffix when the email-derived name is taken" do
@@ -1538,20 +1470,21 @@ RSpec.describe SessionController do
post "/session/login-code/verify.json", params: { email: "[email protected]", code: }
- expect(response.parsed_body["username"]).to eq("newuser1")
+ expect(User.find_by_email("[email protected]").username).to eq("newuser1")
end
context "when the email can't produce a username suggestion" do
let(:login_code) { EmailLoginCode.generate!(email: "[email protected]") }
- it "suggests a random username instead of the generic fallback" do
- SiteSetting.enable_random_usernames = true
+ it "assigns a random username instead of the generic fallback" do
SiteSetting.use_email_for_username_and_name_suggestions = true
post "/session/login-code/verify.json", params: { email: "[email protected]", code: }
- expect(response.parsed_body["username_required"]).to eq(true)
- expect(response.parsed_body["username"]).to match(/\A[A-Z][a-z]+[A-Z][a-z]+\d+\z/)
+ expect(response.parsed_body["account_created"]).to eq(true)
+ expect(User.find_by_email("[email protected]").username).to match(
+ /\A[A-Z][a-z]+[A-Z][a-z]+\d+\z/,
+ )
end
end
@@ -1574,7 +1507,6 @@ RSpec.describe SessionController do
params: {
code:,
- username: "chosen-name",
},
env: {
REMOTE_ADDR: ip_address,
@@ -1611,20 +1543,6 @@ 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)
@@ -1635,7 +1553,6 @@ RSpec.describe SessionController do
params: {
code:,
- username: "chosen-name",
user_fields: {
"0" => "",
},
@@ -1666,18 +1583,6 @@ RSpec.describe SessionController do
name: "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)
@@ -1688,7 +1593,6 @@ RSpec.describe SessionController do
params: {
code:,
- username: "chosen-name",
name: "a" * 256,
}
@@ -1703,7 +1607,6 @@ RSpec.describe SessionController do
params: {
code:,
- username: "chosen-name",
name: " ",
}
diff --git a/spec/requests/users_controller_spec.rb b/spec/requests/users_controller_spec.rb
index 0d3ca254f2a..6d305f6bc81 100644
--- a/spec/requests/users_controller_spec.rb
+++ b/spec/requests/users_controller_spec.rb
@@ -2237,39 +2237,6 @@ RSpec.describe UsersController do
end
describe "#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" do
get "/u/check_username.json"
expect(response.status).to eq(400)
@@ -2340,9 +2307,6 @@ RSpec.describe UsersController do
it "returns the username's availability" do
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(request.params[:username]),
- )
end
end
@@ -2395,7 +2359,6 @@ RSpec.describe UsersController do
expect(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")
end
end
@@ -2466,8 +2429,6 @@ RSpec.describe UsersController do
end
describe "#generate_random_username" do
- before { SiteSetting.enable_random_usernames = true }
-
it "returns a generated username" do
get "/u/random-username.json"
diff --git a/spec/services/email_login_code/redeem_spec.rb b/spec/services/email_login_code/redeem_spec.rb
index f689d75dcc9..4dafe353ea7 100644
--- a/spec/services/email_login_code/redeem_spec.rb
+++ b/spec/services/email_login_code/redeem_spec.rb
@@ -11,8 +11,7 @@ RSpec.describe EmailLoginCode::Redeem do
describe ".call" do
subject(:result) { described_class.call(params:, **dependencies) }
- let(:params) { { email:, code:, username: } }
- let(:username) { "chosen_username" }
+ let(:params) { { email:, code: } }
let(:dependencies) { { ip_address: "127.0.0.1" } }
let(:email) { "[email protected]" }
@@ -105,6 +104,58 @@ RSpec.describe EmailLoginCode::Redeem do
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 "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" do
fab!(:user_field)
@@ -117,7 +168,7 @@ RSpec.describe EmailLoginCode::Redeem do
end
context "when the field values are provided" do
- let(:params) { { email:, code:, username:, user_fields: { user_field.id.to_s => "Dev" } } }
+ let(:params) { { email:, code:, user_fields: { user_field.id.to_s => "Dev" } } }
it { is_expected.to run_successfully }
@@ -134,7 +185,6 @@ RSpec.describe EmailLoginCode::Redeem do
{
email:,
code:,
- username:,
user_fields: {
user_field.id.to_s => "Dev",
hidden_field.id.to_s => "Secret",
@@ -156,7 +206,7 @@ RSpec.describe EmailLoginCode::Redeem do
Fabricate(:user_field, requirement: "for_all_users", show_on_signup: false)
end
- let(:params) { { email:, code:, username:, user_fields: { user_field.id.to_s => "Dev" } } }
+ let(:params) { { email:, code:, user_fields: { user_field.id.to_s => "Dev" } } }
it "does not require fields the signup form can't collect" do
expect(result).to run_successfully
@@ -164,7 +214,7 @@ RSpec.describe EmailLoginCode::Redeem do
end
context "when user_fields is malformed" do
- let(:params) { { email:, code:, username:, user_fields: "not-a-hash" } }
+ let(:params) { { email:, code:, user_fields: "not-a-hash" } }
it "fails as a missing field instead of raising" do
expect { result }.not_to raise_error
@@ -193,13 +243,13 @@ RSpec.describe EmailLoginCode::Redeem do
end
context "when the name is only whitespace" do
- let(:params) { { email:, code:, username:, name: " " } }
+ let(:params) { { email:, code:, name: " " } }
it { is_expected.to fail_a_policy(:required_full_name_provided) }
end
context "when a name is provided" do
- let(:params) { { email:, code:, username:, name: "Jane Doe" } }
+ let(:params) { { email:, code:, name: "Jane Doe" } }
it { is_expected.to run_successfully }
@@ -217,128 +267,6 @@ RSpec.describe EmailLoginCode::Redeem do
end
end
- 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" do
fab!(:staged_user) { Fabricate(:staged, active: false) }
@@ -377,7 +305,6 @@ RSpec.describe EmailLoginCode::Redeem do
fab!(:user)
let(:email) { user.email }
- let(:username) { nil }
it { is_expected.to run_successfully }
@@ -393,13 +320,6 @@ RSpec.describe EmailLoginCode::Redeem do
end
end
- 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" do
expect(result[:user]).to eq(user)
expect(login_code.reload.consumed_at).to be_present
diff --git a/spec/services/invite/redeem_with_email_code_spec.rb b/spec/services/invite/redeem_with_email_code_spec.rb
index 4f6b156a554..d04898cbc76 100644
--- a/spec/services/invite/redeem_with_email_code_spec.rb
+++ b/spec/services/invite/redeem_with_email_code_spec.rb
@@ -14,8 +14,7 @@ RSpec.describe Invite::RedeemWithEmailCode do
fab!(:invite) { Fabricate(:invite, email: "[email protected]") }
- let(:params) { { invite_key: invite.invite_key, email:, code:, username: } }
- let(:username) { "chosen_username" }
+ let(:params) { { invite_key: invite.invite_key, email:, code: } }
let(:dependencies) { { ip_address: "127.0.0.1", server_session: {} } }
let(:email) { invite.email }
let(:login_code) { EmailLoginCode.generate!(email:) }
@@ -28,7 +27,7 @@ RSpec.describe Invite::RedeemWithEmailCode do
end
context "when the invite cannot be found" do
- let(:params) { { invite_key: "missing", email:, code:, username: } }
+ let(:params) { { invite_key: "missing", email:, code: } }
it { is_expected.to fail_to_find_a_model(:invite) }
end
@@ -128,7 +127,6 @@ RSpec.describe Invite::RedeemWithEmailCode do
invite_key: invite.invite_key,
email:,
code:,
- username:,
user_fields: {
user_field.id.to_s => "Engineer",
},
@@ -155,9 +153,7 @@ RSpec.describe Invite::RedeemWithEmailCode do
end
context "when a required full name is provided" do
- let(:params) do
- { invite_key: invite.invite_key, email:, code:, username:, name: "Invited Person" }
- end
+ let(:params) { { invite_key: invite.invite_key, email:, code:, name: "Invited Person" } }
before { SiteSetting.full_name_requirement = "required_at_signup" }
@@ -168,102 +164,6 @@ RSpec.describe Invite::RedeemWithEmailCode do
end
end
- 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" do
it { is_expected.to run_successfully }
@@ -279,7 +179,6 @@ RSpec.describe Invite::RedeemWithEmailCode do
expect(user).to be_active
expect(user).to be_email_confirmed
expect(user.email).to eq(email)
- expect(user.username).to eq(username)
expect(user.user_password).to be_nil
expect(user.registration_ip_address.to_s).to eq(dependencies[:ip_address])
end
@@ -294,15 +193,6 @@ RSpec.describe Invite::RedeemWithEmailCode do
context "when an existing user redeems the invite" do
fab!(: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" do
diff --git a/spec/system/code_login_spec.rb b/spec/system/code_login_spec.rb
index 4ea0cd21a94..594e0823155 100644
--- a/spec/system/code_login_spec.rb
+++ b/spec/system/code_login_spec.rb
@@ -134,12 +134,6 @@ describe "Login via email code" do
expect(page).to have_css(".code-login-form__complete-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")
end
diff --git a/spec/system/code_signup_spec.rb b/spec/system/code_signup_spec.rb
index cbcbbb962d5..d625f794d6e 100644
--- a/spec/system/code_signup_spec.rb
+++ b/spec/system/code_signup_spec.rb
@@ -38,8 +38,6 @@ describe "Sign up via email code" do
end
it "creates a passwordless account, picks a username, and logs in" do
- SiteSetting.enable_random_usernames = true
-
open_code_signup
expect(page).to have_css(".code-login-form__email-step")
expect(page).to have_content(I18n.t("js.code_login.signup_title"))
@@ -53,6 +51,8 @@ describe "Sign up via email code" do
expect(page).to have_css(".code-login-form__complete-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").value
expect(generated).to match(/\A[A-Z][a-z]+[A-Z][a-z]+\d+\z/)
expect(page).to have_no_css(".code-login-form__continue-to-site[disabled]")
@@ -96,7 +96,7 @@ describe "Sign up via email code" do
expect(page).to have_css(".code-login-form__complete-step")
expect(page).to have_css(".login-welcome-header", count: 1)
- expect(page).to have_css(".login-title", text: I18n.t("js.code_login.signup_details_title"))
+ expect(page).to have_css(".login-title", text: I18n.t("js.code_login.account_ready_title"))
expect(page).to have_no_css(".code-login-form__title")
end
@@ -125,8 +125,9 @@ describe "Sign up via email code" do
expect(find("#code-login-username").value).to eq("jane")
end
- it "makes the user pick a username by default" do
+ it "makes the user pick a username when random usernames are disabled" do
SiteSetting.use_email_for_username_and_name_suggestions = false
+ SiteSetting.enable_random_usernames = false
open_code_signup
submit_email("[email protected]")
@@ -134,22 +135,19 @@ describe "Sign up via email code" do
expect(page).to have_css(".code-login-form__complete-step")
expect(page).to have_no_css(".code-login-form__username-regen")
+ # The account carries a generic placeholder name, so it isn't offered up
+ # for the user to accept as-is.
expect(find("#code-login-username").value).to eq("")
expect(page).to have_css(".code-login-form__continue-to-site[disabled]")
- 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").click
expect(page).to have_css(".header-dropdown-toggle.current-user")
expect(User.find_by_email("[email protected]").username).to eq("no-random")
end
- it "lets the user choose their initial username when later changes are disabled" do
+ it "keeps the generated username when usernames can't be changed" do
SiteSetting.username_change_period = 0
open_code_signup
@@ -157,54 +155,22 @@ describe "Sign up via email code" do
fill_code(latest_emailed_code("[email protected]"))
expect(page).to have_css(".code-login-form__complete-step")
- pick_username("locked-name")
+ expect(page).to have_no_css("#code-login-username")
find(".code-login-form__continue-to-site").click
expect(page).to have_css(".header-dropdown-toggle.current-user")
- expect(User.find_by_email("[email protected]").username).to eq("locked-name")
+ expect(User.find_by_email("[email protected]")).to be_present
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__complete-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 "previews a chosen avatar and applies it after creating the account" do
- User.set_callback(:create, :after, :ensure_in_trust_level_group)
-
+ it "opens the avatar picker before continuing" do
open_code_signup
submit_email("[email protected]")
fill_code(latest_emailed_code("[email protected]"))
expect(page).to have_css(".code-login-form__complete-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(".header-dropdown-toggle.current-user img[src*='/user_avatar/']")
- ensure
- User.skip_callback(:create, :after, :ensure_in_trust_level_group)
+ expect(page).to have_css(".avatar-selector-modal")
end
it "shows an error for an incorrect code" do
@@ -237,7 +203,6 @@ describe "Sign up via email code" do
end
it "collects account details before approval and requires a fresh code afterward" do
- SiteSetting.enable_random_usernames = true
SiteSetting.login_required = true
SiteSetting.must_approve_users = true
SiteSetting.full_name_requirement = "required_at_signup"
@@ -361,8 +326,6 @@ describe "Sign up via email code" do
expect(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]")
@@ -451,10 +414,6 @@ describe "Sign up via email code" do
find(".code-login-form__user-fields-step .code-login-form__verify").click
expect(page).to have_css(".code-login-form__complete-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")
end
end