A platform for community discussion. Free, open, simple.
UX: Improve email code approval flow (#43737)
Keegan Georgeb5a3b9954236
diff --git a/app/assets/stylesheets/common/login/code-login-form.scss b/app/assets/stylesheets/common/login/code-login-form.scssindex e922799ff6d..bdaced03143 100644--- a/app/assets/stylesheets/common/login/code-login-form.scss+++ b/app/assets/stylesheets/common/login/code-login-form.scss@@ -49,8 +49,10 @@&__code-step,&__second-factor-step,+ &__account-details-step,&__user-fields-step,- &__complete-step {+ &__complete-step,+ &__pending-approval-step {display: flex;flex-direction: column;align-items: flex-start;@@ -62,6 +64,7 @@}}+ &__account-details-step,&__user-fields-step {.user-fields {align-self: stretch;@@ -69,6 +72,47 @@}}+ &__account-fields {+ display: grid;+ grid-template-columns: minmax(0, 1fr);+ align-self: stretch;+ gap: 1em 0.5em;++ &.--with-username-generator {+ grid-template-columns: minmax(0, 1fr) auto;+ }++ .code-login-form__username-field {+ display: grid;+ grid-template-columns: subgrid;+ grid-column: 1 / -1;+ gap: 0.25em 0.5em;++ > label,+ > .code-login-form__error {+ grid-column: 1 / -1;+ }+ }++ .code-login-form__username-input {+ display: contents;+ }++ .code-login-form__name-field {+ grid-column: 1 / -1;+ }++ .code-login-form__password-field,+ .code-login-form__create-password {+ grid-column: 1;+ }++ .code-login-form__password-field input {+ width: 100%;+ min-width: 0;+ }+ }+&__name-field {display: flex;flex-direction: column;@@ -81,6 +125,12 @@margin: 0;}+ &__password-field {+ align-self: stretch;+ width: 100%;+ margin: 0;+ }+&__new-account {display: flex;flex-direction: column;diff --git a/app/controllers/session_controller.rb b/app/controllers/session_controller.rbindex eb0eac56c25..c728b64cde4 100644--- a/app/controllers/session_controller.rb+++ b/app/controllers/session_controller.rb@@ -38,6 +38,7 @@ class SessionController < ApplicationControllerACTIVATE_USER_KEY = "activate_user"FORGOT_PASSWORD_EMAIL_LIMIT_PER_DAY = 6+ LOGIN_CODE_SIGNUP_KEY_PREFIX = "login-code-signup-"def csrfrender json: { csrf: form_authenticity_token }@@ -538,6 +539,8 @@ class SessionController < ApplicationControllerdef verify_login_codeexpires_now+ return complete_verified_login_code_signup if params[:signup_token].present?+EmailLoginCode::Verify.call(login_code_verification_params) do |result|on_success { |user:| process_verified_login_code(user) }on_failed_contract do |contract|@@ -959,6 +962,8 @@ class SessionController < ApplicationControllerreturn process_verified_invite_login_code(matched_user) if params[:invite_key].present?+ return begin_verified_login_code_signup if pending_approval_signup?(matched_user)+if matched_user.nil? && registration_via_login_code_open?user_fields_required = signup_user_fields_missing?name_required = signup_full_name_missing?@@ -976,6 +981,12 @@ class SessionController < ApplicationControlleron_failed_policy(:can_register_new_account) dorender json: { error: I18n.t("login.new_registrations_disabled") }end+ on_failed_policy(:can_register_from_ip) do+ render json: login_code_registration_ip_limit_error+ end+ on_failed_policy(:username_allowed) do+ render json: { error: I18n.t("login.reserved_username") }+ endon_failed_policy(:required_fields_provided) dorender json: { error: I18n.t("login.missing_user_field") }end@@ -993,6 +1004,97 @@ class SessionController < ApplicationController# Required signup details are only collected once the code has proven# ownership of the inbox, so these responses can't be used to probe whether# an account exists.+ def pending_approval_signup?(matched_user)+ matched_user.nil? && registration_via_login_code_open? && SiteSetting.must_approve_users? &&+ !EmailValidator.can_auto_approve_user?(params[:email].to_s.strip.downcase)+ end++ def begin_verified_login_code_signup+ login_code = EmailLoginCode.login.active.for_email(params[:email].to_s.strip).first+ return render json: invalid_login_code if login_code.blank?++ token = SecureRandom.hex(32)+ expires_in = (login_code.expires_at - Time.zone.now).ceil+ return render json: invalid_login_code if expires_in <= 0++ proof = { email: login_code.email, code: params[:code] }.merge(verified_login_code_signup_proof)+ server_session.set("#{LOGIN_CODE_SIGNUP_KEY_PREFIX}#{token}", proof, expires: expires_in)++ username =+ UserNameSuggester.suggest(login_code.email, allow_generic_fallback: false) ||+ RandomUsernameGenerator.generate++ render json: {+ signup_details_required: true,+ signup_token: token,+ username: username,+ expires_in: expires_in,+ }+ end++ def complete_verified_login_code_signup+ token = params[:signup_token].to_s+ proof = verified_login_code_signup_proof_for(token)+ return render json: invalid_login_code if !proof.is_a?(Hash)++ key = "#{LOGIN_CODE_SIGNUP_KEY_PREFIX}#{token}"+ return render json: invalid_login_code if !SiteSetting.must_approve_users?+ return render json: invalid_login_code if EmailValidator.can_auto_approve_user?(proof[:email])++ signup_params = params.permit(:username, :name, :password, user_fields: {}).to_h+ EmailLoginCode::Redeem.call(+ service_params.deep_merge(+ ip_address: request.remote_ip,+ params:+ signup_params.merge(+ email: proof[:email],+ code: proof[:code],+ new_account_required: true,+ username_required: true,+ ),+ ),+ ) do |result|+ on_success do |user:, existing_user:|+ server_session.delete(key)+ login_with_login_code(user, created_account: existing_user.nil?)+ end+ on_failed_policy(:new_account_available) { render json: invalid_login_code }+ on_failed_policy(:can_register_new_account) do+ render json: { error: I18n.t("login.new_registrations_disabled") }+ end+ on_failed_policy(:can_register_from_ip) do+ render json: login_code_registration_ip_limit_error+ end+ on_failed_policy(:required_username_provided) do+ render json: { error: I18n.t("login.missing_username") }+ end+ on_failed_policy(:username_allowed) do+ 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") }+ end+ on_failed_policy(:required_full_name_provided) do+ render json: { error: I18n.t("login.missing_full_name") }+ end+ on_model_errors(:user) { |user| render json: login_code_signup_error(user) }+ on_failed_contract do |contract|+ render json: { error: contract.errors.full_messages.join(". ") }+ end+ on_failure { render json: invalid_login_code }+ end+ end++ def verified_login_code_signup_proof+ {}+ end++ def verified_login_code_signup_proof_for(token)+ return if token !~ /\A[0-9a-f]{64}\z/++ server_session["#{LOGIN_CODE_SIGNUP_KEY_PREFIX}#{token}"]+ end+def signup_user_fields_missing?params[:user_fields].blank? && UserField.required.where(show_on_signup: true).exists?end@@ -1034,7 +1136,7 @@ class SessionController < ApplicationControllerraise Discourse::ReadOnly if @staff_writes_only_mode && !user.staff?if login_not_approved_for?(user)- render json: login_not_approved+ render json: { pending_approval: true }elsif payload = login_error_check(user)render json: payloadelsif created_account@@ -1124,6 +1226,9 @@ class SessionController < ApplicationControlleron_failed_policy(:can_register_new_account) dorender json: { error: I18n.t("login.new_registrations_disabled") }end+ on_failed_policy(:can_register_from_ip) do+ render json: login_code_registration_ip_limit_error+ endon_failed_policy(:required_fields_provided) dorender json: { error: I18n.t("login.missing_user_field") }end@@ -1176,6 +1281,13 @@ class SessionController < ApplicationController}end+ def login_code_signup_error(user)+ response = { error: user.errors.full_messages.join(". ") }+ password_errors = user.user_password&.errors&.full_messages_for(:password)+ response[:password_error] = password_errors.join(". ") if password_errors.present?+ response+ end+def login_code_account_error(user)ip_error =user.errors.find do |error|diff --git a/app/controllers/users_controller.rb b/app/controllers/users_controller.rbindex 460dff39d6f..b95a5bc62ac 100644--- a/app/controllers/users_controller.rb+++ b/app/controllers/users_controller.rb@@ -87,6 +87,7 @@ class UsersController < ApplicationControllerupdate_security_key]before_action :respond_to_suspicious_request, only: [:create]+ before_action :ensure_random_username_access, only: [:generate_random_username]# we need to allow account creation with bad CSRF tokens, if people are caching, the CSRF token on the# page is going to be empty, this means that server will see an invalid CSRF and blow the session@@ -109,6 +110,7 @@ class UsersController < ApplicationControlleremail_loginadmin_loginconfirm_admin+ generate_random_username]skip_before_action :redirect_to_profile_if_required, only: %i[show staff_info update]@@ -651,8 +653,6 @@ class UsersController < ApplicationControllerenddef generate_random_username- raise Discourse::NotFound if !SiteSetting.enable_random_usernames-RateLimiter.new(nil, "random-username-#{request.remote_ip}", 20, 1.minute).performed!username = RandomUsernameGenerator.generate@@ -2182,6 +2182,19 @@ class UsersController < ApplicationControllerprivate+ def ensure_random_username_access+ raise Discourse::NotFound if !SiteSetting.enable_random_usernames+ return redirect_to_login_if_required if current_user+ return if !SiteSetting.login_required?++ signup_token = request.headers["X-Discourse-Signup-Token"].to_s+ signup_proof =+ if signup_token.match?(/\A[0-9a-f]{64}\z/)+ server_session["#{SessionController::LOGIN_CODE_SIGNUP_KEY_PREFIX}#{signup_token}"]+ end+ raise Discourse::InvalidAccess if !signup_proof.is_a?(Hash)+ end+def assign_topic_post_count(user_serializer)topic_id = params[:include_post_count_for].to_iif topic_id != 0 && guardian.can_see?(Topic.find_by_id(topic_id))@@ -2331,16 +2344,7 @@ class UsersController < ApplicationControllerenddef clashing_with_existing_route?(username)- normalized_username = User.normalize_username(username)- http_verbs = %w[GET POST PUT DELETE PATCH]- allowed_actions = %w[show update destroy]-- http_verbs.any? do |verb|- path = Rails.application.routes.recognize_path("/u/#{normalized_username}", method: verb)- allowed_actions.exclude?(path[:action])- rescue ActionController::RoutingError- false- end+ UsernameValidator.clashing_with_existing_route?(username)enddef confirm_server_sessiondiff --git a/app/mailers/user_notifications.rb b/app/mailers/user_notifications.rbindex 4af517e7cdb..215773e5ef1 100644--- a/app/mailers/user_notifications.rb+++ b/app/mailers/user_notifications.rb@@ -30,10 +30,18 @@ class UserNotifications < ActionMailer::Baselocale: locale,)+ login_url =+ if !user.has_password? && Invite.email_code_enabled?(user)+ "#{Discourse.base_url}/login?mode=code"+ else+ Discourse.base_url+ end+build_email(user.email,template: "user_notifications.signup_after_approval",locale: locale,+ login_url:,new_user_tips: tips,recipient_user: user,)diff --git a/app/models/user.rb b/app/models/user.rbindex 59af9eaac75..a7783dd9efa 100644--- a/app/models/user.rb+++ b/app/models/user.rb@@ -253,6 +253,7 @@ class User < ActiveRecord::Base# Skip validating email, for example from a particular auth provider pluginattr_accessor :skip_email_validation+ attr_accessor :enforce_username_restrictions# Whether we need to be sending a system message after creationattr_accessor :send_welcome_message@@ -2156,6 +2157,14 @@ class User < ActiveRecord::Baseusername_format_validator ||beginif will_save_change_to_username?+ if enforce_username_restrictions &&+ (+ User.reserved_username?(username) ||+ UsernameValidator.clashing_with_existing_route?(username)+ )+ errors.add(:username, I18n.t("login.reserved_username"))+ end+existing =DB.query(USERNAME_EXISTS_SQL, username: self.class.normalize_username(username))diff --git a/app/models/username_validator.rb b/app/models/username_validator.rbindex 9f96703c780..72645a94a2c 100644--- a/app/models/username_validator.rb+++ b/app/models/username_validator.rb@@ -15,6 +15,19 @@ class UsernameValidatorendend+ def self.clashing_with_existing_route?(username)+ normalized_username = User.normalize_username(username)+ http_verbs = %w[GET POST PUT DELETE PATCH]+ allowed_actions = %w[show update destroy]++ http_verbs.any? do |verb|+ path = Rails.application.routes.recognize_path("/u/#{normalized_username}", method: verb)+ allowed_actions.exclude?(path[:action])+ rescue ActionController::RoutingError+ false+ end+ end+def initialize(username, skip_length_validation: false, object: nil)@username = username&.unicode_normalize@skip_length_validation = skip_length_validationdiff --git a/app/services/email_login_code/redeem.rb b/app/services/email_login_code/redeem.rbindex 8aeb3d071ef..b7afb21c430 100644--- a/app/services/email_login_code/redeem.rb+++ b/app/services/email_login_code/redeem.rb@@ -6,6 +6,10 @@ class EmailLoginCode::Redeemparams base_class: EmailLoginCode::Verify::Contract doattribute :user_fieldsattribute :name, :string+ attribute :password, :string+ attribute :username, :string+ attribute :username_required, :boolean, default: false+ attribute :new_account_required, :boolean, default: falsebefore_validation do# Only hash-like input can carry field values; anything else (a stray@@ -20,16 +24,22 @@ class EmailLoginCode::Redeemend)self.name = name.to_s.strip.presence+ self.username = username.to_s.strip.presenceendvalidates :name, length: { maximum: 255 }+ validates :password, length: { maximum: User.max_password_length }, allow_nil: trueendmodel :login_codepolicy :code_matchesmodel :existing_user, :fetch_existing_user, optional: true+ policy :new_account_availablepolicy :email_available_for_new_accountpolicy :can_register_new_account+ policy :can_register_from_ip+ policy :required_username_provided+ policy :username_allowedpolicy :required_fields_providedpolicy :required_full_name_provided@@ -63,6 +73,10 @@ class EmailLoginCode::Redeem# belong to an existing account once normalized (e.g. a Gmail alias). Such a# code can neither log in nor create an account, so it's treated as invalid# (via the controller's generic failure) rather than leaking a reason.+ def new_account_available(existing_user:, params:)+ !params.new_account_required || existing_user.blank?+ end+def email_available_for_new_account(existing_user:, params:)return true if existing_user.present?@@ -80,6 +94,21 @@ class EmailLoginCode::Redeem!ScreenedEmail.should_block?(params.email)end+ def can_register_from_ip(existing_user:, ip_address:)+ 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?++ !User.reserved_username?(params.username) &&+ !UsernameValidator.clashing_with_existing_route?(params.username)+ end+def required_fields_provided(existing_user:, params:)return true if existing_user.present?@@ -116,6 +145,8 @@ class EmailLoginCode::Redeemip_address: ip_address,user_fields: params.user_fields,name: params.name,+ password: params.password,+ username: params.username,)enddiff --git a/app/services/user/action/create_from_verified_email.rb b/app/services/user/action/create_from_verified_email.rbindex fe4fc59d2be..c4644e37369 100644--- a/app/services/user/action/create_from_verified_email.rb+++ b/app/services/user/action/create_from_verified_email.rb@@ -5,6 +5,8 @@ class User::Action::CreateFromVerifiedEmail < Service::ActionBaseoption :ip_address, optional: trueoption :user_fields, optional: trueoption :name, optional: true+ option :password, optional: true+ option :username, optional: truedef callraise Discourse::SiteArchived if SiteSetting.site_archived@@ -12,7 +14,7 @@ class User::Action::CreateFromVerifiedEmail < Service::ActionBase# A random name beats the generic "userN" fallback here: there is no# signup form where the user could pick one before the account exists.# Sites that turn random names off fall through to that generic name.- username =+ suggested_username =UserNameSuggester.suggest(email, allow_generic_fallback: false) ||RandomUsernameGenerator.generate || UserNameSuggester.suggest(email)@@ -22,7 +24,7 @@ class User::Action::CreateFromVerifiedEmail < Service::ActionBaseuser.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,@@ -33,6 +35,9 @@ class User::Action::CreateFromVerifiedEmail < Service::ActionBase}assign_user_fields(user)+ user.password = password if password.present?++ user.enforce_username_restrictions = username.present?if SiteSetting.must_approve_users? && EmailValidator.can_auto_approve_user?(email)ReviewableUser.set_approved_fields!(user, Discourse.system_user)diff --git a/app/services/username_checker_service.rb b/app/services/username_checker_service.rbindex 3540d007150..fc007829bc2 100644--- a/app/services/username_checker_service.rb+++ b/app/services/username_checker_service.rb@@ -18,7 +18,8 @@ class UsernameCheckerServicedef check_username_availability(username, email)available =- User.username_available?(username, email, allow_reserved_username: @allow_reserved_username)+ !UsernameValidator.clashing_with_existing_route?(username) &&+ User.username_available?(username, email, allow_reserved_username: @allow_reserved_username)if available{ available: true, is_developer: is_developer?(email) }diff --git a/config/locales/client.en.yml b/config/locales/client.en.ymlindex 8cd6e2264a0..5f17b6fb203 100644--- a/config/locales/client.en.yml+++ b/config/locales/client.en.yml@@ -3155,6 +3155,12 @@ en: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."+ create_password_optional: "Create a password (optional)"+ submit_for_approval: "Submit for approval"+ pending_approval_title: "Your account is awaiting approval."+ pending_approval_instructions: "A staff member must approve your account before you can log in. We’ll email you when it’s approved."username_label: "Username"username_placeholder: "Choose a username"regenerate_username: "Suggest a random username"diff --git a/config/locales/server.en.yml b/config/locales/server.en.ymlindex ae81c7099b2..dbf5a4cb1ad 100644--- a/config/locales/server.en.yml+++ b/config/locales/server.en.yml@@ -3581,6 +3581,7 @@ en:wrong_invite_code: "The invite code you entered was incorrect."reserved_username: "That username is not allowed."missing_user_field: "You have not completed all the required user fields"+ missing_username: "Please enter a username"missing_full_name: "Please enter your full name"auth_complete: "Authentication is complete."click_to_continue: "Click here to continue."@@ -5261,7 +5262,7 @@ en:A staff member approved your account on %{site_name}.You can now access your new account by logging in at:- %{base_url}+ %{login_url}If the above link is not clickable, try copying and pasting it into the address bar of your web browser.diff --git a/frontend/discourse/app/components/code-login-form.gjs b/frontend/discourse/app/components/code-login-form.gjsindex fa81d6f8af3..23e45ceccd2 100644--- a/frontend/discourse/app/components/code-login-form.gjs+++ b/frontend/discourse/app/components/code-login-form.gjs@@ -3,7 +3,7 @@ import { tracked } from "@glimmer/tracking";import { hash } from "@ember/helper";import { on } from "@ember/modifier";import { action } from "@ember/object";-import { cancel } from "@ember/runloop";+import { cancel, schedule } from "@ember/runloop";import { service } from "@ember/service";import { trustHTML } from "@ember/template";import Form from "discourse/components/form";@@ -22,6 +22,7 @@ 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,@@ -31,20 +32,26 @@ import UserFieldsValidationHelper from "discourse/lib/user-fields-validation-helimport { emailValid } from "discourse/lib/utilities";import { getWebauthnCredential } from "discourse/lib/webauthn";import User, { SECOND_FACTOR_METHODS } from "discourse/models/user";+import { or } from "discourse/truth-helpers";import DButton from "discourse/ui-kit/d-button";+import DInputTip from "discourse/ui-kit/d-input-tip";import DOtp from "discourse/ui-kit/d-otp";+import DPasswordField from "discourse/ui-kit/d-password-field";import DSecondFactorInput from "discourse/ui-kit/d-second-factor-input";+import DTogglePasswordMask from "discourse/ui-kit/d-toggle-password-mask";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";const RESEND_COOLDOWN_SECONDS = 30;+const SIGNUP_CONTINUATION_KEY = "email-code-signup-continuation";export default class CodeLoginForm extends Component {@service login;@service site;@service siteSettings;@service modal;+ @service sessionStore;@tracked email = this.args.initialEmail ?? "";@tracked verifying = false;@@ -55,7 +62,12 @@ export default class CodeLoginForm extends Component {@tracked newAccount;@tracked accountUser;@tracked name = "";+ @tracked accountPassword = "";+ @tracked showOptionalPassword = false;+ @tracked maskPassword = true;+ @tracked capsLockOn = false;@tracked nameRequired = false;+ @tracked signupToken;@tracked nameError;@tracked username = "";@tracked usernameAvailable = false;@@ -74,19 +86,26 @@ export default class CodeLoginForm extends Component {@tracked securityKeyChallenge;@tracked securityKeyAllowedCredentialIds;code = "";+ passwordValidationHelper = new PasswordValidationHelper(this);userFieldsValidationHelper = new UserFieldsValidationHelper({getUserFields: () =>this.site.get("user_fields")?.filter((f) => f.show_on_signup),- getAccountPassword: () => null,+ getAccountPassword: () => this.accountPassword,showValidationOnInit: false,});#cooldownTimer;+ #draftEmail;#postSignupRedirectUrl;#usernameCheckSeq = 0;- @tracked _step = this.args.initialStep ?? "email";+ @tracked _step;constructor() {super(...arguments);+ if (this.isSignup && this.#restoreSignupContinuation()) {+ return;+ }++ this._step = this.args.initialStep ?? "email";if (this.isCodeStep) {this.startResendCooldown();}@@ -149,8 +168,29 @@ export default class CodeLoginForm extends Component {return this.step === "complete";}- // Login has its own page heading; only signup needs a per-step one here.+ get isAccountDetailsStep() {+ return this.step === "account-details";+ }++ get isPendingApprovalStep() {+ return this.step === "pending-approval";+ }+get heading() {+ if (this.isAccountDetailsStep) {+ return {+ title: i18n("code_login.account_details_title"),+ subtitle: i18n("code_login.account_details_instructions"),+ };+ }++ if (this.isPendingApprovalStep) {+ return {+ title: i18n("code_login.pending_approval_title"),+ subtitle: i18n("code_login.pending_approval_instructions"),+ };+ }+if (!this.isSignup) {return null;}@@ -181,7 +221,7 @@ export default class CodeLoginForm extends Component {}get continueDisabled() {- if (this.verifying) {+ if (this.verifying || this.passwordValidation.failed) {return true;}// When the username can't be changed there's nothing to validate.@@ -195,6 +235,30 @@ export default class CodeLoginForm extends Component {return this.userFieldsValidationHelper.userFields;}+ get accountEmail() {+ return this.email;+ }++ get accountName() {+ return this.name;+ }++ get accountUsername() {+ return this.username;+ }++ get passwordRequired() {+ return this.accountPassword.length > 0;+ }++ get passwordValidation() {+ return this.passwordValidationHelper.passwordValidation;+ }++ get showPasswordValidation() {+ return this.accountPassword.length > 0 && this.passwordValidation.reason;+ }+// Re-rendering DOtp with a fresh identity is the only way to clear itget otpGenerationArray() {return [this.otpGeneration];@@ -239,6 +303,18 @@ export default class CodeLoginForm extends Component {await this.sendCode();}+ @action+ captureEmail(event) {+ this.#draftEmail = event.currentTarget+ .closest(".code-login-form")+ .querySelector('input[type="email"]')?.value;+ }++ @action+ usePassword() {+ this.args.onUsePassword?.(this.#draftEmail ?? this.email);+ }+@actionasync requestCode() {if (this.verifying) {@@ -266,11 +342,14 @@ export default class CodeLoginForm extends Component {@actionchangeEmail() {cancel(this.#cooldownTimer);+ this.accountPassword = "";+ this.showOptionalPassword = false;this.resendCooldown = 0;this.code = "";this.codeError = null;this.notice = null;this.otpGeneration++;+ this.#clearSignupContinuation();this.step = "email";this.args.onChangeEmail?.();}@@ -377,6 +456,18 @@ export default class CodeLoginForm extends Component {return;}+ if (result?.signup_details_required) {+ this.#setupSignupContinuation(result);+ this.step = "account-details";+ return;+ }++ if (result?.pending_approval) {+ this.#clearSignupContinuation();+ this.step = "pending-approval";+ return;+ }+if (result?.account_created) {this.setupNewAccount(result);this.step = "complete";@@ -401,6 +492,22 @@ export default class CodeLoginForm extends Component {this.nameError = null;}+ @action+ revealOptionalPassword() {+ this.showOptionalPassword = true;+ }++ @action+ passwordChanged(event) {+ this.accountPassword = event.target.value;+ this.codeError = null;+ }++ @action+ togglePasswordMask() {+ this.maskPassword = !this.maskPassword;+ }+@actionasync submitUserFields() {this.userFieldsValidationHelper.validationVisible = true;@@ -451,7 +558,9 @@ export default class CodeLoginForm extends Component {// Hold the rolling state for at least one animation cycle so a fast// response doesn't cut the dice spin (and the text fade) short.const [result] = await Promise.all([- ajax("/u/random-username.json"),+ ajax("/u/random-username.json", {+ headers: { "X-Discourse-Signup-Token": this.signupToken },+ }),new Promise((resolve) => discourseLater(resolve, 400)),]);@@ -497,7 +606,7 @@ export default class CodeLoginForm extends Component {const result = await User.checkUsername(username,this.email,- this.newAccount.id+ this.newAccount?.id);if (seq !== this.#usernameCheckSeq) {@@ -558,6 +667,73 @@ export default class CodeLoginForm extends Component {}}+ @action+ async submitAccountDetails() {+ this.userFieldsValidationHelper.validationVisible = true;+ if (this.site.full_name_required_for_signup && !this.name.trim()) {+ this.nameError = i18n("user.name.required");+ }+ if (+ this.continueDisabled ||+ this.nameError ||+ this.userFieldsValidationHelper.userFieldsValidation.failed+ ) {+ return;+ }++ this.verifying = true;+ this.codeError = null;++ const data = {+ signup_token: this.signupToken,+ username: this.username.trim(),+ user_fields: {},+ };+ if (this.site.full_name_visible_in_signup) {+ data.name = this.name.trim();+ }+ if (this.accountPassword) {+ data.password = this.accountPassword;+ }+ this.userFields.forEach((field) => {+ data.user_fields[field.field.id] = field.value;+ });++ try {+ const result = await ajax("/session/login-code/verify", {+ type: "POST",+ data,+ });++ if (result?.pending_approval) {+ this.accountPassword = "";+ this.#clearSignupContinuation();+ this.step = "pending-approval";+ } else if (result?.error) {+ if (result.password_error && this.accountPassword) {+ this.passwordValidationHelper.rejectedPasswords.push(+ this.accountPassword+ );+ this.passwordValidationHelper.rejectedPasswordsMessages.set(+ this.accountPassword,+ result.password_error+ );+ }+ this.codeError = result.error;+ } else {+ this.redirectAfterLogin(result?.redirect_url);+ }+ } catch (e) {+ if (isReadOnlyError(e)) {+ this.codeError = this.login.readOnlyLoginMessage;+ } else {+ popupAjaxError(e);+ }+ } finally {+ this.verifying = false;+ }+ }+@actionasync continueAfterSignup() {if (this.continueDisabled) {@@ -691,6 +867,61 @@ export default class CodeLoginForm extends Component {}, 1000);}+ #setupSignupContinuation(result) {+ this.signupToken = result.signup_token;+ this.username = result.username || "";+ this.usernameAvailable = false;+ this.usernameError = null;+ this.nameRequired = this.site.full_name_required_for_signup;++ this.sessionStore.setObject({+ key: SIGNUP_CONTINUATION_KEY,+ value: {+ email: this.email,+ expiresAt: Date.now() + result.expires_in * 1000,+ signupToken: this.signupToken,+ username: this.username,+ },+ });++ if (this.username) {+ this.checkUsernameAvailability();+ }+ }++ #restoreSignupContinuation() {+ const continuation = this.sessionStore.getObject(SIGNUP_CONTINUATION_KEY);+ if (+ !continuation?.email ||+ !continuation.signupToken ||+ !continuation.expiresAt ||+ continuation.expiresAt <= Date.now()+ ) {+ this.#clearSignupContinuation();+ return false;+ }++ this.email = continuation.email;+ this.signupToken = continuation.signupToken;+ this.username = continuation.username || "";+ this.nameRequired = this.site.full_name_required_for_signup;+ this._step = "account-details";+ schedule("afterRender", () => {+ if (!this.isDestroying) {+ this.args.onStepChange?.(this.step);+ }+ });+ if (this.username) {+ this.checkUsernameAvailability();+ }+ return true;+ }++ #clearSignupContinuation() {+ this.signupToken = null;+ this.sessionStore.remove(SIGNUP_CONTINUATION_KEY);+ }+// 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.@@ -839,8 +1070,12 @@ export default class CodeLoginForm extends Component {{{#if @onUsePassword}}<DButtonclass="btn-flat code-login-form__password-toggle"- @action={{@onUsePassword}}- @label="code_login.use_password_instead"+ @action={{this.usePassword}}+ @label={{or+ @usePasswordLabel+ "code_login.use_password_instead"+ }}+ {{on "click" this.captureEmail}}/>{{/if}}</div>@@ -906,6 +1141,169 @@ export default class CodeLoginForm extends Component {{{/unless}}</div></div>+ {{else if this.isAccountDetailsStep}}+ <div class="code-login-form__account-details-step">+ <div+ class="code-login-form__account-fields+ {{if+ this.siteSettings.enable_random_usernames+ '--with-username-generator'+ }}"+ >+ <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="username"+ 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 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>++ {{#if this.site.full_name_visible_in_signup}}+ <div class="code-login-form__name-field">+ <label for="code-login-name">+ {{i18n "user.name.title"}}+ </label>+ <input+ aria-describedby="code-login-name-error"+ aria-invalid={{if this.nameError "true"}}+ autocomplete="name"+ class="code-login-form__name"+ id="code-login-name"+ maxlength="255"+ name="name"+ type="text"+ value={{this.name}}+ {{on "input" this.nameChanged}}+ />+ <div+ aria-live="polite"+ class="code-login-form__error"+ id="code-login-name-error"+ role="alert"+ >+ {{this.nameError}}+ </div>+ </div>+ {{/if}}++ {{#if this.showOptionalPassword}}+ <div+ class="input-group create-account__password code-login-form__password-field"+ >+ <DPasswordField+ aria-describedby="password-validation password-validation-more-info"+ aria-invalid={{this.passwordValidation.failed}}+ autocomplete="new-password"+ id="new-account-password"+ type={{if this.maskPassword "password" "text"}}+ @capsLockOn={{this.capsLockOn}}+ @value={{this.accountPassword}}+ {{on "input" this.passwordChanged}}+ />+ <label class="alt-placeholder" for="new-account-password">+ {{i18n "user.password.title"}}+ </label>+ <DTogglePasswordMask+ @maskPassword={{this.maskPassword}}+ @togglePasswordMask={{this.togglePasswordMask}}+ />+ <div class="create-account__password-info">+ <div class="create-account__password-tip-validation">+ {{#if this.showPasswordValidation}}+ <DInputTip+ id="password-validation"+ @validation={{this.passwordValidation}}+ />+ {{else if+ this.siteSettings.show_signup_form_password_instructions+ }}+ <span+ class="more-info"+ id="password-validation-more-info"+ >+ {{this.passwordValidationHelper.passwordInstructions}}+ </span>+ {{/if}}+ <div+ class="caps-lock-warning+ {{unless this.capsLockOn 'hidden'}}"+ >+ {{dIcon "triangle-exclamation"}}+ {{i18n "login.caps_lock_warning"}}+ </div>+ </div>+ </div>+ </div>+ {{else}}+ <DButton+ class="btn-link code-login-form__create-password"+ @action={{this.revealOptionalPassword}}+ @label="code_login.create_password_optional"+ />+ {{/if}}++ </div>+ <div class="user-fields">+ {{#each this.userFields as |f|}}+ <div class="input-group">+ <UserField+ class={{valueEntered f.value}}+ @field={{f.field}}+ @validation={{f.validation}}+ @value={{f.value}}+ />+ </div>+ {{/each}}+ </div>++ <div aria-live="polite" class="code-login-form__error" role="alert">+ {{this.codeError}}+ </div>++ <div class="code-login-form__actions">+ <DButton+ class="btn-primary code-login-form__submit-approval"+ @action={{this.submitAccountDetails}}+ @disabled={{this.continueDisabled}}+ @isLoading={{this.verifying}}+ @label="code_login.submit_for_approval"+ />+ </div>+ </div>+ {{else if this.isPendingApprovalStep}}+ <div class="code-login-form__pending-approval-step" role="status"></div>{{else if this.isCompleteStep}}<div class="code-login-form__complete-step">{{#unless this.isSignup}}diff --git a/frontend/discourse/app/controllers/login.js b/frontend/discourse/app/controllers/login.jsindex 4fac3416be8..cb2f3a06e09 100644--- a/frontend/discourse/app/controllers/login.js+++ b/frontend/discourse/app/controllers/login.js@@ -21,17 +21,19 @@ import { i18n } from "discourse-i18n";export default class LoginPageController extends Controller {@service siteSettings;+@service capabilities;@service dialog;// eslint-disable-next-line discourse/no-unused-services@service site; // used in the route template@service login;@service modal;-@controller application;@tracked loggingIn = false;+@tracked loggedIn = false;+ @tracked codeLoginSelected = false;@tracked showLoginButtons = true;@tracked showLogin = true;@tracked showSecondFactor = false;@@ -49,7 +51,8 @@ export default class LoginPageController extends Controller {@tracked secondFactorToken;@tracked flash;@tracked flashType;- @tracked showCodeLoginForm = false;+ @tracked loginMode = null;+ queryParams = [{ loginMode: "mode" }];@computed("siteSettings.enable_local_logins")get canLoginLocal() {@@ -64,6 +67,13 @@ export default class LoginPageController extends Controller {);}+ get showCodeLoginForm() {+ return (+ this.canUseCodeLogin &&+ (this.codeLoginSelected || this.loginMode === "code")+ );+ }+@computed("siteSettings.enable_local_logins_via_email")get canLoginLocalWithEmail() {return this.siteSettings.enable_local_logins_via_email;@@ -89,8 +99,7 @@ export default class LoginPageController extends Controller {if (this.hasAtLeastOneLoginButton &&!this.showSecondFactor &&- !this.showSecurityKey &&- !this.showCodeLoginForm+ !this.showSecurityKey) {classes.push("has-alt-auth");}@@ -170,12 +179,18 @@ export default class LoginPageController extends Controller {@actionshowCodeLogin() {- this.showCodeLoginForm = true;+ this.codeLoginSelected = true;}@action- usePassword() {- this.showCodeLoginForm = false;+ usePassword(email) {+ if (typeof email === "string") {+ this.loginName = email;+ }+ this.codeLoginSelected = false;+ if (this.loginMode === "code") {+ this.loginMode = "password";+ }}@actiondiff --git a/frontend/discourse/app/controllers/signup.js b/frontend/discourse/app/controllers/signup.jsindex 33cfea6df30..b1a8b8da85f 100644--- a/frontend/discourse/app/controllers/signup.js+++ b/frontend/discourse/app/controllers/signup.js@@ -125,10 +125,17 @@ export default class SignupPageController extends Controller {);}- @computed("hasAuthOptions", "canCreateLocal", "skipConfirmation")+ @computed(+ "hasAuthOptions",+ "canCreateLocal",+ "siteSettings.enable_local_logins_via_code",+ "siteSettings.enable_local_logins_via_email",+ "skipConfirmation"+ )get showCodeSignupForm() {return (this.siteSettings.enable_local_logins_via_code &&+ this.siteSettings.enable_local_logins_via_email &&this.canCreateLocal &&!this.hasAuthOptions &&!this.skipConfirmationdiff --git a/frontend/discourse/app/routes/login.js b/frontend/discourse/app/routes/login.jsindex a089e797a25..e5b9b23d529 100644--- a/frontend/discourse/app/routes/login.js+++ b/frontend/discourse/app/routes/login.js@@ -98,4 +98,9 @@ export default class extends DiscourseRoute {}}}++ setupController(controller) {+ super.setupController(...arguments);+ controller.codeLoginSelected = false;+ }}diff --git a/frontend/discourse/app/templates/login.gjs b/frontend/discourse/app/templates/login.gjsindex cadd334d1e1..61584199979 100644--- a/frontend/discourse/app/templates/login.gjs+++ b/frontend/discourse/app/templates/login.gjs@@ -47,11 +47,7 @@ export default <template>@outletArgs={{lazyHash [email protected]}}/></WelcomeHeader>- {{#if- (and- @controller.showLoginButtons (not @controller.showCodeLoginForm)- )- }}+ {{#if @controller.showLoginButtons}}<LoginButtons@context="login"@@ -135,13 +131,7 @@ export default <template></div>{{/if}}- {{#if- (and- @controller.showLoginButtons- @controller.site.desktopView- (not @controller.showCodeLoginForm)- )- }}+ {{#if (and @controller.showLoginButtons @controller.site.desktopView)}}{{#unless @controller.canLoginLocal}}<div class="login-left-side">diff --git a/frontend/discourse/tests/acceptance/create-account-test.js b/frontend/discourse/tests/acceptance/create-account-test.jsindex 4ed3c76c7ef..b45fa62bfce 100644--- a/frontend/discourse/tests/acceptance/create-account-test.js+++ b/frontend/discourse/tests/acceptance/create-account-test.js@@ -147,6 +147,53 @@ acceptance("Create Account", function () {});});+acceptance("Create Account with email code available", function (needs) {+ needs.settings({+ enable_local_logins_via_code: true,+ enable_local_logins_via_email: true,+ });++ test("defaults to email-only signup", async function (assert) {+ await visit("/signup");++ assert+ .dom(".code-login-form__email-step")+ .exists("shows email-code signup");+ assert+ .dom("#new-account-password")+ .doesNotExist("does not show a password field");+ });++ test("restores a verified signup after a full page load", async function (assert) {+ this.owner.lookup("service:session-store").setObject({+ key: "email-code-signup-continuation",+ value: {+ email: "[email protected]",+ expiresAt: Date.now() + 60_000,+ signupToken: "signup-token",+ username: "",+ },+ });++ await visit("/signup");++ assert+ .dom(".code-login-form__account-details-step")+ .exists("restores the account details step");+ assert+ .dom(".code-login-form__hidden-email")+ .hasValue("[email protected]", "preserves the verified email");+ });++ test("uses traditional signup when email-code signup is unavailable", async function (assert) {+ this.siteSettings.enable_local_logins_via_email = false;+ await visit("/signup");++ assert.dom("#new-account-password").exists("shows traditional signup");+ assert.dom(".code-login-form").doesNotExist("does not show code signup");+ });+});+acceptance("Create Account - full name requirement", function () {test("full name required", async function (assert) {const site = Site.current();diff --git a/frontend/discourse/tests/acceptance/sign-in-test.js b/frontend/discourse/tests/acceptance/sign-in-test.jsindex 221d4abd808..c14f5e63098 100644--- a/frontend/discourse/tests/acceptance/sign-in-test.js+++ b/frontend/discourse/tests/acceptance/sign-in-test.js@@ -19,7 +19,7 @@ function sessionRequests() {}acceptance("Signing In", function (needs) {- needs.settings({ enable_local_logins_via_code: true });+ needs.settings({ enable_local_logins_via_code: false });test("submits username credentials with the login button", async function (assert) {await visit("/login");@@ -67,20 +67,6 @@ acceptance("Signing In", function (needs) {assert.dom(".code-login-form").doesNotExist("keeps the password flow");});- test("opens code login only from its explicit link", async function (assert) {- await visit("/login");-- await click("#one-time-code-link");-- assert.dom("#login-form").doesNotExist("hides the password form");- assert.dom(".code-login-form").exists("shows the code login form");- assert.strictEqual(- sessionRequests().length,- 0,- "does not try password login"- );- });-test("sign in", async function (assert) {await visit("/");await click("header .login-button");@@ -230,3 +216,50 @@ acceptance("Signing In", function (needs) {.exists("shows an error when the code is invalid");});});++acceptance("Signing In with code", function (needs) {+ needs.settings({ enable_local_logins_via_code: true });++ test("defaults to password login and offers code login", async function (assert) {+ await visit("/login");++ assert.dom("#login-form").exists("shows the password form");+ assert.dom(".code-login-form").doesNotExist("does not open code login");+ assert.dom("#one-time-code-link").exists("offers code login");++ await fillIn("#login-account-name", "[email protected]");+ await click("#one-time-code-link");++ assert.dom(".code-login-form").exists("opens code login explicitly");+ assert+ .dom(".code-login-form__email-step input")+ .hasValue("[email protected]", "preserves the entered email");+ assert+ .dom("#login-buttons .btn-social")+ .isVisible("keeps external login methods accessible");++ await fillIn(".code-login-form__email-step input", "[email protected]");+ await click(".code-login-form__password-toggle");++ assert.dom("#login-form").exists("returns to password login");+ assert+ .dom("#login-account-name")+ .hasValue("[email protected]", "preserves the updated email");+ assert.strictEqual(sessionRequests().length, 0, "does not submit a login");+ });++ test("only an available explicit code mode opens code login", async function (assert) {+ await visit("/login?mode=code");+ assert.dom(".code-login-form").exists("opens the available code login");++ await visit("/login?mode=unknown");+ assert.dom("#login-form").exists("ignores an unknown login mode");++ this.siteSettings.enable_local_logins_via_code = false;+ await visit("/login?mode=code");+ assert.dom("#login-form").exists("ignores unavailable code login");+ assert+ .dom("#one-time-code-link")+ .doesNotExist("hides the unavailable option");+ });+});diff --git a/frontend/discourse/tests/integration/components/code-login-form-test.gjs b/frontend/discourse/tests/integration/components/code-login-form-test.gjsindex 3463345a30e..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,4 +1,4 @@-import { click, fillIn, render } from "@ember/test-helpers";+import { click, fillIn, render, waitFor } from "@ember/test-helpers";import { module, test } from "qunit";import CodeLoginForm from "discourse/components/code-login-form";import { withPluginApi } from "discourse/lib/plugin-api";@@ -61,6 +61,9 @@ module("Integration | Component | CodeLoginForm", function (hooks) {.includesText("[email protected]");assert.dom(".d-otp-input").exists();assert.dom(".code-login-form__resend").exists();+ assert+ .dom(".code-login-form__change-email")+ .exists("the email can still be corrected before verification");});test("signup requests declare their intent", async function (assert) {@@ -219,6 +222,237 @@ module("Integration | Component | CodeLoginForm", function (hooks) {assert.dom(".d-otp-input").hasValue("", "the code input is cleared");});+ test("collects valid account details before submitting for approval", async function (assert) {+ stubCodeRequest();+ this.siteSettings.enable_random_usernames = true;+ this.site.setProperties({+ full_name_required_for_signup: true,+ full_name_visible_in_signup: true,+ });++ const verifyRequests = [];+ let accountDetailAttempts = 0;+ pretender.post("/session/login-code/verify", (request) => {+ const params = new URLSearchParams(request.requestBody);+ verifyRequests.push(params);++ if (!params.get("signup_token")) {+ return response({+ signup_details_required: true,+ signup_token: "signup-token",+ username: "suggested-name",+ expires_in: 600,+ });+ }++ accountDetailAttempts++;+ return accountDetailAttempts === 1+ ? response({+ error: "Password is too common",+ password_error: "Choose a more secure password",+ })+ : response({ pending_approval: true });+ });++ await render(<template><CodeLoginForm @context="signup" /></template>);+ await fillIn(+ ".code-login-form__email-step .form-kit__control-input",+ );+ await formKit().submit();+ await fillIn(".d-otp-input", "123456");++ assert+ .dom(".login-title")+ .hasText(i18n("code_login.account_details_title"));+ assert.dom(".code-login-form__account-details-step").exists();+ assert+ .dom(".code-login-form__create-password")+ .hasClass("btn-link", "the optional password action uses link styling")+ .hasText(i18n("code_login.create_password_optional"));+ assert.dom("#new-account-password").doesNotExist();+ assert+ .dom(".code-login-form__change-email")+ .doesNotExist("a verified email cannot be changed from account details");++ await click(".code-login-form__create-password");+ assert.dom("#new-account-password").hasAttribute("type", "password");+ assert.strictEqual(+ document.querySelector("#new-account-password").getBoundingClientRect()+ .width,+ document.querySelector("#code-login-username").getBoundingClientRect()+ .width,+ "the password and username inputs have the same visible width"+ );+ await click(".toggle-password-mask");+ assert+ .dom("#new-account-password")+ .hasAttribute("type", "text", "the standard mask control reveals it");+ await fillIn("#new-account-password", "short");+ assert+ .dom(".code-login-form__submit-approval")+ .isDisabled("a locally invalid password cannot be submitted");+ await fillIn("#new-account-password", "Correct Horse Battery Staple");++ assert.strictEqual(+ verifyRequests.length,+ 1,+ "verifying the code does not create the account"+ );++ await fillIn("#code-login-username", "taken");+ await waitFor(".code-login-form__submit-approval[disabled]");+ assert+ .dom(".code-login-form__username-field .code-login-form__error")+ .includesText("nottaken");++ await fillIn("#code-login-username", "chosen-name");+ await waitFor(".code-login-form__submit-approval:not([disabled])");+ await click(".code-login-form__submit-approval");++ assert+ .dom(".code-login-form__name-field .code-login-form__error")+ .hasText(i18n("user.name.required"));+ assert.strictEqual(+ verifyRequests.length,+ 1,+ "invalid details are not submitted"+ );++ await fillIn("#code-login-name", " Chosen Name ");+ await click(".code-login-form__submit-approval");++ assert+ .dom(".code-login-form__account-details-step")+ .exists("a server error keeps the details editable");+ assert.dom("#code-login-username").hasValue("chosen-name");+ assert.dom("#code-login-name").hasValue(" Chosen Name ");+ assert+ .dom("#new-account-password")+ .hasValue("Correct Horse Battery Staple");+ assert+ .dom("#password-validation")+ .includesText("Choose a more secure password");+ assert.strictEqual(accountDetailAttempts, 1, "the first attempt failed");++ await fillIn("#new-account-password", "A different secure password 42!");+ await click(".code-login-form__submit-approval");++ assert.dom(".code-login-form__pending-approval-step").exists();+ assert.strictEqual(verifyRequests[1].get("signup_token"), "signup-token");+ assert.strictEqual(verifyRequests[1].get("username"), "chosen-name");+ assert.strictEqual(verifyRequests[1].get("name"), "Chosen Name");+ assert.strictEqual(+ verifyRequests[2].get("password"),+ "A different secure password 42!",+ "the password is only sent with final account-detail submissions"+ );+ assert.strictEqual(+ accountDetailAttempts,+ 2,+ "the verified continuation can be retried"+ );+ });++ test("restores a verified signup continuation at the account details step", async function (assert) {+ this.owner.lookup("service:session-store").setObject({+ key: "email-code-signup-continuation",+ value: {+ email: "[email protected]",+ expiresAt: Date.now() + 60_000,+ signupToken: "signup-token",+ username: "",+ },+ });++ let verificationRequests = 0;+ pretender.post("/session/login-code/verify", () => {+ verificationRequests++;+ return response({ pending_approval: true });+ });++ await render(<template><CodeLoginForm @context="signup" /></template>);++ assert+ .dom(".code-login-form__account-details-step")+ .exists("the account details step is restored");+ assert+ .dom(".code-login-form__hidden-email")+ .hasValue("[email protected]", "the verified email is preserved");+ assert.strictEqual(+ verificationRequests,+ 0,+ "restoring the continuation does not create an account"+ );++ await fillIn("#code-login-username", "chosen-name");+ await waitFor(".code-login-form__submit-approval:not([disabled])");+ await click(".code-login-form__submit-approval");++ assert.strictEqual(verificationRequests, 1, "the proof remains usable");+ assert+ .dom(".code-login-form__pending-approval-step")+ .exists("valid details submit for approval");+ });++ test("ignores missing and expired signup continuations", async function (assert) {+ const sessionStore = this.owner.lookup("service:session-store");++ await render(<template><CodeLoginForm @context="signup" /></template>);++ assert+ .dom(".code-login-form__email-step")+ .exists("a missing continuation starts a fresh signup");++ sessionStore.setObject({+ key: "email-code-signup-continuation",+ value: {+ email: "[email protected]",+ expiresAt: Date.now() - 1,+ signupToken: "expired-token",+ username: "",+ },+ });++ await render(<template><CodeLoginForm @context="signup" /></template>);++ assert+ .dom(".code-login-form__email-step")+ .exists("an expired continuation starts a fresh signup");+ assert.strictEqual(+ sessionStore.getObject("email-code-signup-continuation"),+ null,+ "the expired continuation is removed"+ );+ });++ test("shows the pending approval screen after a valid signup code", async function (assert) {+ stubCodeRequest();+ pretender.post("/session/login-code/verify", () =>+ response({ pending_approval: true })+ );++ await render(<template><CodeLoginForm @context="signup" /></template>);+ await fillIn(+ ".code-login-form__email-step .form-kit__control-input",+ );+ await formKit().submit();+ await fillIn(".d-otp-input", "123456");++ assert+ .dom(".login-title")+ .hasText(i18n("code_login.pending_approval_title"));+ assert+ .dom(".login-subheader")+ .hasText(i18n("code_login.pending_approval_instructions"));+ assert+ .dom(".code-login-form__pending-approval-step")+ .hasNoText("does not add extra instructions below the explanation");+ assert.dom(".d-otp-input").doesNotExist("removes the code input");+ assert.dom(".code-login-form__resend").doesNotExist("removes resend");+ });+test("shows the second factor form when required", async function (assert) {stubCodeRequest();pretender.post("/session/login-code/verify", () =>diff --git a/plugins/discourse-captcha/lib/discourse_captcha/session_controller_patch.rb b/plugins/discourse-captcha/lib/discourse_captcha/session_controller_patch.rbindex 8fcbb1a9cc1..f5accbb3eb2 100644--- a/plugins/discourse-captcha/lib/discourse_captcha/session_controller_patch.rb+++ b/plugins/discourse-captcha/lib/discourse_captcha/session_controller_patch.rb@@ -4,16 +4,45 @@ module DiscourseCaptchamodule SessionControllerPatchdef process_verified_login_code(matched_user)# Invitations carry their own proof of trust and are never CAPTCHA-gated.- if matched_user.nil? && params[:invite_key].blank? && registration_via_login_code_open? &&- !signup_user_fields_missing? && !signup_full_name_missing? &&- (error = captcha_verification_error)+ captcha_required = captcha_enabled? && captcha_required_for_login_code_signup?(matched_user)+ if captcha_required && (error = captcha_verification_error)render json: { error: I18n.t(error) }returnend+ @login_code_signup_captcha_verified = true if captcha_requiredsuperend+ def complete_verified_login_code_signup+ proof = verified_login_code_signup_proof_for(params[:signup_token].to_s)+ if proof.is_a?(Hash) && !proof[:captcha_verified] && (error = captcha_verification_error)+ render json: { error: I18n.t(error) }+ return+ end++ super+ end++ def verified_login_code_signup_proof+ super.merge(captcha_verified: @login_code_signup_captcha_verified)+ end++ private++ def captcha_enabled?+ SiteSetting.discourse_captcha_enabled &&+ SiteSetting.discourse_captcha_provider != CaptchaProvider::NONE+ end++ def captcha_required_for_login_code_signup?(matched_user)+ return false if matched_user.present? || params[:invite_key].present?+ return false if !registration_via_login_code_open?++ pending_approval_signup?(matched_user) ||+ (!signup_user_fields_missing? && !signup_full_name_missing?)+ end+include CaptchaVerificationendenddiff --git a/plugins/discourse-captcha/spec/requests/discourse_captcha/session_controller_spec.rb b/plugins/discourse-captcha/spec/requests/discourse_captcha/session_controller_spec.rbindex 8daf4bdb981..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@@ -76,6 +76,96 @@ RSpec.describe SessionController doexpect(session[:current_user_id]).to eq(existing_user.id)end+ context "when an approval signup requires account details" do+ fab!(:user_field, :user_field)++ before do+ Jobs.run_immediately!+ SiteSetting.must_approve_users = true+ SiteSetting.full_name_requirement = "required_at_signup"+ end++ let(:email) { "[email protected]" }+ let(:login_code) { EmailLoginCode.generate!(email:) }+ let(:account_details) do+ {+ username: "approval-person",+ name: "Approval Person",+ user_fields: {+ user_field.id.to_s => "Developer",+ },+ }+ end++ 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: {+ secret: SiteSetting.hcaptcha_secret_key,+ 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 }+ }.not_to change(User, :count)+ signup_token = response.parsed_body["signup_token"]++ expect(signup_token).to be_present+ expect(verification_request).to have_been_requested.once+ expect(login_code.reload.consumed_at).to be_nil++ expect {+ post "/session/login-code/verify.json",+ params: account_details.merge(signup_token: signup_token)+ }.to change(User, :count).by(1).and change(ReviewableUser, :count).by(1)++ expect(response.parsed_body).to eq("pending_approval" => true)+ expect(verification_request).to have_been_requested.once+ end++ 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",+ params: account_details.merge(signup_token: signup_token)+ }.not_to change(User, :count)+ expect(response.parsed_body["error"]).to eq(I18n.t("captcha_verification_failed"))+ expect(ReviewableUser.count).to eq(0)+ expect(login_code.reload.consumed_at).to be_nil++ stub_request(:post, DiscourseCaptcha::HcaptchaProvider::CAPTCHA_VERIFICATION_URL).with(+ body: hash_including(response: "bad-token"),+ ).to_return(status: 200, body: '{"success":false}')+ post "/captcha/hcaptcha/create.json", params: { token: "bad-token" }+ post "/session/login-code/verify.json",+ params: account_details.merge(signup_token: signup_token)++ expect(response.parsed_body["error"]).to eq(I18n.t("captcha_verification_failed"))+ expect(User.find_by_email(email)).to be_nil+ expect(ReviewableUser.count).to eq(0)+ expect(login_code.reload.consumed_at).to be_nil++ stub_request(:post, DiscourseCaptcha::HcaptchaProvider::CAPTCHA_VERIFICATION_URL).with(+ body: hash_including(response: "valid-token"),+ ).to_return(status: 200, body: '{"success":true}')+ post "/captcha/hcaptcha/create.json", params: { token: "valid-token" }++ expect {+ post "/session/login-code/verify.json",+ params: account_details.merge(signup_token: signup_token)+ }.to change(User, :count).by(1).and change(ReviewableUser, :count).by(1)++ expect(response.parsed_body).to eq("pending_approval" => true)+ expect(login_code.reload.consumed_at).to be_present+ end+ end+context "when signup requires user fields" dofab!(:user_field, :user_field)diff --git a/plugins/discourse-captcha/spec/system/signup_with_captcha_spec.rb b/plugins/discourse-captcha/spec/system/signup_with_captcha_spec.rbindex 60b7b091896..391ae04f8c3 100644--- a/plugins/discourse-captcha/spec/system/signup_with_captcha_spec.rb+++ b/plugins/discourse-captcha/spec/system/signup_with_captcha_spec.rb@@ -8,8 +8,7 @@ RSpec.describe "Signup with captcha" doSiteSetting.enable_local_logins = trueSiteSetting.discourse_captcha_enabled = true- # The captcha outlet only exists on the password signup form, which the- # code-based form replaces when enable_local_logins_via_code is on.+ # Most examples exercise the password form, so keep the code option unavailable.SiteSetting.enable_local_logins_via_code = falseenddiff --git a/spec/mailers/user_notifications_spec.rb b/spec/mailers/user_notifications_spec.rbindex a8b2eff57d7..f3f620ee7d1 100644--- a/spec/mailers/user_notifications_spec.rb+++ b/spec/mailers/user_notifications_spec.rb@@ -77,6 +77,50 @@ RSpec.describe UserNotifications doendend+ describe ".signup_after_approval" do+ before do+ SiteSetting.enable_local_logins_via_code = true+ SiteSetting.enable_local_logins = true+ SiteSetting.enable_local_logins_via_email = true+ end++ it "links a passwordless user to code login when it is available" do+ passwordless_user = Fabricate(:user, password: nil)+ body = UserNotifications.signup_after_approval(passwordless_user).body.to_s++ expect(body).to include("#{Discourse.base_url}/login?mode=code")+ expect(body).not_to include("code=")+ expect(body).to include("#{Discourse.base_url}/guidelines")+ end++ it "links a user with a password to the default destination" do+ body = UserNotifications.signup_after_approval(user).body.to_s++ expect(body).to include("logging in at:\n#{Discourse.base_url}")+ expect(body).not_to include("/login?mode=code")+ end++ it "uses the default destination when code login is unavailable" do+ SiteSetting.enable_local_logins_via_code = false+ passwordless_user = Fabricate(:user, password: nil)+ body = UserNotifications.signup_after_approval(passwordless_user).body.to_s++ expect(body).to include("logging in at:\n#{Discourse.base_url}")+ expect(body).not_to include("/login?mode=code")+ end++ it "uses the default destination when external login is required" do+ SiteSetting.discourse_connect_url = "https://www.example.com/sso"+ SiteSetting.discourse_connect_secret = "s" * 32+ SiteSetting.enable_discourse_connect = true+ passwordless_user = Fabricate(:user, password: nil)+ body = UserNotifications.signup_after_approval(passwordless_user).body.to_s++ expect(body).to include("logging in at:\n#{Discourse.base_url}")+ expect(body).not_to include("/login?mode=code")+ end+ end+describe ".forgot_password" dosubject(:email) { UserNotifications.forgot_password(user) }diff --git a/spec/requests/session_controller_spec.rb b/spec/requests/session_controller_spec.rbindex fd4d7e8ac36..c62dab29300 100644--- a/spec/requests/session_controller_spec.rb+++ b/spec/requests/session_controller_spec.rb@@ -1149,19 +1149,234 @@ RSpec.describe SessionController doexpect(session[:current_user_id]).to be_nilend- it "does not log in an unapproved user when approval is required" do+ it "shows the pending approval result for an existing unapproved user" doSiteSetting.must_approve_users = truepost "/session/login-code/verify.json", params: { email: user.email, code: }expect(response.status).to eq(200)- expect(response.parsed_body["error"]).to eq(I18n.t("login.not_approved"))+ expect(response.parsed_body).to eq("pending_approval" => true)expect(session[:current_user_id]).to be_nil+ expect(login_code.reload.consumed_at).to be_presentendcontext "when the email does not belong to a user" dolet(:login_code) { EmailLoginCode.generate!(email: "[email protected]") }+ it "rejects caller-supplied reserved and route-conflicting usernames without consuming the code" do+ %w[MoDeRaToR ACCOUNT-CREATED].each do |username|+ post "/session/login-code/verify.json",+ params: {+ email: "[email protected]",+ code:,+ 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)+ expect(session[:current_user_id]).to be_nil+ expect(login_code.reload.consumed_at).to be_nil+ end++ post "/session/login-code/verify.json",+ params: {+ email: "[email protected]",+ code:,+ username: "valid-chosen-name",+ }++ expect(response.parsed_body["account_created"]).to eq(true)+ expect(User.find_by_email("[email protected]").username).to eq("valid-chosen-name")+ end++ it "rejects reserved and route-conflicting usernames on an approval continuation" do+ Jobs.run_immediately!+ SiteSetting.must_approve_users = true++ post "/session/login-code/verify.json", params: { email: "[email protected]", code: }+ signup_token = response.parsed_body["signup_token"]++ %w[MoDeRaToR ACCOUNT-CREATED].each do |username|+ post "/session/login-code/verify.json", params: { signup_token:, username: }++ expect(response.parsed_body["error"]).to include(I18n.t("login.reserved_username"))+ expect(User.find_by_email("[email protected]")).to be_nil+ expect(ReviewableUser.count).to eq(0)+ expect(session[:current_user_id]).to be_nil+ expect(login_code.reload.consumed_at).to be_nil+ end++ post "/session/login-code/verify.json",+ params: {+ signup_token:,+ username: "valid-chosen-name",+ }++ expect(response.parsed_body).to eq("pending_approval" => true)+ expect(User.find_by_email("[email protected]").username).to eq("valid-chosen-name")+ expect(ReviewableUser.count).to eq(1)+ end++ it "collects identity before creating a passwordless account awaiting approval" do+ Jobs.run_immediately!+ SiteSetting.must_approve_users = true+ SiteSetting.full_name_requirement = "required_at_signup"+ user_field = Fabricate(:user_field, name: "Occupation")++ post "/session/login-code/verify.json", params: { email: "[email protected]", code: }++ 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_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+ expect(login_code.reload.consumed_at).to be_nil++ post "/session/login-code/verify.json",+ params: {+ signup_token:,+ username: "chosen-name",+ name: "Chosen Name",+ user_fields: {+ user_field.id => "Engineer",+ },+ }++ new_user = User.find_by_email("[email protected]")+ reviewable = ReviewableUser.find_by(target: new_user)+ expect(response.status).to eq(200)+ expect(response.parsed_body).to eq("pending_approval" => true)+ expect(new_user).to be_active+ expect(new_user).not_to be_approved+ expect(new_user.username).to eq("chosen-name")+ expect(new_user.name).to eq("Chosen Name")+ expect(new_user.custom_fields["user_field_#{user_field.id}"]).to eq("Engineer")+ expect(new_user.user_password).to be_nil+ expect(reviewable.payload.slice("username", "name")).to eq(+ "username" => "chosen-name",+ "name" => "Chosen Name",+ )+ expect(session[:current_user_id]).to be_nil+ expect(login_code.reload.consumed_at).to be_present+ end++ it "allows correcting an invalid password without consuming the verified proof" do+ SiteSetting.must_approve_users = true++ post "/session/login-code/verify.json", params: { email: "[email protected]", code: }+ signup_token = response.parsed_body["signup_token"]++ post "/session/login-code/verify.json",+ params: {+ signup_token:,+ username: "valid-name",+ password: "x" * (User.max_password_length + 1),+ }++ expect(response.parsed_body["error"]).to be_present+ 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: {+ signup_token:,+ username: "valid-name",+ password: "short",+ }++ expect(response.parsed_body["password_error"]).to be_present+ expect(User.find_by_email("[email protected]")).to be_nil+ expect(login_code.reload.consumed_at).to be_nil++ password = "a-secure-password-42!"+ post "/session/login-code/verify.json",+ params: {+ signup_token:,+ username: "valid-name",+ password:,+ }++ expect(response.parsed_body).to eq("pending_approval" => true)+ new_user = User.find_by_email("[email protected]")+ expect(new_user.username).to eq("valid-name")+ expect(new_user.confirm_password?(password)).to eq(true)+ expect(session[:current_user_id]).to be_nil+ end++ it "rejects an expired or reused signup proof" do+ SiteSetting.must_approve_users = true++ post "/session/login-code/verify.json", params: { email: "[email protected]", code: }+ signup_token = response.parsed_body["signup_token"]++ freeze_time 11.minutes.from_now do+ post "/session/login-code/verify.json", params: { signup_token:, username: "too-late" }+ end++ expect(response.parsed_body).to eq("error" => I18n.t("email_login_code.invalid_code"))+ expect(User.find_by_email("[email protected]")).to be_nil++ fresh_code = EmailLoginCode.generate!(email: "[email protected]")+ post "/session/login-code/verify.json",+ params: {+ email: "[email protected]",+ code: fresh_code.code,+ }+ fresh_token = response.parsed_body["signup_token"]+ post "/session/login-code/verify.json",+ params: {+ signup_token: fresh_token,+ username: "created-once",+ }+ expect(response.parsed_body).to eq("pending_approval" => true)++ post "/session/login-code/verify.json",+ params: {+ signup_token: fresh_token,+ username: "created-twice",+ }++ expect(response.parsed_body).to eq("error" => I18n.t("email_login_code.invalid_code"))+ expect(UserEmail.where(email: "[email protected]").count).to eq(1)+ expect(session[:current_user_id]).to be_nil+ end++ it "does not turn a signup continuation into an existing-account login" do+ SiteSetting.must_approve_users = true++ post "/session/login-code/verify.json", params: { email: "[email protected]", code: }+ signup_token = response.parsed_body["signup_token"]+ existing_user = Fabricate(:user, email: "[email protected]")+ Fabricate(:user_second_factor_totp, user: existing_user)++ post "/session/login-code/verify.json",+ params: {+ signup_token:,+ username: "should-not-login",+ }++ expect(response.parsed_body).to eq("error" => I18n.t("email_login_code.invalid_code"))+ expect(response.body).not_to include(existing_user.username)+ expect(session[:current_user_id]).to be_nil+ expect(login_code.reload.consumed_at).to be_nil+ end++ it "keeps auto-approved domains on the immediate account creation path" do+ SiteSetting.must_approve_users = true+ SiteSetting.auto_approve_email_domains = "example.com"++ 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)+ expect(new_user).to be_approved+ expect(session[:current_user_id]).to eq(new_user.id)+ end+it "creates and logs in a new user" dopost "/session/login-code/verify.json", params: { email: "[email protected]", code: }diff --git a/spec/requests/users_controller_spec.rb b/spec/requests/users_controller_spec.rbindex a38a2368b49..eca5c12b5e5 100644--- a/spec/requests/users_controller_spec.rb+++ b/spec/requests/users_controller_spec.rb@@ -2418,6 +2418,36 @@ RSpec.describe UsersController doexpect(response.parsed_body["avatar_template"]).to eq(User.default_template(username))end+ context "when login is required" do+ before { SiteSetting.login_required = true }++ it "rejects an anonymous request without a verified signup continuation" do+ get "/u/random-username.json"++ expect(response.status).to eq(403)+ end++ it "allows a verified passwordless signup continuation" do+ SiteSetting.enable_local_logins_via_code = true+ SiteSetting.must_approve_users = true+ login_code = EmailLoginCode.generate!(email: "[email protected]")++ post "/session/login-code/verify.json",+ params: {+ email: login_code.email,+ code: login_code.code,+ }+ signup_token = response.parsed_body["signup_token"]++ get "/u/random-username.json", headers: { "X-Discourse-Signup-Token" => signup_token }++ expect(response.status).to eq(200)+ expect(response.parsed_body["username"]).to be_present+ expect(User.find_by_email(login_code.email)).to be_nil+ expect(session[:current_user_id]).to be_nil+ end+ end+it "keeps an uploaded avatar when generating a username" douser = Fabricate(:user)upload = Fabricate(:upload, user:)diff --git a/spec/services/email_login_code/redeem_spec.rb b/spec/services/email_login_code/redeem_spec.rbindex faac69dfc4b..4dafe353ea7 100644--- a/spec/services/email_login_code/redeem_spec.rb+++ b/spec/services/email_login_code/redeem_spec.rb@@ -308,6 +308,18 @@ RSpec.describe EmailLoginCode::Redeem doit { is_expected.to run_successfully }+ context "when a new account is required" do+ let(:params) { { email:, code:, new_account_required: true } }++ it { is_expected.to fail_a_policy(:new_account_available) }++ it "does not consume the code" do+ result++ expect(login_code.reload.consumed_at).to be_nil+ end+ end+it "returns the user and consumes the code" doexpect(result[:user]).to eq(user)expect(login_code.reload.consumed_at).to be_presentdiff --git a/spec/services/username_checker_service_spec.rb b/spec/services/username_checker_service_spec.rbindex a4946051b29..93974b87dfa 100644--- a/spec/services/username_checker_service_spec.rb+++ b/spec/services/username_checker_service_spec.rb@@ -58,5 +58,12 @@ RSpec.describe UsernameCheckerService doresult = @service.check_username("vincent", @nil_email)expect(result[:available]).to eq(true)end++ it "rejects usernames that clash with an existing user route" do+ result = @service.check_username("ACCOUNT-CREATED", @email)++ expect(result[:available]).to eq(false)+ expect(result[:suggestion]).to be_present+ endendenddiff --git a/spec/system/code_login_spec.rb b/spec/system/code_login_spec.rbindex 838cf5399ec..594e0823155 100644--- a/spec/system/code_login_spec.rb+++ b/spec/system/code_login_spec.rb@@ -28,8 +28,6 @@ describe "Login via email code" dodef start_code_login(email)visit("/login")expect(page).to have_css("#login-account-name")- screenshot_marker(label: "code-login-password-form")-find("#one-time-code-link").clickexpect(page).to have_css(".code-login-form__email-step")screenshot_marker(label: "code-login-email-step")@@ -83,13 +81,14 @@ describe "Login via email code" doendend- it "can switch to the code form and back to password login" do+ it "defaults to password login and can opt into code login" dovisit("/login")expect(page).to have_css("#login-account-name")+ expect(page).to have_no_css(".code-login-form")+ screenshot_marker(label: "code-login-password-form")find("#one-time-code-link").clickexpect(page).to have_css(".code-login-form__email-step")-find(".code-login-form__password-toggle").clickexpect(page).to have_css("#login-account-name")@@ -108,9 +107,7 @@ describe "Login via email code" doit "renders the checkbox at a usable size and lets it be toggled" donew_email = "[email protected]"- visit("/login")- expect(page).to have_css("#login-account-name")- find("#one-time-code-link").click+ visit("/login?mode=code")expect(page).to have_css(".code-login-form__email-step")find(".code-login-form__email-step input[type='email']").fill_in(with: new_email)diff --git a/spec/system/code_signup_spec.rb b/spec/system/code_signup_spec.rbindex 05b591e6be8..d625f794d6e 100644--- a/spec/system/code_signup_spec.rb+++ b/spec/system/code_signup_spec.rb@@ -9,6 +9,12 @@ describe "Sign up via email code" doJobs.run_immediately!end+ def open_code_signup+ visit("/signup")+ expect(page).to have_css(".code-login-form__email-step")+ expect(page).to have_no_css("#new-account-password")+ end+def fill_code(code)find(".d-otp-input").fill_in(with: code)end@@ -32,7 +38,7 @@ describe "Sign up via email code" doendit "creates a passwordless account, picks a username, and logs in" do- visit("/signup")+ open_code_signupexpect(page).to have_css(".code-login-form__email-step")expect(page).to have_content(I18n.t("js.code_login.signup_title"))screenshot_marker(label: "code-signup-email-step")@@ -67,7 +73,7 @@ describe "Sign up via email code" doendit "shows a single heading that is replaced as the flow advances" do- visit("/signup")+ open_code_signupexpect(page).to have_css(".code-login-form__email-step")expect(page).to have_css(".login-welcome-header", count: 1)@@ -97,7 +103,7 @@ describe "Sign up via email code" doit "blocks continuing while the picked username is taken" doFabricate(:user, username: "takenname")- visit("/signup")+ open_code_signupsubmit_email("[email protected]")fill_code(latest_emailed_code("[email protected]"))@@ -111,7 +117,7 @@ describe "Sign up via email code" doit "prefills the username when email-based suggestions are enabled" doSiteSetting.use_email_for_username_and_name_suggestions = true- visit("/signup")+ open_code_signupsubmit_email("[email protected]")fill_code(latest_emailed_code("[email protected]"))@@ -123,7 +129,7 @@ describe "Sign up via email code" doSiteSetting.use_email_for_username_and_name_suggestions = falseSiteSetting.enable_random_usernames = false- visit("/signup")+ open_code_signupsubmit_email("[email protected]")fill_code(latest_emailed_code("[email protected]"))@@ -144,7 +150,7 @@ describe "Sign up via email code" doit "keeps the generated username when usernames can't be changed" doSiteSetting.username_change_period = 0- visit("/signup")+ open_code_signupsubmit_email("[email protected]")fill_code(latest_emailed_code("[email protected]"))@@ -157,7 +163,7 @@ describe "Sign up via email code" doendit "opens the avatar picker before continuing" do- visit("/signup")+ open_code_signupsubmit_email("[email protected]")fill_code(latest_emailed_code("[email protected]"))@@ -168,7 +174,7 @@ describe "Sign up via email code" doendit "shows an error for an incorrect code" do- visit("/signup")+ open_code_signupsubmit_email("[email protected]")correct_code = latest_emailed_code("[email protected]")@@ -185,7 +191,7 @@ describe "Sign up via email code" doit "does not create an account when registrations are disabled" doSiteSetting.allow_new_registrations = false- visit("/signup")+ open_code_signupsubmit_email("[email protected]")# No code is sent when registrations are closed, so any code is rejected.@@ -196,26 +202,175 @@ describe "Sign up via email code" doexpect(User.find_by_email("[email protected]")).to be_nilend- it "shows a pending-approval message when users must be approved" do+ it "collects account details before approval and requires a fresh code afterward" do+ SiteSetting.login_required = trueSiteSetting.must_approve_users = true+ SiteSetting.full_name_requirement = "required_at_signup"+ user_field = Fabricate(:user_field, name: "Occupation")+ admin = Fabricate(:admin)+ email = "[email protected]"- visit("/signup")- submit_email("[email protected]")- fill_code(latest_emailed_code("[email protected]"))+ open_code_signup+ submit_email(email)+ fill_code(latest_emailed_code(email))++ expect(page).to have_css(".login-title", text: I18n.t("js.code_login.account_details_title"))+ expect(page).to have_css(".code-login-form__account-details-step")+ expect(User.find_by_email(email)).to be_nil++ generated_username = find("#code-login-username").value+ find(".code-login-form__username-regen").click+ expect(page).to have_no_field("code-login-username", with: generated_username)+ expect(page).to have_no_css(".dialog-container")+ expect(User.find_by_email(email)).to be_nil+ rolled_username = find("#code-login-username").value+ expect(page).to have_no_css(".code-login-form__submit-approval[disabled]")++ with_logs do |browser_logs|+ page.refresh++ expect(page).to have_current_path("/signup")+ expect(page).to have_css(".code-login-form__account-details-step")+ expect(page).to have_field("code-login-username")+ expect(User.find_by_email(email)).to be_nil++ browser_errors =+ browser_logs.logs.select do |log|+ log[:level] == "error" && !log[:message].include?("Failed to load resource")+ end+ expect(browser_errors).to be_empty+ end++ fill_in("code-login-username", with: "invalid username!")+ expect(page).to have_css(".code-login-form__submit-approval[disabled]")+ expect(User.find_by_email(email)).to be_nil++ pick_username(rolled_username)+ find(".code-login-form__submit-approval").click++ expect(page).to have_css(+ ".code-login-form__name-field .code-login-form__error",+ text: I18n.t("js.user.name.required"),+ )+ expect(User.find_by_email(email)).to be_nil- expect(page).to have_css(".code-login-form__error", text: I18n.t("login.not_approved"))+ fill_in("code-login-name", with: "Chosen Name")+ find(".user-field-occupation input").fill_in(with: "Engineer")+ find(".code-login-form__submit-approval").click++ expect(page).to have_css(".login-title", text: I18n.t("js.code_login.pending_approval_title"))+ expect(page).to have_css(+ ".login-subheader",+ text: I18n.t("js.code_login.pending_approval_instructions"),+ )+ expect(page).to have_no_css(".d-otp-input")expect(page).to have_no_css(".header-dropdown-toggle.current-user")- user = User.find_by_email("[email protected]")+ user = User.find_by_email(email)expect(user).not_to be_approved- expect(ReviewableUser.pending.find_by(target: user)).to be_present+ expect(user.username).to eq(rolled_username)+ expect(user.name).to eq("Chosen Name")+ expect(user.custom_fields["user_field_#{user_field.id}"]).to eq("Engineer")++ reviewable = ReviewableUser.pending.find_by!(target: user)+ expect(reviewable.payload.slice("username", "name")).to eq(+ "username" => rolled_username,+ "name" => "Chosen Name",+ )++ sign_in(admin)+ review_page = PageObjects::Pages::Review.new+ review_page.visit_reviewable(reviewable)+ expect(page).to have_content(rolled_username)+ expect(page).to have_content("Chosen Name")+ expect(page).to have_content("Occupation")+ expect(page).to have_content("Engineer")+ review_page.click_approve_user_button++ expect(review_page).to have_reviewable_with_approved_status(reviewable)+ expect(user.reload).to be_approved+ approval_email = ActionMailer::Base.deliveries.last+ expect(approval_email.to).to contain_exactly(email)+ expect(approval_email.body.to_s).to include("/login?mode=code")++ user_menu = PageObjects::Components::UserMenu.new+ user_menu.open.click_profile_tab+ find("#quick-access-profile .logout .btn").click+ expect(page).to have_current_path("/")+ visit("/login?mode=code")+ find(".code-login-form__email-step input[type='email']").fill_in(with: email)+ find(".code-login-form__continue").click+ fill_code(latest_emailed_code(email))++ expect(page).to have_css(".header-dropdown-toggle.current-user")+ expect(User.find_by_email(email).username).to eq(rolled_username)+ end++ it "creates a password account before approval and logs in with it after approval" do+ SiteSetting.must_approve_users = true+ admin = Fabricate(:admin)+ email = "[email protected]"+ password = "a-secure-password-42!"++ open_code_signup+ submit_email(email)+ fill_code(latest_emailed_code(email))++ expect(page).to have_button(I18n.t("js.code_login.create_password_optional"))+ expect(page).to have_css(".code-login-form__create-password.btn-link")+ expect(page).to have_no_button(I18n.t("js.code_login.use_different_email"))+ expect(page).to have_no_field("new-account-password")+ screenshot_marker(label: "code-signup-account-details-password-link")++ find(".code-login-form__create-password").click+ expect(page).to have_field("new-account-password", type: "password")+ screenshot_marker(label: "code-signup-account-details-password-expanded")++ fill_in("new-account-password", with: "short")+ expect(page).to have_css(".code-login-form__submit-approval[disabled]")++ fill_in("new-account-password", with: password)+ expect(page).to have_no_css(".code-login-form__submit-approval[disabled]")+ find(".code-login-form__submit-approval").click++ expect(page).to have_css(".code-login-form__pending-approval-step")+ expect(page).to have_no_css(".header-dropdown-toggle.current-user")+ screenshot_marker(label: "code-signup-pending-approval")++ user = User.find_by_email(email)+ expect(user).not_to be_approved+ expect(user.confirm_password?(password)).to eq(true)++ reviewable = ReviewableUser.pending.find_by!(target: user)+ sign_in(admin)+ review_page = PageObjects::Pages::Review.new+ review_page.visit_reviewable(reviewable)+ review_page.click_approve_user_button++ expect(review_page).to have_reviewable_with_approved_status(reviewable)+ approval_email = ActionMailer::Base.deliveries.last+ expect(approval_email.body.to_s).to include("logging in at:")+ expect(approval_email.body.to_s).not_to include("request a fresh login code")++ user_menu = PageObjects::Components::UserMenu.new+ user_menu.open.click_profile_tab+ find("#quick-access-profile .logout .btn").click+ expect(page).to have_current_path("/")++ visit("/login")+ expect(page).to have_field("login-account-password")+ fill_in("login-account-name", with: email)+ fill_in("login-account-password", with: password)+ find("#login-button").click++ expect(page).to have_css(".header-dropdown-toggle.current-user")endcontext "with required user fields" dofab!(:user_field) { Fabricate(:user_field, name: "Occupation") }it "collects the fields after the code is verified" do- visit("/signup")+ open_code_signupsubmit_email("[email protected]")fill_code(latest_emailed_code("[email protected]"))@@ -241,7 +396,7 @@ describe "Sign up via email code" dobefore { SiteSetting.full_name_requirement = "required_at_signup" }it "collects the name after the code is verified" do- visit("/signup")+ open_code_signupsubmit_email("[email protected]")fill_code(latest_emailed_code("[email protected]"))