Skip to content

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

FEATURE: Sign up with a one-time email code (#40909)

Keegan George8b280eb7b03f
diff --git a/app/assets/stylesheets/common/login/code-login-form.scss b/app/assets/stylesheets/common/login/code-login-form.scss
index 9389874c40c..c0735d0ae14 100644
--- a/app/assets/stylesheets/common/login/code-login-form.scss
+++ b/app/assets/stylesheets/common/login/code-login-form.scss
@@ -1,3 +1,17 @@
+@use "lib/viewport";
+
+@keyframes code-login-form-step-in {
+ from {
+ opacity: 0;
+ transform: translateY(0.5rem);
+ }
+
+ to {
+ opacity: 1;
+ transform: translateY(0);
+ }
+}
+
.code-login-form {
display: flex;
flex-direction: column;
@@ -10,11 +24,81 @@
}
&__code-step,
- &__second-factor-step {
+ &__second-factor-step,
+ &__user-fields-step,
+ &__complete-step {
display: flex;
flex-direction: column;
align-items: flex-start;
gap: 1em;
+
+ // Ease each step in so advancing through the flow doesn't snap abruptly.
+ @media (prefers-reduced-motion: no-preference) {
+ animation: code-login-form-step-in 0.25s ease;
+ }
+ }
+
+ &__user-fields-step {
+ .user-fields {
+ align-self: stretch;
+ margin-top: 0.5em;
+ }
+ }
+
+ &__new-account {
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ align-self: stretch;
+ gap: 1em;
+ padding: 1em 0;
+ }
+
+ &__avatar {
+ position: relative;
+ padding: 0;
+ border: none;
+ background: none;
+ cursor: pointer;
+ line-height: 0;
+
+ .avatar {
+ display: block;
+ }
+ }
+
+ &__avatar-edit {
+ position: absolute;
+ right: 0;
+ bottom: 0;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ width: 2em;
+ height: 2em;
+ border-radius: 50%;
+ background: var(--tertiary);
+ color: var(--secondary);
+
+ .d-icon {
+ margin: 0;
+ }
+ }
+
+ &__username-field {
+ display: flex;
+ flex-direction: column;
+ align-self: stretch;
+ gap: 0.25em;
+ }
+
+ &__new-account-username {
+ width: 100%;
+ margin: 0;
+ }
+
+ &__continue-to-site {
+ align-self: stretch;
}
&__title {
@@ -52,3 +136,30 @@
gap: 0.5em;
}
}
+
+// Keep the disclaimer from hugging the continue button it follows.
+.code-login-form + .signup-page-cta__disclaimer {
+ margin-top: 1.5em;
+}
+
+// Scoped to the passwordless signup flow so login and regular signup are untouched.
+@include viewport.until(md) {
+ .signup-page .signup-body.passwordless-signup {
+ padding: 1.5rem;
+
+ // Drop the heading's own padding so it lines up with the form below it.
+ .login-welcome-header {
+ padding: 0;
+ margin-bottom: 1rem;
+ }
+
+ .code-login-form__email-actions {
+ align-self: stretch;
+ }
+
+ .code-login-form__continue,
+ .code-login-form__verify {
+ width: 100%;
+ }
+ }
+}
diff --git a/app/controllers/session_controller.rb b/app/controllers/session_controller.rb
index 3200b8773b6..a20d0832411 100644
--- a/app/controllers/session_controller.rb
+++ b/app/controllers/session_controller.rb
@@ -898,12 +898,34 @@ class SessionController < ApplicationController
end
end
- EmailLoginCode::Redeem.call(service_params) do |result|
- on_success { |user:| login_with_login_code(user) }
+ return render json: { user_fields_required: true } if needs_signup_user_fields?(matched_user)
+
+ EmailLoginCode::Redeem.call(
+ service_params.deep_merge(ip_address: request.remote_ip),
+ ) do |result|
+ on_success do |user:, existing_user:|
+ login_with_login_code(user, created_account: existing_user.nil?)
+ end
+ on_failed_policy(:can_register_new_account) do
+ render json: { error: I18n.t("login.new_registrations_disabled") }
+ end
+ on_failed_policy(:required_fields_provided) do
+ render json: { error: I18n.t("login.missing_user_field") }
+ end
on_failure { render json: invalid_login_code }
end
end
+ # 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
+ # 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 &&
+ !SiteSetting.require_invite_code
+ end
+
def login_code_second_factor_info(user)
response = { second_factor_required: true }
@@ -928,13 +950,38 @@ class SessionController < ApplicationController
params[:second_factor_token].blank?
end
- def login_with_login_code(user)
+ def login_with_login_code(user, created_account: false)
raise Discourse::ReadOnly if @staff_writes_only_mode && !user.staff?
if login_not_approved_for?(user)
render json: login_not_approved
elsif payload = login_error_check(user)
render json: payload
+ elsif created_account && !cookies[:sso_payload]
+ # Same tail as `login`, except the response tells the client a new
+ # account was created so it can show the "account ready" step before
+ # following the usual post-login redirect.
+ session.delete(ACTIVATE_USER_KEY)
+ user.update_timezone_if_missing(params[:timezone])
+ log_on_user(user, replay_anonymous_action: true)
+ render json:
+ success_json.merge(
+ account_created: true,
+ user: serialize_data(user, UserSerializer, root: false),
+ # The username is only worth prefilling when it was derived
+ # from the email; otherwise it's a generic fallback and the
+ # client should make the user pick one.
+ prefill_username: SiteSetting.use_email_for_username_and_name_suggestions,
+ # Sites that lock usernames (e.g. username_change_period: 0)
+ # can't offer an inline pick, so the client keeps the generated
+ # name instead of dead-ending on a forbidden change.
+ can_edit_username: user.guardian.can_edit_username?(user),
+ # `can_upload_avatar` lives on CurrentUserSerializer, but the
+ # account-ready step builds the user from UserSerializer, so
+ # the avatar picker needs the upload permission passed through.
+ can_upload_avatar:
+ user.in_any_groups?(SiteSetting.uploaded_avatars_allowed_groups_map),
+ )
else
login(user)
end
diff --git a/app/services/email_login_code/redeem.rb b/app/services/email_login_code/redeem.rb
index a97f5466f64..d518db96e31 100644
--- a/app/services/email_login_code/redeem.rb
+++ b/app/services/email_login_code/redeem.rb
@@ -3,13 +3,42 @@
class EmailLoginCode::Redeem
include Service::Base
- params base_class: EmailLoginCode::Verify::Contract
+ params base_class: EmailLoginCode::Verify::Contract do
+ attribute :user_fields
+
+ before_validation do
+ # Only hash-like input can carry field values; anything else (a stray
+ # string/array) becomes an empty set so it fails as a missing field
+ # rather than raising during normalization.
+ self.user_fields =
+ (
+ if user_fields.is_a?(Hash) || user_fields.is_a?(ActionController::Parameters)
+ user_fields.to_h.stringify_keys
+ else
+ {}
+ end
+ )
+ end
+ end
model :login_code
policy :code_matches
- model :user, :fetch_user
- step :consume_code
- only_if(:user_requires_activation?) { step :activate_user }
+ model :existing_user, :fetch_existing_user, optional: true
+ policy :email_available_for_new_account
+ policy :can_register_new_account
+ policy :required_fields_provided
+
+ lock(:email) do
+ transaction do
+ step :consume_code
+ model :user, :ensure_user
+ end
+ end
+
+ only_if(:user_requires_activation?) do
+ step :activate_user
+ step :send_welcome_message
+ end
private
@@ -21,16 +50,63 @@ class EmailLoginCode::Redeem
login_code.verify(params.code)
end
- def fetch_user(params:)
+ def fetch_existing_user(params:)
User.real.where(staged: false).with_email(params.email).first
end
+ # Login matches on the exact address only, but a code's address can still
+ # 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 email_available_for_new_account(existing_user:, params:)
+ return true if existing_user.present?
+
+ User::Action::FindByEmail.call(email: params.email).blank?
+ end
+
+ def can_register_new_account(existing_user:, params:)
+ return true if existing_user.present?
+
+ # Mirrors EmailLoginCode::Request#deliverable? so account creation enforces
+ # the same gates as the code request, even for a code issued before an
+ # address was blocked or one created outside the request service.
+ SiteSetting.allow_new_registrations && !SiteSetting.invite_only &&
+ !SiteSetting.require_invite_code && EmailValidator.allowed?(params.email) &&
+ !ScreenedEmail.should_block?(params.email)
+ end
+
+ def required_fields_provided(existing_user:, params:)
+ return true if existing_user.present?
+
+ values = params.user_fields.presence || {}
+ # Only the fields shown at signup can be collected here (the UI and
+ # CreateFromVerifiedEmail both use show_on_signup); requiring a hidden field
+ # would make passwordless signup impossible to complete.
+ UserField
+ .required
+ .where(show_on_signup: true)
+ .pluck(:id)
+ .all? do |field_id|
+ value = values[field_id.to_s]
+ value.present? && value != "false"
+ end
+ end
+
def consume_code(login_code:)
# consume! is atomic; if it lost a race with a concurrent redemption the
# code is already spent, so this redemption must not log anyone in.
fail!("code already redeemed") unless login_code.consume!
end
+ def ensure_user(existing_user:, params:, ip_address:)
+ existing_user ||
+ User::Action::CreateFromVerifiedEmail.call(
+ email: params.email,
+ ip_address: ip_address,
+ user_fields: params.user_fields,
+ )
+ end
+
def user_requires_activation?(user:)
!user.active?
end
@@ -38,4 +114,12 @@ class EmailLoginCode::Redeem
def activate_user(user:)
user.activate
end
+
+ def send_welcome_message(user:)
+ # Don't welcome accounts that can't access the forum yet (e.g. awaiting
+ # approval under must_approve_users), matching the normal signup path.
+ return if !user.guardian.can_access_forum?
+
+ user.enqueue_welcome_message("welcome_user")
+ end
end
diff --git a/app/services/email_login_code/request.rb b/app/services/email_login_code/request.rb
index 5e34af565e7..ece46a89e61 100644
--- a/app/services/email_login_code/request.rb
+++ b/app/services/email_login_code/request.rb
@@ -19,13 +19,9 @@ class EmailLoginCode::Request
end
model :user, optional: true
+ only_if(:existing_account?) { step :trigger_before_email_login }
- # The code only ever logs an existing user in, so a code is generated and
- # emailed only when the address matches a real account. Unknown addresses
- # still get a successful (empty) response, so the endpoint can't be used to
- # probe whether an account exists.
- only_if(:existing_account?) do
- step :trigger_before_email_login
+ only_if(:deliverable?) do
model :login_code, :generate_login_code
step :send_login_code_email
end
@@ -44,6 +40,21 @@ class EmailLoginCode::Request
DiscourseEvent.trigger(:before_email_login, user)
end
+ def deliverable?(user:, params:)
+ return true if user.present?
+ return if !SiteSetting.allow_new_registrations
+ return if SiteSetting.invite_only
+ return if SiteSetting.require_invite_code
+ return if !EmailValidator.allowed?(params.email)
+ return if ScreenedEmail.should_block?(params.email)
+ # Login matches on the exact address, but a new account can't be created for
+ # an email that already belongs to someone once normalized, so don't send a
+ # code that could never be redeemed into an account.
+ return if User::Action::FindByEmail.call(email: params.email)
+
+ true
+ end
+
def generate_login_code(params:)
EmailLoginCode.generate!(email: params.email)
end
diff --git a/app/services/user/action/create_from_verified_email.rb b/app/services/user/action/create_from_verified_email.rb
new file mode 100644
index 00000000000..1b8e83df0e0
--- /dev/null
+++ b/app/services/user/action/create_from_verified_email.rb
@@ -0,0 +1,53 @@
+# frozen_string_literal: true
+
+class User::Action::CreateFromVerifiedEmail < Service::ActionBase
+ option :email
+ option :ip_address, optional: true
+ option :user_fields, optional: true
+
+ def call
+ username = UserNameSuggester.suggest(email)
+
+ user = User.where(staged: true).with_email(email).first
+ user&.unstage!
+ user ||= User.new
+
+ user.attributes = {
+ email: email,
+ username: username,
+ name: username,
+ active: false,
+ locale: I18n.locale,
+ ip_address: ip_address,
+ registration_ip_address: ip_address,
+ }
+
+ assign_user_fields(user)
+
+ if SiteSetting.must_approve_users? && EmailValidator.can_auto_approve_user?(email)
+ ReviewableUser.set_approved_fields!(user, Discourse.system_user)
+ end
+
+ user.save!
+ user
+ end
+
+ private
+
+ def assign_user_fields(user)
+ return if user_fields.blank?
+
+ fields = user.custom_fields
+ UserField
+ .where(show_on_signup: true)
+ .pluck(:id)
+ .each do |field_id|
+ value = user_fields[field_id.to_s]
+ value = nil if value == "false"
+ fields["#{User::USER_FIELD_PREFIX}#{field_id}"] = value[
+ 0...UserField.max_length
+ ] if value.present?
+ end
+ user.custom_fields = fields
+ end
+end
diff --git a/config/locales/client.en.yml b/config/locales/client.en.yml
index 151b3ca55d3..c983b411e4e 100644
--- a/config/locales/client.en.yml
+++ b/config/locales/client.en.yml
@@ -2929,6 +2929,18 @@ en:
use_different_email: "Use a different email address"
use_password_instead: "Log in with your password instead"
email_me_code: "Email me a one-time login code"
+ signup_title: "Join this community"
+ signup_instructions: "Enter your email address to join this community. We'll send you a code to confirm it and you'll be on your way!"
+ user_fields_title: "Almost done"
+ user_fields_instructions: "Just a few more details to finish creating your account."
+ account_ready_title: "Your account is ready! 🎉"
+ account_ready_edit: "Pick your username and avatar"
+ account_ready_continue: "Continue"
+ username_label: "Username"
+ username_placeholder: "Choose a username"
+ change_avatar: "Change avatar"
+ username_taken: "That username is taken. Try another."
+ username_unavailable: "That username isn't available. Try %{suggestion}."
login:
header_title: "Welcome back"
diff --git a/config/locales/server.en.yml b/config/locales/server.en.yml
index 3bd57dc9894..189e35ecd23 100644
--- a/config/locales/server.en.yml
+++ b/config/locales/server.en.yml
@@ -2138,7 +2138,7 @@ en:
enable_local_logins: "Enable local username and password login based accounts. WARNING: if disabled, you may be unable to log in if you have not previously configured at least one alternate login method."
enable_local_logins_via_email: "Allow users to request a one-click login link to be sent to them via email."
- enable_local_logins_via_code: "Send a one-time code instead of a login link when a user logs in via email. Requires 'enable local logins via email'."
+ enable_local_logins_via_code: "Send a one-time code instead of a login link when a user logs in via email, and let new users sign up with just an email address and that code. Requires 'enable local logins via email'."
allow_passkeys_for_2fa: "Allow users to use a passkey to satisfy two-factor authentication when confirming a sensitive action."
allow_new_registrations: "Allow new user registrations. Uncheck this to prevent anyone from creating a new account."
enable_signup_cta: "Show a notice to returning anonymous users prompting them to sign up for an account."
diff --git a/frontend/discourse/app/components/code-login-form.gjs b/frontend/discourse/app/components/code-login-form.gjs
index 5cb40305d79..06713a8ac48 100644
--- a/frontend/discourse/app/components/code-login-form.gjs
+++ b/frontend/discourse/app/components/code-login-form.gjs
@@ -1,37 +1,56 @@
import Component from "@glimmer/component";
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 { service } from "@ember/service";
import { trustHTML } from "@ember/template";
import Form from "discourse/components/form";
+import AvatarSelectorModal from "discourse/components/modal/avatar-selector";
import SecondFactorForm from "discourse/components/second-factor-form";
import SecurityKeyForm from "discourse/components/security-key-form";
+import UserField from "discourse/components/user-field";
+import valueEntered from "discourse/helpers/value-entered";
import { ajax } from "discourse/lib/ajax";
import { popupAjaxError } from "discourse/lib/ajax-error";
import cookie, { removeCookie } from "discourse/lib/cookie";
+import discourseDebounce from "discourse/lib/debounce";
import escape from "discourse/lib/escape";
import getURL from "discourse/lib/get-url";
import discourseLater from "discourse/lib/later";
+import UserFieldsValidationHelper from "discourse/lib/user-fields-validation-helper";
import { emailValid } from "discourse/lib/utilities";
import { getWebauthnCredential } from "discourse/lib/webauthn";
-import { SECOND_FACTOR_METHODS } from "discourse/models/user";
+import User, { SECOND_FACTOR_METHODS } from "discourse/models/user";
import DButton from "discourse/ui-kit/d-button";
import DOtp from "discourse/ui-kit/d-otp";
import DSecondFactorInput from "discourse/ui-kit/d-second-factor-input";
+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;
export default class CodeLoginForm extends Component {
- @tracked step = "email";
+ @service site;
+ @service modal;
+
@tracked email = this.args.initialEmail ?? "";
@tracked verifying = false;
@tracked codeError;
@tracked notice;
@tracked resendCooldown = 0;
@tracked otpGeneration = 0;
-
+ @tracked newAccount;
+ @tracked accountUser;
+ @tracked username = "";
+ @tracked usernameAvailable = false;
+ @tracked usernameChecking = false;
+ @tracked usernameError;
+ @tracked usernameEditable = true;
+ @tracked avatarTemplate;
+ @tracked avatarDetailsLoaded = false;
@tracked secondFactorMethod = SECOND_FACTOR_METHODS.TOTP;
@tracked secondFactorToken;
@tracked securityKeyCredential;
@@ -40,15 +59,36 @@ export default class CodeLoginForm extends Component {
@tracked securityKeyRequired = false;
@tracked securityKeyChallenge;
@tracked securityKeyAllowedCredentialIds;
-
code = "";
+ userFieldsValidationHelper = new UserFieldsValidationHelper({
+ getUserFields: () =>
+ this.site.get("user_fields")?.filter((f) => f.show_on_signup),
+ getAccountPassword: () => null,
+ showValidationOnInit: false,
+ });
#cooldownTimer;
+ #usernameCheckSeq = 0;
+ @tracked _step = "email";
willDestroy() {
super.willDestroy(...arguments);
cancel(this.#cooldownTimer);
}
+ // Tracked-backed so the parent can react to step transitions via onStepChange.
+ get step() {
+ return this._step;
+ }
+
+ set step(value) {
+ this._step = value;
+ this.args.onStepChange?.(value);
+ }
+
+ get isSignup() {
+ return this.args.context === "signup";
+ }
+
get isEmailStep() {
return this.step === "email";
}
@@ -67,6 +107,29 @@ export default class CodeLoginForm extends Component {
return this.totpEnabled || this.backupCodesEnabled;
}
+ get isUserFieldsStep() {
+ return this.step === "user-fields";
+ }
+
+ get isCompleteStep() {
+ return this.step === "complete";
+ }
+
+ get continueDisabled() {
+ if (this.verifying) {
+ return true;
+ }
+ // When the username can't be changed there's nothing to validate.
+ if (!this.usernameEditable) {
+ return false;
+ }
+ return !this.usernameAvailable || this.usernameChecking;
+ }
+
+ get userFields() {
+ return this.userFieldsValidationHelper.userFields;
+ }
+
// Re-rendering DOtp with a fresh identity is the only way to clear it
get otpGenerationArray() {
return [this.otpGeneration];
@@ -163,12 +226,22 @@ export default class CodeLoginForm extends Component {
data.second_factor_method = this.secondFactorMethod;
}
+ if (this.isUserFieldsStep) {
+ data.user_fields = {};
+ this.userFields.forEach((f) => (data.user_fields[f.field.id] = f.value));
+ }
+
try {
const result = await ajax("/session/login-code/verify", {
type: "POST",
data,
});
+ if (result?.user_fields_required && !this.isUserFieldsStep) {
+ this.step = "user-fields";
+ return;
+ }
+
if (result?.second_factor_required && !this.isSecondFactorStep) {
this.totpEnabled = result.totp_enabled;
this.backupCodesEnabled = result.backup_codes_enabled;
@@ -186,6 +259,8 @@ export default class CodeLoginForm extends Component {
if (this.isSecondFactorStep) {
this.securityKeyCredential = null;
this.codeError = result.error;
+ } else if (this.isUserFieldsStep) {
+ this.codeError = result.error;
} else {
this.codeError = result.error;
this.code = "";
@@ -194,15 +269,13 @@ export default class CodeLoginForm extends Component {
return;
}
- const destinationUrl = cookie("destination_url");
- if (result?.redirect_url) {
- window.location.assign(result.redirect_url);
- } else if (destinationUrl) {
- removeCookie("destination_url");
- window.location.assign(destinationUrl);
- } else {
- window.location.assign(getURL("/"));
+ if (result?.account_created) {
+ this.setupNewAccount(result);
+ this.step = "complete";
+ return;
}
+
+ this.redirectAfterLogin(result?.redirect_url);
} catch (e) {
popupAjaxError(e);
} finally {
@@ -210,6 +283,146 @@ export default class CodeLoginForm extends Component {
}
}
+ @action
+ async submitUserFields() {
+ this.userFieldsValidationHelper.validationVisible = true;
+ if (this.userFieldsValidationHelper.userFieldsValidation.failed) {
+ return;
+ }
+ return this.verifyCode();
+ }
+
+ // The account is logged in server-side but the app is still in its anonymous
+ // boot state, so username/avatar are edited through authenticated requests on
+ // a User model built from the verify response rather than the current user.
+ setupNewAccount(result) {
+ const user = result.user;
+ this.newAccount = user;
+ // can_upload_avatar isn't in UserSerializer, so carry it from the response.
+ this.accountUser = User.create({
+ ...user,
+ can_upload_avatar: result.can_upload_avatar,
+ });
+ this.usernameEditable = result.can_edit_username;
+ // Only prefill an email-derived suggestion; otherwise the user picks one.
+ this.username = result.prefill_username ? user.username : "";
+ this.avatarTemplate = user.avatar_template;
+ if (this.usernameEditable && this.username) {
+ this.checkUsernameAvailability();
+ }
+ }
+
+ @action
+ usernameChanged(event) {
+ this.username = event.target.value;
+ this.usernameAvailable = false;
+ this.usernameError = null;
+ discourseDebounce(this, this.checkUsernameAvailability, 350);
+ }
+
+ async checkUsernameAvailability() {
+ const username = this.username?.trim();
+ if (!username) {
+ this.usernameAvailable = false;
+ this.usernameError = null;
+ return;
+ }
+
+ // Ignore responses that arrive out of order behind a newer check.
+ const seq = ++this.#usernameCheckSeq;
+ this.usernameChecking = true;
+ try {
+ const result = await User.checkUsername(
+ username,
+ this.email,
+ this.newAccount.id
+ );
+
+ if (seq !== this.#usernameCheckSeq) {
+ return;
+ }
+
+ if (result.available) {
+ this.usernameAvailable = true;
+ this.usernameError = null;
+ } else {
+ this.usernameAvailable = false;
+ this.usernameError =
+ result.errors?.join(" ") ||
+ (result.suggestion
+ ? i18n("code_login.username_unavailable", {
+ suggestion: result.suggestion,
+ })
+ : i18n("code_login.username_taken"));
+ }
+ } catch {
+ if (seq === this.#usernameCheckSeq) {
+ this.usernameAvailable = false;
+ }
+ } finally {
+ if (seq === this.#usernameCheckSeq) {
+ this.usernameChecking = false;
+ }
+ }
+ }
+
+ @action
+ async changeAvatar() {
+ try {
+ // The picker needs the gravatar/system/upload state, loaded on demand.
+ if (!this.avatarDetailsLoaded) {
+ await this.accountUser.findDetails();
+ this.avatarDetailsLoaded = true;
+ }
+ } catch (e) {
+ return popupAjaxError(e);
+ }
+
+ this.modal.show(AvatarSelectorModal, {
+ model: {
+ user: this.accountUser,
+ onAvatarChange: () => this.avatarChanged(),
+ },
+ });
+ }
+
+ async avatarChanged() {
+ // pickAvatar doesn't update the model, so reload to show the new avatar.
+ try {
+ await this.accountUser.findDetails();
+ this.avatarTemplate = this.accountUser.avatar_template;
+ } catch (e) {
+ popupAjaxError(e);
+ }
+ }
+
+ @action
+ async continueAfterSignup() {
+ if (this.continueDisabled) {
+ return;
+ }
+
+ this.verifying = true;
+
+ const username = this.username.trim();
+ if (
+ this.usernameEditable &&
+ username.toLowerCase() !== this.newAccount.username.toLowerCase()
+ ) {
+ try {
+ await this.accountUser.changeUsername(username);
+ } catch (e) {
+ this.verifying = false;
+ popupAjaxError(e);
+ return;
+ }
+ }
+
+ // Leave the button disabled and spinning through the redirect so it doesn't
+ // flash back to its idle state before the page navigates away.
+ this.redirectAfterLogin();
+ }
+
@action
submitSecondFactor() {
this.securityKeyCredential = null;
@@ -271,6 +484,18 @@ export default class CodeLoginForm extends Component {
}
}
+ redirectAfterLogin(redirectUrl) {
+ const destinationUrl = cookie("destination_url");
+ if (redirectUrl) {
+ window.location.assign(redirectUrl);
+ } else if (destinationUrl) {
+ removeCookie("destination_url");
+ window.location.assign(destinationUrl);
+ } else {
+ window.location.assign(getURL("/"));
+ }
+ }
+
startResendCooldown() {
cancel(this.#cooldownTimer);
this.resendCooldown = RESEND_COOLDOWN_SECONDS;
@@ -291,6 +516,12 @@ export default class CodeLoginForm extends Component {
<template>
<div class="code-login-form">
{{#if this.isEmailStep}}
+ {{#if this.isSignup}}
+ <p class="code-login-form__instructions">
+ {{i18n "code_login.signup_instructions"}}
+ </p>
+ {{/if}}
+
<Form
@data={{hash email=this.email}}
@onSubmit={{this.submitEmail}}
@@ -376,6 +607,103 @@ export default class CodeLoginForm extends Component {
/>
</div>
</div>
+ {{else if this.isCompleteStep}}
+ <div class="code-login-form__complete-step">
+ <h2 class="code-login-form__title">
+ {{i18n "code_login.account_ready_title"}}
+ </h2>
+ {{#if this.usernameEditable}}
+ <p class="code-login-form__instructions">
+ {{i18n "code_login.account_ready_edit"}}
+ </p>
+ {{/if}}
+
+ <div class="code-login-form__new-account">
+ <button
+ type="button"
+ class="code-login-form__avatar"
+ title={{i18n "code_login.change_avatar"}}
+ {{on "click" this.changeAvatar}}
+ >
+ {{dBoundAvatarTemplate this.avatarTemplate "huge"}}
+ <span class="code-login-form__avatar-edit">
+ {{dIcon "pencil"}}
+ </span>
+ </button>
+
+ {{#if this.usernameEditable}}
+ <div class="code-login-form__username-field">
+ <label for="code-login-username">
+ {{i18n "code_login.username_label"}}
+ </label>
+ <input
+ {{on "input" this.usernameChanged}}
+ type="text"
+ value={{this.username}}
+ id="code-login-username"
+ name="username"
+ autocomplete="off"
+ placeholder={{i18n "code_login.username_placeholder"}}
+ class="code-login-form__new-account-username"
+ aria-invalid={{if this.usernameError "true"}}
+ />
+ <div
+ class="code-login-form__error"
+ aria-live="polite"
+ role="alert"
+ >
+ {{this.usernameError}}
+ </div>
+ </div>
+ {{else}}
+ <div class="code-login-form__new-account-username">
+ {{this.newAccount.username}}
+ </div>
+ {{/if}}
+ </div>
+
+ <DButton
+ @action={{this.continueAfterSignup}}
+ @label="code_login.account_ready_continue"
+ @disabled={{this.continueDisabled}}
+ @isLoading={{this.verifying}}
+ class="btn-large btn-primary code-login-form__continue-to-site"
+ />
+ </div>
+ {{else if this.isUserFieldsStep}}
+ <div class="code-login-form__user-fields-step">
+ <h2 class="code-login-form__title">
+ {{i18n "code_login.user_fields_title"}}
+ </h2>
+ <p class="code-login-form__instructions">
+ {{i18n "code_login.user_fields_instructions"}}
+ </p>
+
+ <div class="user-fields">
+ {{#each this.userFields as |f|}}
+ <div class="input-group">
+ <UserField
+ @field={{f.field}}
+ @value={{f.value}}
+ @validation={{f.validation}}
+ class={{valueEntered f.value}}
+ />
+ </div>
+ {{/each}}
+ </div>
+
+ <div class="code-login-form__error" aria-live="polite" role="alert">
+ {{this.codeError}}
+ </div>
+
+ <DButton
+ @action={{this.submitUserFields}}
+ @label="code_login.continue_button"
+ @isLoading={{this.verifying}}
+ type="submit"
+ class="btn-primary code-login-form__verify"
+ />
+ </div>
{{else}}
<div class="code-login-form__second-factor-step">
{{#if this.codeError}}
diff --git a/frontend/discourse/app/components/modal/avatar-selector.gjs b/frontend/discourse/app/components/modal/avatar-selector.gjs
index 13267f9a713..966db4ffaf2 100644
--- a/frontend/discourse/app/components/modal/avatar-selector.gjs
+++ b/frontend/discourse/app/components/modal/avatar-selector.gjs
@@ -101,9 +101,11 @@ export default class AvatarSelectorModal extends Component {
}
get allowAvatarUpload() {
+ // Falls back to the edited user when there is no current user yet, e.g.
+ // right after a passwordless signup before the app has rebooted.
+ const user = this.currentUser ?? this.user;
return (
- this.currentUser.can_upload_avatar &&
- allowsImages(this.currentUser.staff, this.siteSettings)
+ user.can_upload_avatar && allowsImages(user.staff, this.siteSettings)
);
}
@@ -116,12 +118,23 @@ export default class AvatarSelectorModal extends Component {
this.selected = value;
}
+ // Callers that pass `model.onAvatarChange` (e.g. inline signup) handle the
+ // result themselves; otherwise we reload so the new avatar shows everywhere.
+ afterAvatarSaved({ guardTesting = false } = {}) {
+ if (this.args.model.onAvatarChange) {
+ this.args.model.onAvatarChange();
+ this.args.closeModal?.();
+ } else if (!guardTesting || !isTesting()) {
+ window.location.reload();
+ }
+ }
+
@action
async selectAvatar(url, event) {
event?.preventDefault();
try {
await this.user.selectAvatar(url);
- window.location.reload();
+ this.afterAvatarSaved();
} catch (error) {
popupAjaxError(error);
}
@@ -162,9 +175,7 @@ export default class AvatarSelectorModal extends Component {
async saveAvatarSelection() {
try {
await this.user.pickAvatar(this.selectedUploadId, this.selected);
- if (!isTesting()) {
- window.location.reload();
- }
+ this.afterAvatarSaved({ guardTesting: true });
} catch (error) {
popupAjaxError(error);
}
diff --git a/frontend/discourse/app/controllers/signup.js b/frontend/discourse/app/controllers/signup.js
index 95d4fcf7447..9b1f493ce85 100644
--- a/frontend/discourse/app/controllers/signup.js
+++ b/frontend/discourse/app/controllers/signup.js
@@ -36,6 +36,7 @@ export default class SignupPageController extends Controller {
@tracked skipConfirmation;
@tracked serverAccountEmail;
@tracked serverEmailValidation;
+ @tracked codeSignupStep = "email";
@autoTrackedArray rejectedEmails = [];
accountChallenge = 0;
@@ -137,10 +138,31 @@ export default class SignupPageController extends Controller {
@computed("hasAuthOptions", "canCreateLocal", "skipConfirmation")
get showCreateForm() {
return (
- (this.hasAuthOptions || this.canCreateLocal) && !this.skipConfirmation
+ (this.hasAuthOptions || this.canCreateLocal) &&
+ !this.skipConfirmation &&
+ !this.showCodeSignupForm
);
}
+ @computed("hasAuthOptions", "canCreateLocal", "skipConfirmation")
+ get showCodeSignupForm() {
+ return (
+ this.siteSettings.enable_local_logins_via_code &&
+ this.canCreateLocal &&
+ !this.hasAuthOptions &&
+ !this.skipConfirmation
+ );
+ }
+
+ get codeSignupOnEmailStep() {
+ return this.codeSignupStep === "email";
+ }
+
+ @action
+ updateCodeSignupStep(step) {
+ this.codeSignupStep = step;
+ }
+
@computed("site.desktopView", "hasAuthOptions")
get showExternalLoginButtons() {
return this.site?.desktopView && !this.hasAuthOptions;
@@ -151,7 +173,12 @@ export default class SignupPageController extends Controller {
return this.formSubmitted;
}
- @computed("userFields", "hasAtLeastOneLoginButton", "hasAuthOptions")
+ @computed(
+ "userFields",
+ "hasAtLeastOneLoginButton",
+ "hasAuthOptions",
+ "showCodeSignupForm"
+ )
get bodyClasses() {
const classes = [];
if (this.userFields) {
@@ -163,6 +190,9 @@ export default class SignupPageController extends Controller {
if (!this.canCreateLocal) {
classes.push("no-local-logins");
}
+ if (this.showCodeSignupForm) {
+ classes.push("passwordless-signup");
+ }
return classes.join(" ");
}
@@ -389,8 +419,16 @@ export default class SignupPageController extends Controller {
return findAll().length > 0;
}
- @computed("authOptions", "hasAtLeastOneLoginButton")
+ @computed(
+ "authOptions",
+ "hasAtLeastOneLoginButton",
+ "showCodeSignupForm",
+ "codeSignupStep"
+ )
get showRightSide() {
+ if (this.showCodeSignupForm && !this.codeSignupOnEmailStep) {
+ return false;
+ }
return !this.authOptions && this.hasAtLeastOneLoginButton;
}
diff --git a/frontend/discourse/app/instance-initializers/auth-complete.js b/frontend/discourse/app/instance-initializers/auth-complete.js
index 89da35b071f..f5647446995 100644
--- a/frontend/discourse/app/instance-initializers/auth-complete.js
+++ b/frontend/discourse/app/instance-initializers/auth-complete.js
@@ -96,6 +96,20 @@ export default {
}
next(() => {
+ // A bare email prefill (no external auth provider) feeds the
+ // email+code signup flow when it's enabled
+ if (
+ siteSettings.enable_local_logins_via_code &&
+ options.email &&
+ !options.auth_provider
+ ) {
+ router.transitionTo("signup").then(() => {
+ owner.lookup("controller:signup").accountEmail =
+ options.email;
+ });
+ return;
+ }
+
const site = owner.lookup("service:site");
const hasRequiredName =
!site.full_name_required_for_signup ||
diff --git a/frontend/discourse/app/templates/signup.gjs b/frontend/discourse/app/templates/signup.gjs
index 8836c9de482..350640ad5c7 100644
--- a/frontend/discourse/app/templates/signup.gjs
+++ b/frontend/discourse/app/templates/signup.gjs
@@ -1,6 +1,7 @@
import { Input } from "@ember/component";
import { on } from "@ember/modifier";
import { trustHTML } from "@ember/template";
+import CodeLoginForm from "discourse/components/code-login-form";
import FullnameInput from "discourse/components/fullname-input";
import HoneypotInput from "discourse/components/honeypot-input";
import LoginButtons from "discourse/components/login-buttons";
@@ -49,10 +50,16 @@ export default <template>
}}
>
{{#unless @controller.skipConfirmation}}
- <SignupProgressBar @step={{@controller.progressBarStep}} />
+ {{#unless @controller.showCodeSignupForm}}
+ <SignupProgressBar @step={{@controller.progressBarStep}} />
+ {{/unless}}
<WelcomeHeader
id="create-account-title"
- @header={{i18n "create_account.header_title"}}
+ @header={{if
+ @controller.showCodeSignupForm
+ (i18n "code_login.signup_title")
+ (i18n "create_account.header_title")
+ }}
>
<PluginOutlet
@name="create-account-header-bottom"
@@ -60,6 +67,20 @@ export default <template>
/>
</WelcomeHeader>
{{/unless}}
+ {{#if @controller.showCodeSignupForm}}
+ <CodeLoginForm
+ @context="signup"
+ @initialEmail={{@controller.accountEmail}}
+ @onStepChange={{@controller.updateCodeSignupStep}}
+ />
+ {{#if
+ (and @controller.codeSignupOnEmailStep @controller.disclaimerHtml)
+ }}
+ <div class="signup-page-cta__disclaimer">
+ {{trustHTML @controller.disclaimerHtml}}
+ </div>
+ {{/if}}
+ {{/if}}
{{#if @controller.showCreateForm}}
<form id="login-form">
{{#if @controller.associateHtml}}
diff --git a/spec/requests/session_controller_spec.rb b/spec/requests/session_controller_spec.rb
index 8a4e31b009a..65308db9f4d 100644
--- a/spec/requests/session_controller_spec.rb
+++ b/spec/requests/session_controller_spec.rb
@@ -807,13 +807,88 @@ RSpec.describe SessionController do
context "when the email does not belong to a user" do
let(:login_code) { EmailLoginCode.generate!(email: "[email protected]") }
- it "renders a generic error and does not create an account" do
+ it "creates and logs in a new user" do
post "/session/login-code/verify.json", params: { email: "[email protected]", code: }
expect(response.status).to eq(200)
- expect(response.parsed_body["error"]).to eq(I18n.t("email_login_code.invalid_code"))
+
+ new_user = User.find_by_email("[email protected]")
+ expect(new_user).to be_active
+ expect(session[:current_user_id]).to eq(new_user.id)
+ end
+
+ it "returns the flags the account-ready step needs" do
+ post "/session/login-code/verify.json", params: { email: "[email protected]", code: }
+
+ body = response.parsed_body
+ expect(body["account_created"]).to eq(true)
+ expect(body["can_edit_username"]).to eq(true)
+ # The avatar picker needs the upload permission, which isn't on
+ # UserSerializer. (Its value depends on automatic group membership,
+ # added on commit, so only assert the flag is present here.)
+ expect(body).to have_key("can_upload_avatar")
+ # Off by default, so the client makes the user pick rather than
+ # prefilling a generic username.
+ expect(body["prefill_username"]).to eq(false)
+ end
+
+ it "flags the username for prefill when email-based suggestions are on" do
+ SiteSetting.use_email_for_username_and_name_suggestions = true
+
+ post "/session/login-code/verify.json", params: { email: "[email protected]", code: }
+
+ expect(response.parsed_body["prefill_username"]).to eq(true)
+ end
+
+ it "renders an error when registrations are disabled" do
+ SiteSetting.allow_new_registrations = false
+
+ post "/session/login-code/verify.json", params: { email: "[email protected]", code: }
+
+ expect(response.status).to eq(200)
+ expect(response.parsed_body["error"]).to eq(I18n.t("login.new_registrations_disabled"))
expect(session[:current_user_id]).to be_nil
- expect(User.find_by_email("[email protected]")).to be_nil
+ end
+
+ context "when required signup fields exist" do
+ fab!(:user_field)
+
+ it "asks for the fields without consuming the code, then creates the user with them" do
+ post "/session/login-code/verify.json", params: { email: "[email protected]", code: }
+
+ expect(response.status).to eq(200)
+ expect(response.parsed_body["user_fields_required"]).to eq(true)
+ 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:,
+ user_fields: {
+ user_field.id.to_s => "Dev",
+ },
+ }
+
+ new_user = User.find_by_email("[email protected]")
+ expect(new_user.custom_fields["user_field_#{user_field.id}"]).to eq("Dev")
+ expect(session[:current_user_id]).to eq(new_user.id)
+ end
+
+ it "renders an error when the required fields are missing" do
+ post "/session/login-code/verify.json",
+ params: {
+ email: "[email protected]",
+ code:,
+ user_fields: {
+ "0" => "",
+ },
+ }
+
+ expect(response.status).to eq(200)
+ expect(response.parsed_body["error"]).to eq(I18n.t("login.missing_user_field"))
+ expect(session[:current_user_id]).to be_nil
+ end
end
end
diff --git a/spec/services/email_login_code/redeem_spec.rb b/spec/services/email_login_code/redeem_spec.rb
index fe6be25fba6..2241c512254 100644
--- a/spec/services/email_login_code/redeem_spec.rb
+++ b/spec/services/email_login_code/redeem_spec.rb
@@ -10,11 +10,9 @@ RSpec.describe EmailLoginCode::Redeem do
describe ".call" do
subject(:result) { described_class.call(params:, **dependencies) }
- fab!(:user)
-
let(:params) { { email:, code: } }
let(:dependencies) { { ip_address: "127.0.0.1" } }
- let(:email) { user.email }
+ let(:email) { "[email protected]" }
let!(:login_code) { EmailLoginCode.generate!(email:) }
@@ -38,35 +36,270 @@ RSpec.describe EmailLoginCode::Redeem do
it { is_expected.to fail_a_policy(:code_matches) }
end
- context "when the email does not belong to a user" do
- let(:email) { "[email protected]" }
+ context "when the email is unknown and registrations are disabled" do
+ before { SiteSetting.allow_new_registrations = false }
+
+ it { is_expected.to fail_a_policy(:can_register_new_account) }
+
+ it "does not consume the code or create a user" do
+ result
+
+ expect(login_code.reload.consumed_at).to be_nil
+ expect(User.find_by_email(email)).to be_nil
+ end
+ end
+
+ context "when the email domain is blocked" do
+ let(:email) { "[email protected]" }
+
+ before { SiteSetting.blocked_email_domains = "blocked.com" }
+
+ it { is_expected.to fail_a_policy(:can_register_new_account) }
+
+ it "does not consume the code or create a user" do
+ result
+
+ expect(login_code.reload.consumed_at).to be_nil
+ expect(User.find_by_email(email)).to be_nil
+ end
+ end
+
+ context "when the email is screened" do
+ let(:email) { "[email protected]" }
- it { is_expected.to fail_to_find_a_model(:user) }
+ before { Fabricate(:screened_email, email:, action_type: ScreenedEmail.actions[:block]) }
+
+ it { is_expected.to fail_a_policy(:can_register_new_account) }
+ end
+
+ context "when the email domain is not in the allowlist" do
+ let(:email) { "[email protected]" }
+
+ before { SiteSetting.allowed_email_domains = "allowed.com" }
+
+ it { is_expected.to fail_a_policy(:can_register_new_account) }
+ end
+
+ context "when the email matches an existing account only after normalization" do
+ fab!(:other_user) { Fabricate(:user, email: "[email protected]") }
+
+ let(:email) { "[email protected]" }
+
+ before { SiteSetting.normalize_emails = true }
+
+ it { is_expected.to fail_a_policy(:email_available_for_new_account) }
+
+ it "does not consume the code or create a user" do
+ result
+
+ expect(login_code.reload.consumed_at).to be_nil
+ expect(User.find_by_email(email)).to be_nil
+ end
+ end
+
+ context "when the email is unknown" do
+ let(:email) { "[email protected]" }
+
+ it { is_expected.to run_successfully }
+
+ it "consumes the code" do
+ expect { result }.to change { login_code.reload.consumed_at }.from(nil)
+ end
+
+ it "creates an active user with a confirmed email and no password" do
+ user = result[:user]
+
+ expect(user).to be_active
+ expect(user.email).to eq(email)
+ expect(user).to be_email_confirmed
+ expect(user.password_hash).to be_nil
+ expect(user.registration_ip_address.to_s).to eq("127.0.0.1")
+ end
+
+ it "does not derive the username from the email by default" do
+ expect(result[:user].username).not_to include("jane")
+ end
+
+ it "derives the username from the email when email-based suggestions are enabled" do
+ SiteSetting.use_email_for_username_and_name_suggestions = true
+
+ expect(result[:user].username).to eq("jane")
+ end
+
+ it "enqueues the welcome message" do
+ expect { result }.to change {
+ Jobs::SendSystemMessage.jobs.count do |job|
+ job["args"][0]["message_type"] == "welcome_user"
+ end
+ }.by(1)
+ end
+ end
+
+ context "when required signup fields exist" do
+ fab!(:user_field)
+
+ it { is_expected.to fail_a_policy(:required_fields_provided) }
it "does not consume the code" do
- expect { result }.not_to change { login_code.reload.consumed_at }
+ result
+
+ expect(login_code.reload.consumed_at).to be_nil
+ end
+
+ context "when the field values are provided" do
+ let(:params) { { email:, code:, user_fields: { user_field.id.to_s => "Dev" } } }
+
+ it { is_expected.to run_successfully }
+
+ it "saves the field value on the new user" do
+ expect(result[:user].custom_fields["user_field_#{user_field.id}"]).to eq("Dev")
+ end
+
+ context "when a field is not shown on signup" do
+ fab!(:hidden_field) do
+ Fabricate(:user_field, requirement: "optional", show_on_signup: false)
+ end
+
+ let(:params) do
+ {
+ email:,
+ code:,
+ user_fields: {
+ user_field.id.to_s => "Dev",
+ hidden_field.id.to_s => "Secret",
+ },
+ }
+ end
+
+ it "ignores values for fields that aren't shown on signup" do
+ user = result[:user]
+
+ expect(user.custom_fields["user_field_#{user_field.id}"]).to eq("Dev")
+ expect(user.custom_fields["user_field_#{hidden_field.id}"]).to be_nil
+ end
+ end
+ end
+
+ context "when a required field is hidden from signup" do
+ fab!(:hidden_required_field) do
+ Fabricate(:user_field, requirement: "for_all_users", show_on_signup: false)
+ end
+
+ let(:params) { { email:, code:, user_fields: { user_field.id.to_s => "Dev" } } }
+
+ it "does not require fields the signup form can't collect" do
+ expect(result).to run_successfully
+ end
+ end
+
+ context "when user_fields is malformed" do
+ let(:params) { { email:, code:, user_fields: "not-a-hash" } }
+
+ it "fails as a missing field instead of raising" do
+ expect { result }.not_to raise_error
+ expect(result).to fail_a_policy(:required_fields_provided)
+ end
+ end
+
+ context "when the email belongs to an existing user" do
+ fab!(:user)
+
+ let(:email) { user.email }
+
+ it { is_expected.to run_successfully }
end
end
- context "when the email belongs to an existing active user" do
+ context "when the email belongs to a staged user" do
+ fab!(:staged_user) { Fabricate(:staged, active: false) }
+
+ let(:email) { staged_user.email }
+
it { is_expected.to run_successfully }
- it "returns the user and consumes the code" do
- expect(result[:user]).to eq(user)
+ it "unstages and activates the existing user" do
+ user = result[:user]
+
+ expect(user.id).to eq(staged_user.id)
+ expect(user).not_to be_staged
+ expect(user).to be_active
expect(login_code.reload.consumed_at).to be_present
end
end
context "when the email belongs to an existing inactive user" do
- fab!(:user) { Fabricate(:user, active: false) }
+ fab!(:inactive_user) { Fabricate(:user, active: false) }
+
+ let(:email) { inactive_user.email }
it { is_expected.to run_successfully }
it "activates the user and consumes the code" do
- expect(result[:user].id).to eq(user.id)
+ user = result[:user]
+
+ expect(user.id).to eq(inactive_user.id)
expect(user.reload).to be_active
expect(login_code.reload.consumed_at).to be_present
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 }
+
+ it "returns the user and consumes the code" do
+ expect(result[:user]).to eq(user)
+ expect(login_code.reload.consumed_at).to be_present
+ end
+
+ it "does not enqueue another welcome message" do
+ expect { result }.not_to change { Jobs::SendSystemMessage.jobs.size }
+ end
+
+ it "succeeds even when registrations are disabled" do
+ SiteSetting.allow_new_registrations = false
+
+ expect(result).to run_successfully
+ end
+ end
+
+ context "when users must be approved" do
+ before do
+ SiteSetting.must_approve_users = true
+ Jobs.run_immediately!
+ end
+
+ it { is_expected.to run_successfully }
+
+ it "creates an unapproved user with a pending reviewable" do
+ user = result[:user]
+
+ expect(user).not_to be_approved
+ expect(ReviewableUser.pending.find_by(target: user)).to be_present
+ end
+
+ context "when the email domain is auto-approved" do
+ before { SiteSetting.auto_approve_email_domains = "example.com" }
+
+ it "creates an approved user" do
+ expect(result[:user]).to be_approved
+ end
+ end
+ end
+
+ context "when the new account is awaiting approval" do
+ before { SiteSetting.must_approve_users = true }
+
+ it "does not enqueue the welcome message until it can access the forum" do
+ expect { result }.not_to change {
+ Jobs::SendSystemMessage.jobs.count do |job|
+ job["args"][0]["message_type"] == "welcome_user"
+ end
+ }
+ end
+ end
end
end
diff --git a/spec/services/email_login_code/request_spec.rb b/spec/services/email_login_code/request_spec.rb
index e1df2adbc47..3f8b83811f7 100644
--- a/spec/services/email_login_code/request_spec.rb
+++ b/spec/services/email_login_code/request_spec.rb
@@ -65,15 +65,15 @@ RSpec.describe EmailLoginCode::Request do
end
end
- context "when the email does not belong to a user" do
- let(:email) { "[email protected]" }
+ context "when the email is unknown and signups are open" do
+ let(:email) { "[email protected]" }
it { is_expected.to run_successfully }
- it "does not generate a code or enqueue an email" do
- expect_not_enqueued_with(job: :send_email_login_code) { result }
+ it "generates a login code and enqueues the email" do
+ expect_enqueued_with(job: :send_email_login_code, args: { to_address: email }) { result }
- expect(EmailLoginCode.count).to eq(0)
+ expect(EmailLoginCode.for_email(email).count).to eq(1)
end
it "does not trigger the :before_email_login event" do
@@ -90,7 +90,79 @@ RSpec.describe EmailLoginCode::Request do
it { is_expected.to run_successfully }
- it "does not generate a code, since staged users cannot log in" do
+ it "treats it as a new registration, not an existing account" do
+ events = DiscourseEvent.track_events(:before_email_login) { result }
+
+ expect(events).to be_empty
+ expect(EmailLoginCode.for_email(email).count).to eq(1)
+ end
+
+ it "does not generate a code when registrations are closed" do
+ SiteSetting.allow_new_registrations = false
+
+ expect { result }.not_to change(EmailLoginCode, :count)
+ expect(result).to run_successfully
+ end
+ end
+
+ context "when the email is unknown and registrations are disabled" do
+ let(:email) { "[email protected]" }
+
+ before { SiteSetting.allow_new_registrations = false }
+
+ it { is_expected.to run_successfully }
+
+ it "does not generate a code or enqueue an email" do
+ expect_not_enqueued_with(job: :send_email_login_code) { result }
+
+ expect(EmailLoginCode.count).to eq(0)
+ end
+ end
+
+ context "when the email is unknown and the site is invite only" do
+ let(:email) { "[email protected]" }
+
+ before { SiteSetting.invite_only = true }
+
+ it { is_expected.to run_successfully }
+
+ it "does not generate a code" do
+ expect { result }.not_to change(EmailLoginCode, :count)
+ end
+ end
+
+ context "when the email is unknown and an invite code is required" do
+ let(:email) { "[email protected]" }
+
+ before { SiteSetting.invite_code = "SECRET" }
+
+ it { is_expected.to run_successfully }
+
+ it "does not generate a code" do
+ expect { result }.not_to change(EmailLoginCode, :count)
+ end
+ end
+
+ context "when the email domain is blocked" do
+ let(:email) { "[email protected]" }
+
+ before { SiteSetting.blocked_email_domains = "blocked.com" }
+
+ it { is_expected.to run_successfully }
+
+ it "does not generate a code" do
+ expect { result }.not_to change(EmailLoginCode, :count)
+ end
+ end
+
+ context "when the email is screened" do
+ let(:email) { "[email protected]" }
+
+ before { Fabricate(:screened_email, email:) }
+
+ it { is_expected.to run_successfully }
+
+ it "does not generate a code" do
expect { result }.not_to change(EmailLoginCode, :count)
end
end
diff --git a/spec/system/code_signup_spec.rb b/spec/system/code_signup_spec.rb
new file mode 100644
index 00000000000..5e07eb04e95
--- /dev/null
+++ b/spec/system/code_signup_spec.rb
@@ -0,0 +1,182 @@
+# frozen_string_literal: true
+
+describe "Sign up via email code" do
+ include ThemeScreenshotMarker
+
+ before do
+ SiteSetting.enable_local_logins_via_email = true
+ SiteSetting.enable_local_logins_via_code = true
+ Jobs.run_immediately!
+ end
+
+ def fill_code(code)
+ find(".d-otp-input").fill_in(with: code)
+ end
+
+ def latest_emailed_code(email)
+ wait_for(timeout: 10) { ActionMailer::Base.deliveries.count != 0 }
+ mail = ActionMailer::Base.deliveries.last
+ expect(mail.to).to contain_exactly(email)
+ mail.subject[/(\d{6})/, 1]
+ end
+
+ def submit_email(email)
+ find(".code-login-form__email-step input[type='email']").fill_in(with: email)
+ find(".code-login-form__continue").click
+ expect(page).to have_css(".code-login-form__code-step")
+ end
+
+ def pick_username(name)
+ fill_in("code-login-username", with: name)
+ expect(page).to have_no_css(".code-login-form__continue-to-site[disabled]")
+ end
+
+ it "creates a passwordless account, picks a username, and logs in" do
+ visit("/signup")
+ expect(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")
+
+ submit_email("[email protected]")
+ screenshot_marker(label: "code-signup-code-step")
+
+ fill_code(latest_emailed_code("[email protected]"))
+
+ expect(page).to have_css(".code-login-form__complete-step")
+ screenshot_marker(label: "code-signup-complete-step")
+
+ # A username must be picked before the account can be used.
+ expect(page).to have_css(".code-login-form__continue-to-site[disabled]")
+ pick_username("new-person")
+
+ find(".code-login-form__continue-to-site").click
+
+ expect(page).to have_css(".header-dropdown-toggle.current-user")
+
+ user = User.find_by_email("[email protected]")
+ expect(user).to be_active
+ expect(user.username).to eq("new-person")
+ expect(user.user_password).to be_nil
+ end
+
+ it "blocks continuing while the picked username is taken" do
+ Fabricate(:user, username: "takenname")
+
+ visit("/signup")
+ submit_email("[email protected]")
+ fill_code(latest_emailed_code("[email protected]"))
+
+ expect(page).to have_css(".code-login-form__complete-step")
+
+ fill_in("code-login-username", with: "takenname")
+ expect(page).to have_css(".code-login-form__error", text: "username")
+ expect(page).to have_css(".code-login-form__continue-to-site[disabled]")
+ end
+
+ it "prefills the username when email-based suggestions are enabled" do
+ SiteSetting.use_email_for_username_and_name_suggestions = true
+
+ visit("/signup")
+ submit_email("[email protected]")
+ fill_code(latest_emailed_code("[email protected]"))
+
+ expect(page).to have_css(".code-login-form__complete-step")
+ expect(find("#code-login-username").value).to eq("jane")
+ end
+
+ it "keeps the generated username when usernames can't be changed" do
+ SiteSetting.username_change_period = 0
+
+ visit("/signup")
+ submit_email("[email protected]")
+ fill_code(latest_emailed_code("[email protected]"))
+
+ expect(page).to have_css(".code-login-form__complete-step")
+ expect(page).to have_no_css("#code-login-username")
+
+ find(".code-login-form__continue-to-site").click
+ expect(page).to have_css(".header-dropdown-toggle.current-user")
+ expect(User.find_by_email("[email protected]")).to be_present
+ end
+
+ it "opens the avatar picker before continuing" do
+ visit("/signup")
+ submit_email("[email protected]")
+ fill_code(latest_emailed_code("[email protected]"))
+
+ expect(page).to have_css(".code-login-form__complete-step")
+ find(".code-login-form__avatar").click
+
+ expect(page).to have_css(".avatar-selector-modal")
+ end
+
+ it "shows an error for an incorrect code" do
+ visit("/signup")
+ submit_email("[email protected]")
+
+ correct_code = latest_emailed_code("[email protected]")
+ fill_code(correct_code == "000000" ? "000001" : "000000")
+
+ expect(page).to have_css(
+ ".code-login-form__error",
+ text: I18n.t("email_login_code.invalid_code"),
+ )
+ expect(page).to have_no_css(".header-dropdown-toggle.current-user")
+ expect(User.find_by_email("[email protected]")).to be_nil
+ end
+
+ it "does not create an account when registrations are disabled" do
+ SiteSetting.allow_new_registrations = false
+
+ visit("/signup")
+ submit_email("[email protected]")
+
+ # No code is sent when registrations are closed, so any code is rejected.
+ fill_code("000000")
+
+ expect(page).to have_css(".code-login-form__error")
+ expect(page).to have_no_css(".header-dropdown-toggle.current-user")
+ expect(User.find_by_email("[email protected]")).to be_nil
+ end
+
+ it "shows a pending-approval message when users must be approved" do
+ SiteSetting.must_approve_users = true
+
+ visit("/signup")
+ submit_email("[email protected]")
+ fill_code(latest_emailed_code("[email protected]"))
+
+ expect(page).to have_css(".code-login-form__error", text: I18n.t("login.not_approved"))
+ expect(page).to have_no_css(".header-dropdown-toggle.current-user")
+
+ user = User.find_by_email("[email protected]")
+ expect(user).not_to be_approved
+ expect(ReviewableUser.pending.find_by(target: user)).to be_present
+ end
+
+ context "with required user fields" do
+ fab!(:user_field) { Fabricate(:user_field, name: "Occupation") }
+
+ it "collects the fields 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")
+ screenshot_marker(label: "code-signup-user-fields-step")
+
+ find(".user-field-occupation input").fill_in(with: "Dev")
+ find(".code-login-form__user-fields-step .code-login-form__verify").click
+
+ expect(page).to have_css(".code-login-form__complete-step")
+ pick_username("fields-person")
+ find(".code-login-form__continue-to-site").click
+
+ expect(page).to have_css(".header-dropdown-toggle.current-user")
+
+ user = User.find_by_email("[email protected]")
+ expect(user.username).to eq("fields-person")
+ expect(user.custom_fields["user_field_#{user_field.id}"]).to eq("Dev")
+ end
+ end
+end