A platform for community discussion. Free, open, simple.
UX: Improve password manager and full name handling in code login (#41746)
Keegan George45223988767e
diff --git a/app/assets/stylesheets/common/login/code-login-form.scss b/app/assets/stylesheets/common/login/code-login-form.scssindex c23f000104f..55c4a0281b1 100644--- a/app/assets/stylesheets/common/login/code-login-form.scss+++ b/app/assets/stylesheets/common/login/code-login-form.scss@@ -55,6 +55,18 @@}}+ &__name-field {+ display: flex;+ flex-direction: column;+ align-self: stretch;+ gap: 0.25em;+ }++ &__name {+ 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 969bccf7e28..6caf9327305 100644--- a/app/controllers/session_controller.rb+++ b/app/controllers/session_controller.rb@@ -900,7 +900,13 @@ class SessionController < ApplicationControllerendend- return render json: { user_fields_required: true } if needs_signup_user_fields?(matched_user)+ if matched_user.nil? && registration_via_login_code_open?+ user_fields_required = signup_user_fields_missing?+ name_required = signup_full_name_missing?+ if user_fields_required || name_required+ return render json: { user_fields_required:, name_required: }+ end+ endEmailLoginCode::Redeem.call(service_params.deep_merge(ip_address: request.remote_ip),@@ -914,17 +920,29 @@ class SessionController < ApplicationControlleron_failed_policy(:required_fields_provided) dorender 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_failed_contract do |contract|+ render json: failed_json.merge(errors: contract.errors.full_messages), status: :bad_request+ endon_failure { render json: invalid_login_code }endend- # Required signup fields are only collected once the code has proven- # ownership of the inbox, so this response can't be used to probe whether+ # 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 needs_signup_user_fields?(matched_user)- matched_user.nil? && params[:user_fields].blank? &&- UserField.required.where(show_on_signup: true).exists? &&- SiteSetting.allow_new_registrations && !SiteSetting.invite_only &&+ def signup_user_fields_missing?+ params[:user_fields].blank? && UserField.required.where(show_on_signup: true).exists?+ end++ def signup_full_name_missing?+ params[:name].blank? && Site.full_name_required_for_signup+ end++ def registration_via_login_code_open?+ SiteSetting.allow_new_registrations && !SiteSetting.invite_only &&!SiteSetting.require_invite_codeenddiff --git a/app/services/email_login_code/redeem.rb b/app/services/email_login_code/redeem.rbindex d518db96e31..e237069fee8 100644--- a/app/services/email_login_code/redeem.rb+++ b/app/services/email_login_code/redeem.rb@@ -5,6 +5,7 @@ class EmailLoginCode::Redeemparams base_class: EmailLoginCode::Verify::Contract doattribute :user_fields+ attribute :name, :stringbefore_validation do# Only hash-like input can carry field values; anything else (a stray@@ -18,7 +19,10 @@ class EmailLoginCode::Redeem{}end)+ self.name = name.to_s.strip.presenceend++ validates :name, length: { maximum: 255 }endmodel :login_code@@ -27,6 +31,7 @@ class EmailLoginCode::Redeempolicy :email_available_for_new_accountpolicy :can_register_new_accountpolicy :required_fields_provided+ policy :required_full_name_providedlock(:email) dotransaction do@@ -92,6 +97,12 @@ class EmailLoginCode::Redeemendend+ def required_full_name_provided(existing_user:, params:)+ return true if existing_user.present?++ !Site.full_name_required_for_signup || params.name.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.@@ -104,6 +115,7 @@ class EmailLoginCode::Redeememail: params.email,ip_address: ip_address,user_fields: params.user_fields,+ name: params.name,)enddiff --git a/app/services/user/action/create_from_verified_email.rb b/app/services/user/action/create_from_verified_email.rbindex 1b8e83df0e0..648136571dc 100644--- a/app/services/user/action/create_from_verified_email.rb+++ b/app/services/user/action/create_from_verified_email.rb@@ -4,6 +4,7 @@ class User::Action::CreateFromVerifiedEmail < Service::ActionBaseoption :emailoption :ip_address, optional: trueoption :user_fields, optional: true+ option :name, optional: truedef callusername = UserNameSuggester.suggest(email)@@ -15,7 +16,7 @@ class User::Action::CreateFromVerifiedEmail < Service::ActionBaseuser.attributes = {email: email,username: username,- name: username,+ name: name.presence || username,active: false,locale: I18n.locale,ip_address: ip_address,diff --git a/config/locales/server.en.yml b/config/locales/server.en.ymlindex 435fe82c891..88de977c471 100644--- a/config/locales/server.en.yml+++ b/config/locales/server.en.yml@@ -3343,6 +3343,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_full_name: "Please enter your full name"auth_complete: "Authentication is complete."click_to_continue: "Click here to continue."already_logged_in: "Sorry! This invitation is intended for new users, who do not already have an existing account."diff --git a/frontend/discourse/app/components/code-login-form.gjs b/frontend/discourse/app/components/code-login-form.gjsindex 385503a1a97..ce8ab7c1fd4 100644--- a/frontend/discourse/app/components/code-login-form.gjs+++ b/frontend/discourse/app/components/code-login-form.gjs@@ -47,6 +47,9 @@ export default class CodeLoginForm extends Component {@tracked otpGeneration = 0;@tracked newAccount;@tracked accountUser;+ @tracked name = "";+ @tracked nameRequired = false;+ @tracked nameError;@tracked username = "";@tracked usernameAvailable = false;@tracked usernameChecking = false;@@ -263,6 +266,9 @@ export default class CodeLoginForm extends Component {if (this.isUserFieldsStep) {data.user_fields = {};this.userFields.forEach((f) => (data.user_fields[f.field.id] = f.value));+ if (this.nameRequired) {+ data.name = this.name.trim();+ }}try {@@ -271,7 +277,11 @@ export default class CodeLoginForm extends Component {data,});- if (result?.user_fields_required && !this.isUserFieldsStep) {+ if (+ (result?.user_fields_required || result?.name_required) &&+ !this.isUserFieldsStep+ ) {+ this.nameRequired = !!result.name_required;this.step = "user-fields";return;}@@ -317,10 +327,22 @@ export default class CodeLoginForm extends Component {}}+ @action+ nameChanged(event) {+ this.name = event.target.value;+ this.nameError = null;+ }+@actionasync submitUserFields() {this.userFieldsValidationHelper.validationVisible = true;- if (this.userFieldsValidationHelper.userFieldsValidation.failed) {+ if (this.nameRequired && !this.name.trim()) {+ this.nameError = i18n("user.name.required");+ }+ if (+ this.nameError ||+ this.userFieldsValidationHelper.userFieldsValidation.failed+ ) {return;}return this.verifyCode();@@ -571,6 +593,22 @@ export default class CodeLoginForm extends Component {</PluginOutlet>{{/if}}+ {{#unless this.isEmailStep}}+ {{! Steps replace each other in the DOM, so without this hidden field+ password managers lose track of which account is authenticating once+ the email input unmounts. }}+ <input+ type="email"+ value={{this.email}}+ name="email"+ autocomplete="username"+ readonly={{true}}+ tabindex="-1"+ aria-hidden="true"+ class="code-login-form__hidden-email sr-only"+ />+ {{/unless}}+{{#if this.isEmailStep}}{{#if this.isSignup}}<p class="code-login-form__instructions">@@ -593,10 +631,7 @@ export default class CodeLoginForm extends Component {@format="full"as |field|>- <field.Control- autofocus="autofocus"- autocomplete="username email"- />+ <field.Control autofocus="autofocus" autocomplete="username" /></form.Field><div class="code-login-form__email-actions">@@ -706,8 +741,10 @@ export default class CodeLoginForm extends Component {placeholder={{i18n "code_login.username_placeholder"}}class="code-login-form__new-account-username"aria-invalid={{if this.usernameError "true"}}+ aria-describedby="code-login-username-error"/><div+ id="code-login-username-error"class="code-login-form__error"aria-live="polite"role="alert"@@ -741,6 +778,34 @@ export default class CodeLoginForm extends Component {</p>{{/unless}}+ {{#if this.nameRequired}}+ <div class="code-login-form__name-field">+ <label for="code-login-name">+ {{i18n "user.name.title"}}+ </label>+ <input+ {{on "input" this.nameChanged}}+ type="text"+ value={{this.name}}+ id="code-login-name"+ name="name"+ autocomplete="name"+ maxlength="255"+ class="code-login-form__name"+ aria-invalid={{if this.nameError "true"}}+ aria-describedby="code-login-name-error"+ />+ <div+ id="code-login-name-error"+ class="code-login-form__error"+ aria-live="polite"+ role="alert"+ >+ {{this.nameError}}+ </div>+ </div>+ {{/if}}+<div class="user-fields">{{#each this.userFields as |f|}}<div class="input-group">diff --git a/frontend/discourse/tests/integration/components/code-login-form-test.gjs b/frontend/discourse/tests/integration/components/code-login-form-test.gjsindex 9539d4c0ca4..ca0b113af97 100644--- a/frontend/discourse/tests/integration/components/code-login-form-test.gjs+++ b/frontend/discourse/tests/integration/components/code-login-form-test.gjs@@ -32,7 +32,11 @@ module("Integration | Component | CodeLoginForm", function (hooks) {assert.dom(".code-login-form__email-step").exists();assert.form().field("email").hasValue("[email protected]");+ assert+ .dom(".code-login-form__email-step .form-kit__control-input")+ .hasAttribute("autocomplete", "username");assert.dom(".d-otp-input").doesNotExist();+ assert.dom(".code-login-form__hidden-email").doesNotExist();});test("rejects an invalid email address", async function (assert) {@@ -58,6 +62,22 @@ module("Integration | Component | CodeLoginForm", function (hooks) {assert.dom(".code-login-form__resend").exists();});+ test("keeps a hidden email field for password managers after the email step", async function (assert) {+ stubCodeRequest();++ await goToCodeStep();++ assert+ .dom(".code-login-form__hidden-email")+ .hasValue("[email protected]")+ .hasAttribute("autocomplete", "username")+ .hasAttribute("readonly");++ await click(".code-login-form__change-email");++ assert.dom(".code-login-form__hidden-email").doesNotExist();+ });+test("shows an error and clears the input for a wrong code", async function (assert) {stubCodeRequest();pretender.post("/session/login-code/verify", () =>@@ -90,6 +110,58 @@ module("Integration | Component | CodeLoginForm", function (hooks) {assert.dom("#second-factor").exists();});+ test("collects a required full name before completing signup", async function (assert) {+ stubCodeRequest();++ const verifyRequests = [];+ pretender.post("/session/login-code/verify", (request) => {+ const params = new URLSearchParams(request.requestBody);+ verifyRequests.push(params);++ if (params.get("name")) {+ return response({+ account_created: true,+ user: { id: 1, username: "jane", avatar_template: "/letter/j.png" },+ can_edit_username: true,+ prefill_username: false,+ });+ }++ return response({ name_required: true });+ });++ await goToCodeStep();+ await fillIn(".d-otp-input", "123456");++ assert.dom(".code-login-form__user-fields-step").exists();+ assert+ .dom("#code-login-name")+ .exists()+ .hasAttribute("autocomplete", "name");++ await click(".code-login-form__verify");++ assert+ .dom(".code-login-form__name-field .code-login-form__error")+ .hasText(i18n("user.name.required"));+ assert.strictEqual(+ verifyRequests.length,+ 1,+ "an empty name is not submitted"+ );++ await fillIn("#code-login-name", " Jane Doe ");+ await click(".code-login-form__verify");++ assert.strictEqual(verifyRequests.length, 2);+ assert.strictEqual(+ verifyRequests[1].get("name"),+ "Jane Doe",+ "the trimmed name is sent"+ );+ assert.dom(".code-login-form__complete-step").exists();+ });+test("returns to the email step when using a different email", async function (assert) {stubCodeRequest();diff --git a/spec/requests/session_controller_spec.rb b/spec/requests/session_controller_spec.rbindex 7a784a36380..f70d9cc6ed4 100644--- a/spec/requests/session_controller_spec.rb+++ b/spec/requests/session_controller_spec.rb@@ -900,6 +900,59 @@ RSpec.describe SessionController doexpect(session[:current_user_id]).to be_nilendend++ context "when a full name is required at signup" do+ before { SiteSetting.full_name_requirement = "required_at_signup" }++ it "asks for the name without consuming the code, then creates the user with it" do+ post "/session/login-code/verify.json", params: { email: "[email protected]", code: }++ expect(response.status).to eq(200)+ expect(response.parsed_body["name_required"]).to eq(true)+ expect(response.parsed_body["user_fields_required"]).to eq(false)+ expect(session[:current_user_id]).to be_nil+ expect(EmailLoginCode.active.for_email("[email protected]")).to be_present++ post "/session/login-code/verify.json",+ params: {+ email: "[email protected]",+ code:,+ 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)+ end++ it "renders the contract errors when the name is too long" do+ post "/session/login-code/verify.json",+ params: {+ email: "[email protected]",+ code:,+ name: "a" * 256,+ }++ expect(response.status).to eq(400)+ expect(response.parsed_body["errors"].join).to include("Name")+ expect(session[:current_user_id]).to be_nil+ expect(User.find_by_email("[email protected]")).to be_nil+ end++ it "asks for the name again when a blank name is submitted" do+ post "/session/login-code/verify.json",+ params: {+ email: "[email protected]",+ code:,+ name: " ",+ }++ expect(response.status).to eq(200)+ expect(response.parsed_body["name_required"]).to eq(true)+ expect(session[:current_user_id]).to be_nil+ expect(User.find_by_email("[email protected]")).to be_nil+ end+ endendcontext "when the user has TOTP enabled" dodiff --git a/spec/services/email_login_code/redeem_spec.rb b/spec/services/email_login_code/redeem_spec.rbindex 2241c512254..74158d0a0ec 100644--- a/spec/services/email_login_code/redeem_spec.rb+++ b/spec/services/email_login_code/redeem_spec.rb@@ -5,6 +5,7 @@ RSpec.describe EmailLoginCode::Redeem doit { is_expected.to validate_presence_of(:email) }it { is_expected.to validate_presence_of(:code) }it { is_expected.not_to allow_values("12345", "abcdef").for(:code) }+ it { is_expected.to validate_length_of(:name).is_at_most(255) }enddescribe ".call" do@@ -126,6 +127,20 @@ RSpec.describe EmailLoginCode::Redeem doexpect(result[:user].username).to eq("jane")end+ it "defaults the name to the generated username" do+ user = result[:user]++ expect(user.name).to eq(user.username)+ 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" doexpect { result }.to change {Jobs::SendSystemMessage.jobs.count do |job|@@ -210,6 +225,42 @@ RSpec.describe EmailLoginCode::Redeem doendend+ context "when a full name is required at signup" do+ before { SiteSetting.full_name_requirement = "required_at_signup" }++ it { is_expected.to fail_a_policy(:required_full_name_provided) }++ it "does not consume the code" do+ result++ expect(login_code.reload.consumed_at).to be_nil+ end++ context "when the name is only whitespace" do+ 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:, name: "Jane Doe" } }++ it { is_expected.to run_successfully }++ it "saves the name on the new user" do+ expect(result[:user].name).to eq("Jane Doe")+ end+ end++ context "when the email belongs to an existing active user" do+ fab!(:user)++ let(:email) { user.email }++ it { is_expected.to run_successfully }+ end+ end+context "when the email belongs to a staged user" dofab!(:staged_user) { Fabricate(:staged, active: false) }diff --git a/spec/system/code_signup_spec.rb b/spec/system/code_signup_spec.rbindex 9355525e694..7ba40098ab8 100644--- a/spec/system/code_signup_spec.rb+++ b/spec/system/code_signup_spec.rb@@ -207,4 +207,30 @@ describe "Sign up via email code" doexpect(user.custom_fields["user_field_#{user_field.id}"]).to eq("Dev")endend++ context "when a full name is required at signup" do+ before { SiteSetting.full_name_requirement = "required_at_signup" }++ it "collects the name after the code is verified" do+ visit("/signup")+ submit_email("[email protected]")+ fill_code(latest_emailed_code("[email protected]"))++ expect(page).to have_css(".code-login-form__user-fields-step")+ expect(page).to have_css("#code-login-name")++ find(".code-login-form__user-fields-step .code-login-form__verify").click+ expect(page).to have_css(+ ".code-login-form__name-field .code-login-form__error",+ text: I18n.t("js.user.name.required"),+ )+ expect(page).to have_css(".code-login-form__user-fields-step")++ fill_in("code-login-name", with: "Jane Doe")+ find(".code-login-form__user-fields-step .code-login-form__verify").click++ expect(page).to have_css(".code-login-form__complete-step")+ expect(User.find_by_email("[email protected]").name).to eq("Jane Doe")+ end+ endend