Skip to content

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

FEATURE: Use email code for invites (#43138)

Penar Musarajaa6cb6375880
diff --git a/app/assets/stylesheets/common/login/invite-signup.scss b/app/assets/stylesheets/common/login/invite-signup.scss
index 87378ada6e5..58954cc75e5 100644
--- a/app/assets/stylesheets/common/login/invite-signup.scss
+++ b/app/assets/stylesheets/common/login/invite-signup.scss
@@ -31,7 +31,7 @@
margin: 0;
}
- .avatar {
+ .invited-by .avatar {
width: 30px;
height: 30px;
}
diff --git a/app/controllers/invites_controller.rb b/app/controllers/invites_controller.rb
index 4fcded5827a..0fb19dcb52c 100644
--- a/app/controllers/invites_controller.rb
+++ b/app/controllers/invites_controller.rb
@@ -367,6 +367,11 @@ class InvitesController < ApplicationController
# via the SSO flow (SessionController#sso_login)
raise Discourse::NotFound if SiteSetting.enable_discourse_connect
+ if Invite.email_code_enabled?(current_user) && current_user.nil? &&
+ server_session[:authentication].blank?
+ raise Discourse::NotFound
+ end
+
params.require(:id)
params.permit(
:email,
@@ -601,7 +606,9 @@ class InvitesController < ApplicationController
end
end
- email_verified_by_link = invite.email_token.present? && params[:t] == invite.email_token
+ email_verified_by_link =
+ !Invite.email_code_enabled?(current_user) && invite.email_token.present? &&
+ params[:t] == invite.email_token
email = invite.email if email_verified_by_link
diff --git a/app/controllers/session_controller.rb b/app/controllers/session_controller.rb
index 1dda8c28d6c..5d357ca22f2 100644
--- a/app/controllers/session_controller.rb
+++ b/app/controllers/session_controller.rb
@@ -502,6 +502,8 @@ class SessionController < ApplicationController
# the behavior for emails we refuse to deliver to.
return render json: success_json if login_code_honeypot_fails?
+ return request_invite_login_code if params[:invite_key].present?
+
EmailLoginCode::Request.call(
service_params.deep_merge(ip_address: request.remote_ip),
) do |result|
@@ -518,7 +520,7 @@ class SessionController < ApplicationController
def verify_login_code
expires_now
- EmailLoginCode::Verify.call(service_params) do |result|
+ EmailLoginCode::Verify.call(login_code_verification_params) do |result|
on_success { |user:| process_verified_login_code(user) }
on_failed_contract do |contract|
render json: failed_json.merge(errors: contract.errors.full_messages), status: :bad_request
@@ -870,7 +872,8 @@ class SessionController < ApplicationController
RateLimiter.new(nil, "login-code-hour-#{request.remote_ip}", 6, 1.hour).performed!
RateLimiter.new(nil, "login-code-min-#{request.remote_ip}", 3, 1.minute).performed!
- email = params[:email].to_s.strip.downcase
+ invite = Invite.find_by(invite_key: params[:invite_key]) if params[:invite_key].present?
+ email = (invite&.email.presence || params[:email]).to_s.strip.downcase
if email.present?
RateLimiter.new(
nil,
@@ -905,6 +908,8 @@ class SessionController < ApplicationController
end
end
+ return process_verified_invite_login_code(matched_user) if params[:invite_key].present?
+
if matched_user.nil? && registration_via_login_code_open?
user_fields_required = signup_user_fields_missing?
name_required = signup_full_name_missing?
@@ -976,7 +981,7 @@ class SessionController < ApplicationController
params[:second_factor_token].blank?
end
- def login_with_login_code(user, created_account: false)
+ def login_with_login_code(user, created_account: false, redirect_url: nil)
raise Discourse::ReadOnly if @staff_writes_only_mode && !user.staff?
if login_not_approved_for?(user)
@@ -1009,12 +1014,91 @@ class SessionController < ApplicationController
# the avatar picker needs the upload permission passed through.
can_upload_avatar:
user.in_any_groups?(SiteSetting.uploaded_avatars_allowed_groups_map),
- # Only set when a DiscourseConnect provider handoff is pending.
- redirect_url: deferred_sso_provider_url,
+ # A pending provider handoff takes precedence, since an external
+ # site is waiting on the answer. Reading it unconditionally also
+ # consumes the cookie, so a caller-supplied redirect can't leave
+ # a signed payload behind to be replayed on a later login.
+ redirect_url: deferred_sso_provider_url || redirect_url,
)
else
- login(user)
+ login(user, redirect_url:)
+ end
+ end
+
+ def request_invite_login_code
+ Invite::RequestEmailCode.call(
+ service_params.deep_merge(ip_address: request.remote_ip),
+ ) do |result|
+ on_success { render json: success_json }
+ on_failed_policy(:can_register_from_ip) do
+ render json: login_code_registration_ip_limit_error
+ end
+ on_failed_contract do |contract|
+ render json: failed_json.merge(errors: contract.errors.full_messages), status: :bad_request
+ end
+ on_failure { render json: success_json }
+ end
+ end
+
+ def login_code_verification_params
+ invite = Invite.find_by(invite_key: params[:invite_key]) if params[:invite_key].present?
+ email = invite&.email.presence || params[:email]
+
+ service_params.deep_merge(params: params.to_unsafe_h.merge(email:))
+ end
+
+ def process_verified_invite_login_code(matched_user)
+ if matched_user
+ return render json: login_not_approved if login_not_approved_for?(matched_user)
+ return render json: login_error if (login_error = login_error_check(matched_user))
+ end
+
+ if matched_user.nil? && (signup_user_fields_missing? || signup_full_name_missing?)
+ return(
+ render json: {
+ user_fields_required: signup_user_fields_missing?,
+ name_required: signup_full_name_missing?,
+ }
+ )
end
+
+ Invite::RedeemWithEmailCode.call(
+ login_code_verification_params.deep_merge(ip_address: request.remote_ip),
+ ) do |result|
+ on_success do |invite:, user:, existing_user:|
+ login_with_login_code(
+ user,
+ created_account: existing_user.nil?,
+ redirect_url: invite_login_code_redirect(invite, user),
+ )
+ 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_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_account_error(user) }
+ on_model_not_found(:user) do |model_result|
+ if model_result.exception.is_a?(Invite::UserExists)
+ render json: { error: model_result.exception.message }
+ else
+ render json: invalid_login_code
+ end
+ end
+ on_failed_contract do |contract|
+ render json: failed_json.merge(errors: contract.errors.full_messages), status: :bad_request
+ end
+ on_failure { render json: invalid_login_code }
+ end
+ end
+
+ def invite_login_code_redirect(invite, user)
+ topic = invite.topics.first
+ topic && user.guardian.can_see?(topic) ? path(topic.relative_url) : path("/")
end
# A pending provider handoff would redirect as soon as the session exists,
@@ -1083,7 +1167,7 @@ class SessionController < ApplicationController
{ error: user.suspended_message, reason: "suspended" }
end
- def login(user, passkey_login: false, second_factor_auth_result: nil)
+ def login(user, passkey_login: false, second_factor_auth_result: nil, redirect_url: nil)
session.delete(ACTIVATE_USER_KEY)
user.update_timezone_if_missing(params[:timezone])
log_on_user(user, replay_anonymous_action: true)
@@ -1096,6 +1180,8 @@ class SessionController < ApplicationController
second_factor_auth_result.used_2fa_method != UserSecondFactor.methods[:backup_codes]
)
sso_provider(payload, confirmed_2fa_during_login)
+ elsif redirect_url
+ render json: success_json.merge(redirect_url:)
else
render_serialized(user, UserSerializer)
end
diff --git a/app/mailers/invite_mailer.rb b/app/mailers/invite_mailer.rb
index 85e98df4730..73b247ff11a 100644
--- a/app/mailers/invite_mailer.rb
+++ b/app/mailers/invite_mailer.rb
@@ -41,7 +41,7 @@ class InviteMailer < ActionMailer::Base
template: sanitized_message ? "custom_invite_mailer" : "invite_mailer",
inviter_name: inviter_name,
site_domain_name: Discourse.current_hostname,
- invite_link: invite.link(with_email_token: true),
+ invite_link: invite.link(with_email_token: !Invite.email_code_enabled?),
topic_title: topic_title,
topic_excerpt: topic_excerpt,
site_description: SiteSetting.site_description,
@@ -60,7 +60,7 @@ class InviteMailer < ActionMailer::Base
template: sanitized_message ? "custom_invite_forum_mailer" : template,
inviter_name: inviter_name,
site_domain_name: Discourse.current_hostname,
- invite_link: invite.link(with_email_token: true),
+ invite_link: invite.link(with_email_token: !Invite.email_code_enabled?),
site_description: SiteSetting.site_description,
site_title: SiteSetting.title,
user_custom_message: sanitized_message,
diff --git a/app/models/invite.rb b/app/models/invite.rb
index cb44c82194c..c46b1bc0b0d 100644
--- a/app/models/invite.rb
+++ b/app/models/invite.rb
@@ -55,6 +55,12 @@ class Invite < ActiveRecord::Base
attribute :email_already_exists
+ def self.email_code_enabled?(user = nil)
+ UpcomingChanges.enabled_for_user?(:enable_local_logins_via_code, user) &&
+ SiteSetting.enable_local_logins && SiteSetting.enable_local_logins_via_email &&
+ !SiteSetting.enable_discourse_connect
+ end
+
def self.emailed_status_types
@emailed_status_types ||=
Enum.new(not_required: 0, pending: 1, bulk_pending: 2, sending: 3, sent: 4)
@@ -237,6 +243,7 @@ class Invite < ActiveRecord::Base
ip_address: nil,
session: nil,
email_token: nil,
+ email_verified: false,
redeeming_user: nil
)
return if !redeemable?
@@ -251,6 +258,7 @@ class Invite < ActiveRecord::Base
ip_address: ip_address,
session: session,
email_token: email_token,
+ email_verified: email_verified,
redeeming_user: redeeming_user,
).redeem
end
diff --git a/app/models/invite_redeemer.rb b/app/models/invite_redeemer.rb
index 7e8581d2192..80c583f6711 100644
--- a/app/models/invite_redeemer.rb
+++ b/app/models/invite_redeemer.rb
@@ -23,6 +23,7 @@ class InviteRedeemer
:ip_address,
:session,
:email_token,
+ :email_verified,
:redeeming_user
def initialize(
@@ -35,6 +36,7 @@ class InviteRedeemer
ip_address: nil,
session: nil,
email_token: nil,
+ email_verified: false,
redeeming_user: nil
)
@invite = invite
@@ -45,6 +47,7 @@ class InviteRedeemer
@ip_address = ip_address
@session = session
@email_token = email_token
+ @email_verified = email_verified
@redeeming_user = redeeming_user
ensure_email_is_present!(email)
@@ -71,7 +74,7 @@ class InviteRedeemer
if email.blank? && @invite.is_email_invite?
@email = @invite.email
- elsif @redeeming_user.present?
+ elsif @redeeming_user.present? && !email_verified
@email = @redeeming_user.email
else
@email = email
@@ -91,11 +94,16 @@ class InviteRedeemer
user_custom_fields: nil,
ip_address: nil,
session: nil,
- email_token: nil
+ email_token: nil,
+ email_verified: false
)
if username && UsernameValidator.new(username).valid_format? &&
User.username_available?(username, email)
available_username = username
+ elsif email_verified
+ available_username =
+ UserNameSuggester.suggest(email, allow_generic_fallback: false) ||
+ RandomUsernameGenerator.generate || UserNameSuggester.suggest(email)
else
available_username = UserNameSuggester.suggest(email)
end
@@ -107,7 +115,7 @@ class InviteRedeemer
user.attributes = {
email: email,
username: available_username,
- name: name || available_username,
+ name: name.presence || (email_verified ? user.name : available_username),
active: false,
trust_level: SiteSetting.default_invitee_trust_level,
ip_address: ip_address,
@@ -159,8 +167,12 @@ class InviteRedeemer
user.save!
authenticator.finish
- if invite.emailed_status != Invite.emailed_status_types[:not_required] &&
- email == invite.email && invite.email_token.present? && email_token == invite.email_token
+ if email_verified ||
+ (
+ invite.emailed_status != Invite.emailed_status_types[:not_required] &&
+ email == invite.email && invite.email_token.present? &&
+ email_token == invite.email_token
+ )
user.activate
end
@@ -186,7 +198,7 @@ class InviteRedeemer
# prefill the email and do not let the user modify it.
#
# Note that an invite link can also have a domain scope which must be checked.
- email_to_check = redeeming_user&.email || email
+ email_to_check = email_verified ? email : (redeeming_user&.email || email)
if invite.email.present? && !invite.email_matches?(email_to_check)
raise ActiveRecord::RecordNotSaved.new(I18n.t("invite.not_matching_email"))
@@ -235,6 +247,7 @@ class InviteRedeemer
ip_address: ip_address,
session: session,
email_token: email_token,
+ email_verified: email_verified,
)
invited_user.send_welcome_message = false
@invited_user = invited_user
diff --git a/app/services/invite/redeem_with_email_code.rb b/app/services/invite/redeem_with_email_code.rb
new file mode 100644
index 00000000000..64dc366b763
--- /dev/null
+++ b/app/services/invite/redeem_with_email_code.rb
@@ -0,0 +1,177 @@
+# frozen_string_literal: true
+
+class Invite::RedeemWithEmailCode
+ include Service::Base
+
+ params base_class: EmailLoginCode::Verify::Contract do
+ attribute :invite_key, :string
+ attribute :user_fields
+ attribute :name, :string
+
+ before_validation do
+ self.invite_key = invite_key.to_s.strip
+ self.user_fields =
+ if user_fields.is_a?(Hash) || user_fields.is_a?(ActionController::Parameters)
+ user_fields.to_h.stringify_keys
+ else
+ {}
+ end
+ self.name = name.to_s.strip.presence
+ end
+
+ validates :invite_key, presence: true
+ validates :name, length: { maximum: 255 }
+ end
+
+ model :invite
+ policy :email_can_redeem_invite
+ model :login_code
+ policy :code_matches
+ model :existing_user, optional: true
+ policy :email_available_for_new_account
+ policy :can_register_new_account
+ policy :required_fields_provided
+ policy :required_full_name_provided
+
+ try(
+ ActiveRecord::RecordInvalid,
+ ActiveRecord::RecordNotSaved,
+ ActiveRecord::LockWaitTimeout,
+ Invite::UserExists,
+ ) do
+ lock(:email) do
+ transaction do
+ step :consume_code
+ model :user, :redeem_invite
+ end
+ end
+ end
+
+ only_if(:user_requires_activation?) { step :activate_user }
+ only_if(:welcome_message_pending?) { step :send_welcome_message }
+ only_if(:staff_user?) { step :refresh_automatic_groups }
+ step :create_topic_notifications
+
+ private
+
+ def fetch_invite(params:)
+ invite = Invite.find_by(invite_key: params.invite_key)
+ invite if invite&.redeemable?
+ end
+
+ def email_can_redeem_invite(invite:, params:)
+ return if invite.email.present? && !invite.email_matches?(params.email)
+ return if invite.domain.present? && !invite.domain_matches?(params.email)
+
+ true
+ end
+
+ def fetch_login_code(params:)
+ EmailLoginCode.active.for_email(params.email).first
+ end
+
+ def code_matches(login_code:, params:)
+ login_code.verify(params.code)
+ end
+
+ def fetch_existing_user(params:)
+ User.real.where(staged: false).with_email(params.email).first
+ end
+
+ 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?
+
+ SiteSetting.allow_new_registrations && EmailValidator.allowed?(params.email) &&
+ !ScreenedEmail.should_block?(params.email)
+ end
+
+ def required_fields_provided(existing_user:, params:)
+ return true if existing_user.present?
+
+ UserField
+ .required
+ .where(show_on_signup: true)
+ .pluck(:id)
+ .all? do |field_id|
+ value = params.user_fields[field_id.to_s]
+ value.present? && value != "false"
+ end
+ end
+
+ 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:)
+ fail!("code already redeemed") unless login_code.consume!
+ end
+
+ def redeem_invite(existing_user:, invite:, params:, ip_address:)
+ attributes =
+ if existing_user
+ { redeeming_user: existing_user, email: params.email, email_verified: true }
+ else
+ {
+ email: params.email,
+ name: params.name,
+ user_custom_fields: params.user_fields,
+ ip_address: ip_address,
+ email_verified: true,
+ }
+ end
+
+ invite.redeem(**attributes)
+ end
+
+ def user_requires_activation?(user:)
+ !user.active?
+ end
+
+ def activate_user(user:)
+ user.activate
+ end
+
+ def welcome_message_pending?(user:)
+ user.send_welcome_message
+ end
+
+ def send_welcome_message(user:)
+ user.enqueue_welcome_message("welcome_invite")
+ end
+
+ def staff_user?(user:)
+ user.staff?
+ end
+
+ def refresh_automatic_groups
+ Group.refresh_automatic_groups!(:admins, :moderators, :staff)
+ end
+
+ def create_topic_notifications(invite:, user:)
+ invite.topics.each do |topic|
+ next if !user.guardian.can_see?(topic)
+
+ recent_notification =
+ user
+ .notifications
+ .where(notification_type: Notification.types[:invited_to_topic])
+ .where(topic_id: topic.id, post_number: 1)
+ .where("created_at > ?", 1.hour.ago)
+ next if recent_notification.exists?
+
+ topic.create_invite_notification!(
+ user,
+ Notification.types[:invited_to_topic],
+ invite.invited_by,
+ )
+ end
+ end
+end
diff --git a/app/services/invite/request_email_code.rb b/app/services/invite/request_email_code.rb
new file mode 100644
index 00000000000..cd777ef11d4
--- /dev/null
+++ b/app/services/invite/request_email_code.rb
@@ -0,0 +1,72 @@
+# frozen_string_literal: true
+
+class Invite::RequestEmailCode
+ include Service::Base
+
+ params do
+ attribute :invite_key, :string
+ attribute :email, :string
+
+ before_validation do
+ self.invite_key = invite_key.to_s.strip
+ self.email = email.to_s.strip.downcase
+ end
+
+ validates :invite_key, presence: true
+
+ def email_for(invite)
+ invite.email.presence || email
+ end
+ end
+
+ model :invite
+ policy :email_can_redeem_invite
+ policy :can_register_from_ip
+ only_if(:existing_account?) { step :trigger_before_email_login }
+ model :login_code, :generate_login_code
+ step :send_login_code_email
+
+ private
+
+ def fetch_invite(params:)
+ invite = Invite.find_by(invite_key: params.invite_key)
+ invite if invite&.redeemable?
+ end
+
+ def email_can_redeem_invite(invite:, params:)
+ email = params.email_for(invite)
+ return if !EmailAddressValidator.valid_value?(email)
+ return if invite.email.present? && !invite.email_matches?(email)
+ return if invite.domain.present? && !invite.domain_matches?(email)
+ return true if User.real.where(staged: false).with_email(email).exists?
+ return if User::Action::FindByEmail.call(email: email).present?
+ return if !EmailValidator.allowed?(email)
+ return if ScreenedEmail.should_block?(email)
+
+ true
+ end
+
+ def can_register_from_ip(invite:, params:, ip_address:)
+ email = params.email_for(invite)
+ return true if User.real.where(staged: false).with_email(email).exists?
+
+ !SpamHandler.should_prevent_registration_from_ip?(ip_address)
+ end
+
+ def existing_account?(invite:, params:)
+ User.real.where(staged: false).with_email(params.email_for(invite)).exists?
+ end
+
+ def trigger_before_email_login(invite:, params:)
+ user = User.real.where(staged: false).with_email(params.email_for(invite)).first
+ DiscourseEvent.trigger(:before_email_login, user)
+ end
+
+ def generate_login_code(invite:, params:)
+ EmailLoginCode.generate!(email: params.email_for(invite))
+ end
+
+ def send_login_code_email(login_code:)
+ Jobs.enqueue(:send_email_login_code, to_address: login_code.email, code: login_code.code)
+ end
+end
diff --git a/config/locales/client.en.yml b/config/locales/client.en.yml
index 9464ebc7094..ffbcfb282d7 100644
--- a/config/locales/client.en.yml
+++ b/config/locales/client.en.yml
@@ -3261,6 +3261,8 @@ en:
social_login_available: "You'll also be able to sign in with any social login using that email."
your_email: "Your account email address is <b>%{email}</b>."
accept_invite: "Accept Invitation"
+ send_code: "Send code"
+ code_instructions: "We'll send a one-time code to %{email} to confirm your email address."
success: "Your account has been created and you're now logged in."
name_label: "Name"
password_label: "Password"
diff --git a/config/locales/server.en.yml b/config/locales/server.en.yml
index e3e9058ff96..9657b638399 100644
--- a/config/locales/server.en.yml
+++ b/config/locales/server.en.yml
@@ -2291,7 +2291,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: "Allow members to sign up and log in faster using one-time email codes (OTPs)."
+ enable_local_logins_via_code: "Allow members to sign up, accept invitations, and log in with one-time email codes (OTPs), without requiring a password."
enable_random_usernames: 'Generates random usernames for accounts created with a one-time email code using the format "adjective + noun + two random numbers" (example: QuietFalcon34). New members can change their username during the signup process.'
random_username_adjectives: 'Words used as the first half of a randomly generated username. The leading letter is capitalized when the words are combined.'
random_username_nouns: 'Words used as the second half of a randomly generated username. The leading letter is capitalized when the words are combined.'
diff --git a/frontend/discourse/app/components/code-login-form.gjs b/frontend/discourse/app/components/code-login-form.gjs
index 23b57cf7e68..138bce842cf 100644
--- a/frontend/discourse/app/components/code-login-form.gjs
+++ b/frontend/discourse/app/components/code-login-form.gjs
@@ -100,6 +100,14 @@ export default class CodeLoginForm extends Component {
return this.args.context === "signup";
}
+ get isInvite() {
+ return this.args.context === "invite";
+ }
+
+ get isInviteEmailLocked() {
+ return this.isInvite && this.args.emailLocked;
+ }
+
get isEmailStep() {
return this.step === "email";
}
@@ -212,6 +220,17 @@ export default class CodeLoginForm extends Component {
await this.sendCode();
}
+ @action
+ async requestCode() {
+ if (this.verifying) {
+ return;
+ }
+
+ this.verifying = true;
+ await this.sendCode();
+ this.verifying = false;
+ }
+
@action
async resendCode() {
if (this.resendDisabled) {
@@ -262,6 +281,10 @@ export default class CodeLoginForm extends Component {
timezone: moment.tz.guess(),
};
+ if (this.isInvite) {
+ data.invite_key = this.args.inviteKey;
+ }
+
if (this.isSecondFactorStep) {
data.second_factor_token =
this.securityKeyCredential || this.secondFactorToken;
@@ -573,6 +596,7 @@ export default class CodeLoginForm extends Component {
data: {
email: this.email,
signup: this.isSignup,
+ invite_key: this.isInvite ? this.args.inviteKey : undefined,
password_confirmation: honeypot.value,
challenge: honeypot.challenge.split("").reverse().join(""),
},
@@ -700,59 +724,82 @@ export default class CodeLoginForm extends Component {
{{/unless}}
{{#if this.isEmailStep}}
- {{#if this.isSignup}}
- <p class="code-login-form__instructions">
- {{i18n "code_login.signup_instructions"}}
- </p>
- {{/if}}
-
- <Form
- class="code-login-form__email-step"
- @data={{hash email=this.email}}
- @onSubmit={{this.submitEmail}}
- as |form|
- >
- <form.Field
- @format="full"
- @name="email"
- @title={{i18n "code_login.email_label"}}
- @type="input-email"
- @validate={{this.validateEmail}}
- @validation="required"
- as |field|
- >
- <field.Control autocomplete="username" autofocus="autofocus" />
- </form.Field>
-
- {{! Lets a signup flow add its own fields to this form — an agreement
- it needs accepted before the account exists, say — so they are
- validated and submitted together with the email. }}
- <PluginOutlet
- @name="code-login-email-step-fields"
- @outletArgs={{lazyHash form=form context=@context}}
- />
-
- {{#if this.codeError}}
- <div aria-live="polite" class="code-login-form__error" role="alert">
- {{this.codeError}}
- </div>
+ {{#if this.isInviteEmailLocked}}
+ <div class="code-login-form__email-step">
+ <p class="code-login-form__instructions">
+ {{i18n "invites.code_instructions" email=this.email}}
+ </p>
+ <DButton
+ class="btn-primary code-login-form__continue"
+ @action={{this.requestCode}}
+ @isLoading={{this.verifying}}
+ @label="invites.send_code"
+ />
+ {{#if this.codeError}}
+ <div class="code-login-form__error" role="alert">
+ {{this.codeError}}
+ </div>
+ {{/if}}
+ </div>
+ {{else}}
+ {{#if this.isSignup}}
+ <p class="code-login-form__instructions">
+ {{i18n "code_login.signup_instructions"}}
+ </p>
{{/if}}
- <div class="code-login-form__email-actions">
- <form.Submit
- class="btn-primary code-login-form__continue"
- @label="code_login.continue_button"
+ <Form
+ class="code-login-form__email-step"
+ @data={{hash email=this.email}}
+ @onSubmit={{this.submitEmail}}
+ as |form|
+ >
+ <form.Field
+ @format="full"
+ @name="email"
+ @title={{i18n "code_login.email_label"}}
+ @type="input-email"
+ @validate={{this.validateEmail}}
+ @validation="required"
+ as |field|
+ >
+ <field.Control autocomplete="username" autofocus="autofocus" />
+ </form.Field>
+
+ {{! Lets a signup flow add its own fields to this form — an agreement
+ it needs accepted before the account exists, say — so they are
+ validated and submitted together with the email. }}
+ <PluginOutlet
+ @name="code-login-email-step-fields"
+ @outletArgs={{lazyHash form=form context=@context}}
/>
- {{#if @onUsePassword}}
- <DButton
- class="btn-flat code-login-form__password-toggle"
- @action={{@onUsePassword}}
- @label="code_login.use_password_instead"
- />
+ {{#if this.codeError}}
+ <div
+ aria-live="polite"
+ class="code-login-form__error"
+ role="alert"
+ >
+ {{this.codeError}}
+ </div>
{{/if}}
- </div>
- </Form>
+
+ <div class="code-login-form__email-actions">
+ <form.Submit
+ class="btn-primary code-login-form__continue"
+ @label="code_login.continue_button"
+ />
+
+ {{#if @onUsePassword}}
+ <DButton
+ class="btn-flat code-login-form__password-toggle"
+ @action={{@onUsePassword}}
+ @label="code_login.use_password_instead"
+ />
+ {{/if}}
+ </div>
+ </Form>
+ {{/if}}
{{else if this.isCodeStep}}
<div class="code-login-form__code-step">
{{#unless this.isSignup}}
@@ -797,11 +844,13 @@ export default class CodeLoginForm extends Component {
@disabled={{this.resendDisabled}}
@translatedLabel={{this.resendLabel}}
/>
- <DButton
- class="btn-flat code-login-form__change-email"
- @action={{this.changeEmail}}
- @label="code_login.use_different_email"
- />
+ {{#unless this.isInviteEmailLocked}}
+ <DButton
+ class="btn-flat code-login-form__change-email"
+ @action={{this.changeEmail}}
+ @label="code_login.use_different_email"
+ />
+ {{/unless}}
</div>
</div>
{{else if this.isCompleteStep}}
diff --git a/frontend/discourse/app/controllers/invites/show.js b/frontend/discourse/app/controllers/invites/show.js
index 9343600cf2f..5db29d20125 100644
--- a/frontend/discourse/app/controllers/invites/show.js
+++ b/frontend/discourse/app/controllers/invites/show.js
@@ -19,6 +19,7 @@ import { i18n } from "discourse-i18n";
export default class InvitesShowController extends Controller {
@tracked accountPassword;
@tracked accountUsername;
+ @tracked codeInviteStep = "email";
@tracked isDeveloper;
@autoTrackedArray rejectedEmails = [];
@@ -193,11 +194,31 @@ export default class InvitesShowController extends Controller {
return !this.existingUserId;
}
+ @computed("codeInviteStep", "showCodeInviteForm")
+ get showInviteIntroduction() {
+ return !this.showCodeInviteForm || this.codeInviteStep === "email";
+ }
+
@computed("externalAuthsOnly", "discourseConnectEnabled")
get showSignupProgressBar() {
return !(this.externalAuthsOnly || this.discourseConnectEnabled);
}
+ @computed("codeInviteStep", "showCodeInviteForm", "successMessage")
+ get progressBarStep() {
+ if (this.showCodeInviteForm) {
+ if (this.codeInviteStep === "complete") {
+ return "login";
+ }
+
+ if (this.codeInviteStep !== "email") {
+ return "activate";
+ }
+ }
+
+ return this.successMessage ? "activate" : "signup";
+ }
+
@computed(
"emailValidation.failed",
"usernameValidation.failed",
@@ -251,6 +272,15 @@ export default class InvitesShowController extends Controller {
);
}
+ get showCodeInviteForm() {
+ return (
+ this.siteSettings.enable_local_logins_via_code &&
+ this.siteSettings.enable_local_logins_via_email &&
+ this.siteSettings.enable_local_logins &&
+ !this.authOptions
+ );
+ }
+
@computed
get showFullname() {
return this.site.full_name_visible_in_signup;
@@ -360,6 +390,11 @@ export default class InvitesShowController extends Controller {
});
}
+ @action
+ updateCodeInviteStep(step) {
+ this.codeInviteStep = step;
+ }
+
@action
setAccountUsername(event) {
this.accountUsername = event.target.value;
diff --git a/frontend/discourse/app/routes/invites/show.js b/frontend/discourse/app/routes/invites/show.js
index 398195202d7..b148b173526 100644
--- a/frontend/discourse/app/routes/invites/show.js
+++ b/frontend/discourse/app/routes/invites/show.js
@@ -47,6 +47,7 @@ export default class InvitesShow extends DiscourseRoute {
setupController(controller, model) {
super.setupController(...arguments);
controller.accountUsername = model.username;
+ controller.codeInviteStep = "email";
if (model.user_fields) {
controller.userFields.forEach((userField) => {
diff --git a/frontend/discourse/app/templates/invites/show.gjs b/frontend/discourse/app/templates/invites/show.gjs
index cdb90542b25..a541fb78479 100644
--- a/frontend/discourse/app/templates/invites/show.gjs
+++ b/frontend/discourse/app/templates/invites/show.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 LoginButtons from "discourse/components/login-buttons";
import PluginOutlet from "discourse/components/plugin-outlet";
@@ -30,10 +31,10 @@ export default <template>
<div class="container invites-show clearfix">
{{#if @controller.showWelcomeHeader}}
{{#if @controller.showSignupProgressBar}}
- <SignupProgressBar
- @step={{if @controller.successMessage "activate" "signup"}}
- />
- <WelcomeHeader @header={{@controller.welcomeTitle}} />
+ <SignupProgressBar @step={{@controller.progressBarStep}} />
+ {{#if @controller.showInviteIntroduction}}
+ <WelcomeHeader @header={{@controller.welcomeTitle}} />
+ {{/if}}
{{/if}}
{{/if}}
@@ -46,27 +47,29 @@ export default <template>
<p>{{trustHTML @controller.successMessage}}</p>
</div>
{{else}}
- <div class="invited-by">
- <p>{{i18n "invites.invited_by"}}</p>
- <p>
- <DUserInfo @user={{@controller.invitedBy}} />
- </p>
- </div>
+ {{#if @controller.showInviteIntroduction}}
+ <div class="invited-by">
+ <p>{{i18n "invites.invited_by"}}</p>
+ <p>
+ <DUserInfo @user={{@controller.invitedBy}} />
+ </p>
+ </div>
- {{#if @controller.associateHtml}}
- <p class="create-account-associate-link">
- {{trustHTML @controller.associateHtml}}
- </p>
- {{/if}}
+ {{#if @controller.associateHtml}}
+ <p class="create-account-associate-link">
+ {{trustHTML @controller.associateHtml}}
+ </p>
+ {{/if}}
- {{#unless @controller.isInviteLink}}
- <p class="email-message">
- {{trustHTML @controller.yourEmailMessage}}
- {{#if @controller.showSocialLoginAvailable}}
- {{i18n "invites.social_login_available"}}
- {{/if}}
- </p>
- {{/unless}}
+ {{#unless @controller.isInviteLink}}
+ <p class="email-message">
+ {{trustHTML @controller.yourEmailMessage}}
+ {{#if @controller.showSocialLoginAvailable}}
+ {{i18n "invites.social_login_available"}}
+ {{/if}}
+ </p>
+ {{/unless}}
+ {{/if}}
{{#if @controller.externalAuthsOnly}}
{{! authOptions are present once the user has followed the OmniAuth flow (e.g. twitter/google/etc) }}
@@ -95,178 +98,199 @@ export default <template>
{{/if}}
{{#if @controller.shouldDisplayForm}}
- <form>
- {{#if @controller.isInviteLink}}
- <div class="input email-input input-group">
- <Input
- autofocus="autofocus"
- class={{valueEntered @controller.email}}
- disabled={{@controller.externalAuthsOnly}}
- id="new-account-email"
- name="email"
- @type="email"
- @value={{@controller.email}}
- {{on "focusin" @controller.scrollInputIntoView}}
- />
- <label class="alt-placeholder" for="new-account-email">
- {{i18n "user.email.title"}}
- </label>
- <DInputTip
- id="account-email-validation"
- @validation={{@controller.emailValidation}}
- />
- {{#unless @controller.emailValidation.reason}}
- <div class="instructions">
- {{i18n "user.email.instructions"}}
- </div>
- {{/unless}}
- </div>
- {{/if}}
-
- <div class="input username-input input-group">
- <PluginOutlet
- @name="invite-username-input"
- @outletArgs={{lazyHash
- }}
- >
- <input
- autocomplete="off"
- class={{valueEntered @controller.accountUsername}}
- id="new-account-username"
- maxlength={{@controller.maxUsernameLength}}
- name="username"
- type="text"
- value={{@controller.accountUsername}}
- {{on "focusin" @controller.scrollInputIntoView}}
- {{on "input" @controller.setAccountUsername}}
- />
- <label class="alt-placeholder" for="new-account-username">
- {{i18n "user.username.title"}}
- </label>
- <DInputTip
- id="username-validation"
- @validation={{@controller.usernameValidation}}
- />
- </PluginOutlet>
- </div>
-
+ {{#if @controller.showCodeInviteForm}}
+ <CodeLoginForm
+ @context="invite"
+ @emailLocked={{not @controller.isInviteLink}}
+ @initialEmail={{@controller.email}}
+ @inviteKey={{@controller.model.token}}
+ @onStepChange={{@controller.updateCodeInviteStep}}
+ />
{{#if
- (and @controller.showFullname @controller.fullnameRequired)
+ (and
+ @controller.showInviteIntroduction
+ @controller.disclaimerHtml
+ )
}}
- <FullnameInput
- class="input name-input input-group name-required"
- @accountName={{@controller.accountName}}
- @nameDisabled={{@controller.nameDisabled}}
- @nameTitle={{@controller.nameTitle}}
- @nameValidation={{@controller.nameValidation}}
- @onFocusIn={{@controller.scrollInputIntoView}}
- />
+ <div class="disclaimer">
+ {{trustHTML @controller.disclaimerHtml}}
+ </div>
{{/if}}
+ {{else}}
+ <form>
+ {{#if @controller.isInviteLink}}
+ <div class="input email-input input-group">
+ <Input
+ autofocus="autofocus"
+ class={{valueEntered @controller.email}}
+ disabled={{@controller.externalAuthsOnly}}
+ id="new-account-email"
+ name="email"
+ @type="email"
+ @value={{@controller.email}}
+ {{on "focusin" @controller.scrollInputIntoView}}
+ />
+ <label class="alt-placeholder" for="new-account-email">
+ {{i18n "user.email.title"}}
+ </label>
+ <DInputTip
+ id="account-email-validation"
+ @validation={{@controller.emailValidation}}
+ />
+ {{#unless @controller.emailValidation.reason}}
+ <div class="instructions">
+ {{i18n "user.email.instructions"}}
+ </div>
+ {{/unless}}
+ </div>
+ {{/if}}
- {{#unless @controller.externalAuthsOnly}}
- <div class="input password-input input-group">
- <DPasswordField
- autocomplete="new-password"
- class={{valueEntered @controller.accountPassword}}
- id="new-account-password"
- type={{if @controller.maskPassword "password" "text"}}
- @capsLockOn={{@controller.capsLockOn}}
- @value={{@controller.accountPassword}}
- {{on "focusin" @controller.scrollInputIntoView}}
- />
- <label class="alt-placeholder" for="new-account-password">
- {{i18n "invites.password_label"}}
- </label>
- <DTogglePasswordMask
- @maskPassword={{@controller.maskPassword}}
- @parentController="invites-show"
- @togglePasswordMask={{@controller.togglePasswordMask}}
+ <div class="input username-input input-group">
+ <PluginOutlet
+ @name="invite-username-input"
+ @outletArgs={{lazyHash
+ }}
+ >
+ <input
+ autocomplete="off"
+ class={{valueEntered @controller.accountUsername}}
+ id="new-account-username"
+ maxlength={{@controller.maxUsernameLength}}
+ name="username"
+ type="text"
+ value={{@controller.accountUsername}}
+ {{on "focusin" @controller.scrollInputIntoView}}
+ {{on "input" @controller.setAccountUsername}}
+ />
+ <label class="alt-placeholder" for="new-account-username">
+ {{i18n "user.username.title"}}
+ </label>
+ <DInputTip
+ id="username-validation"
+ @validation={{@controller.usernameValidation}}
+ />
+ </PluginOutlet>
+ </div>
+
+ {{#if
+ (and @controller.showFullname @controller.fullnameRequired)
+ }}
+ <FullnameInput
+ class="input name-input input-group name-required"
+ @accountName={{@controller.accountName}}
+ @nameDisabled={{@controller.nameDisabled}}
+ @nameTitle={{@controller.nameTitle}}
+ @nameValidation={{@controller.nameValidation}}
+ @onFocusIn={{@controller.scrollInputIntoView}}
/>
- <div class="create-account__password-info">
- <div class="create-account__password-tip-validation">
- <DInputTip
- id="password-validation"
- @validation={{@controller.passwordValidation}}
- />
- <div
- class="caps-lock-warning
- {{unless @controller.capsLockOn 'hidden'}}"
- >
- {{dIcon "triangle-exclamation"}}
- {{i18n "login.caps_lock_warning"}}
+ {{/if}}
+
+ {{#unless @controller.externalAuthsOnly}}
+ <div class="input password-input input-group">
+ <DPasswordField
+ autocomplete="new-password"
+ class={{valueEntered @controller.accountPassword}}
+ id="new-account-password"
+ type={{if @controller.maskPassword "password" "text"}}
+ @capsLockOn={{@controller.capsLockOn}}
+ @value={{@controller.accountPassword}}
+ {{on "focusin" @controller.scrollInputIntoView}}
+ />
+ <label class="alt-placeholder" for="new-account-password">
+ {{i18n "invites.password_label"}}
+ </label>
+ <DTogglePasswordMask
+ @maskPassword={{@controller.maskPassword}}
+ @parentController="invites-show"
+ @togglePasswordMask={{@controller.togglePasswordMask}}
+ />
+ <div class="create-account__password-info">
+ <div class="create-account__password-tip-validation">
+ <DInputTip
+ id="password-validation"
+ @validation={{@controller.passwordValidation}}
+ />
+ <div
+ class="caps-lock-warning
+ {{unless @controller.capsLockOn 'hidden'}}"
+ >
+ {{dIcon "triangle-exclamation"}}
+ {{i18n "login.caps_lock_warning"}}
+ </div>
</div>
</div>
</div>
- </div>
- {{/unless}}
+ {{/unless}}
- {{#if
- (and
- @controller.showFullname (not @controller.fullnameRequired)
- )
- }}
- <FullnameInput
- class="input name-input input-group"
- @accountName={{@controller.accountName}}
- @nameDisabled={{@controller.nameDisabled}}
- @nameTitle={{@controller.nameTitle}}
- @nameValidation={{@controller.nameValidation}}
- @onFocusIn={{@controller.scrollInputIntoView}}
- />
- {{/if}}
+ {{#if
+ (and
+ @controller.showFullname
+ (not @controller.fullnameRequired)
+ )
+ }}
+ <FullnameInput
+ class="input name-input input-group"
+ @accountName={{@controller.accountName}}
+ @nameDisabled={{@controller.nameDisabled}}
+ @nameTitle={{@controller.nameTitle}}
+ @nameValidation={{@controller.nameValidation}}
+ @onFocusIn={{@controller.scrollInputIntoView}}
+ />
+ {{/if}}
- {{#if @controller.userFields}}
- <div class="user-fields">
- {{#each @controller.userFields as |f|}}
- <div class="input-group">
- <UserField
- class={{valueEntered f.value}}
- @field={{f.field}}
- @value={{f.value}}
- {{on "focusin" @controller.scrollInputIntoView}}
- />
- </div>
- {{/each}}
- </div>
- {{/if}}
+ {{#if @controller.userFields}}
+ <div class="user-fields">
+ {{#each @controller.userFields as |f|}}
+ <div class="input-group">
+ <UserField
+ class={{valueEntered f.value}}
+ @field={{f.field}}
+ @value={{f.value}}
+ {{on "focusin" @controller.scrollInputIntoView}}
+ />
+ </div>
+ {{/each}}
+ </div>
+ {{/if}}
- <div class="invitation-cta">
- <DButton
- class="btn-primary invitation-cta__accept"
- type="submit"
- @action={{@controller.submit}}
- @disabled={{@controller.submitDisabled}}
- @label="invites.accept_invite"
- />
- <div class="invitation-cta__info">
- <span class="invitation-cta__signed-up">{{i18n
- "login.previous_sign_up"
- }}</span>
+ <div class="invitation-cta">
<DButton
- class="btn-flat invitation-cta__sign-in"
- @action={{routeAction "showLogin"}}
- @label="log_in"
+ class="btn-primary invitation-cta__accept"
+ type="submit"
+ @action={{@controller.submit}}
+ @disabled={{@controller.submitDisabled}}
+ @label="invites.accept_invite"
/>
+ <div class="invitation-cta__info">
+ <span class="invitation-cta__signed-up">{{i18n
+ "login.previous_sign_up"
+ }}</span>
+ <DButton
+ class="btn-flat invitation-cta__sign-in"
+ @action={{routeAction "showLogin"}}
+ @label="log_in"
+ />
+ </div>
</div>
- </div>
- <div class="disclaimer">
- {{trustHTML @controller.disclaimerHtml}}
- </div>
+ <div class="disclaimer">
+ {{trustHTML @controller.disclaimerHtml}}
+ </div>
- {{#if @controller.errorMessage}}
- <br /><br />
- <div
- class="alert alert-error"
- >{{@controller.errorMessage}}</div>
- {{/if}}
- </form>
+ {{#if @controller.errorMessage}}
+ <br /><br />
+ <div
+ class="alert alert-error"
+ >{{@controller.errorMessage}}</div>
+ {{/if}}
+ </form>
+ {{/if}}
{{/if}}
{{! When using DiscourseConnect, all invite acceptance has to go through the SSO flow }}
{{#unless @controller.discourseConnectEnabled}}
diff --git a/frontend/discourse/tests/integration/components/code-login-form-test.gjs b/frontend/discourse/tests/integration/components/code-login-form-test.gjs
index c77ecdb0562..c736071a1f0 100644
--- a/frontend/discourse/tests/integration/components/code-login-form-test.gjs
+++ b/frontend/discourse/tests/integration/components/code-login-form-test.gjs
@@ -86,6 +86,46 @@ module("Integration | Component | CodeLoginForm", function (hooks) {
.exists("the form advances after the request succeeds");
});
+ test("email invitations request a code without exposing the address", async function (assert) {
+ let requestParams;
+ pretender.get("/session/hp.json", () =>
+ response({ value: "hp-value", challenge: "abc", expires_in: 300 })
+ );
+ pretender.post("/session/login-code", (request) => {
+ requestParams = new URLSearchParams(request.requestBody);
+ return response({ success: "OK" });
+ });
+
+ await render(
+ <template>
+ <CodeLoginForm
+ @context="invite"
+ @emailLocked={{true}}
+ @initialEmail="u***@example.com"
+ @inviteKey="invite-key"
+ />
+ </template>
+ );
+
+ assert
+ .dom(".code-login-form__email-step input")
+ .doesNotExist("the masked address is not rendered in an editable field");
+
+ await click(".code-login-form__continue");
+
+ assert.strictEqual(
+ requestParams.get("invite_key"),
+ "invite-key",
+ "the code request identifies the invitation"
+ );
+ assert
+ .dom(".code-login-form__code-step")
+ .exists("the code entry step is shown");
+ assert
+ .dom(".code-login-form__change-email")
+ .doesNotExist("the scoped invitation address cannot be changed");
+ });
+
test("shows a request error without advancing to the code step", async function (assert) {
const error =
"New registrations are not allowed from your IP address (maximum limit reached). Contact a staff member.";
diff --git a/spec/mailers/invite_mailer_spec.rb b/spec/mailers/invite_mailer_spec.rb
index a47ae78fd28..5ae90ae850e 100644
--- a/spec/mailers/invite_mailer_spec.rb
+++ b/spec/mailers/invite_mailer_spec.rb
@@ -32,6 +32,39 @@ RSpec.describe InviteMailer do
"#{Discourse.base_url}/invites/#{invite.invite_key}",
)
end
+
+ it "omits the email token when invite acceptance uses a code" do
+ SiteSetting.enable_local_logins_via_code = true
+
+ expect(invite_mail.body.encoded).to include(
+ "#{Discourse.base_url}/invites/#{invite.invite_key}",
+ )
+ expect(invite_mail.body.encoded).not_to include(invite.email_token)
+ end
+
+ %i[enable_local_logins enable_local_logins_via_email].each do |setting|
+ it "includes the email token when #{setting} is disabled after enabling codes" do
+ SiteSetting.enable_local_logins_via_code = true
+ SiteSetting.public_send("#{setting}=", false)
+
+ expect(invite_mail.body.encoded).to include(invite.email_token)
+ end
+ end
+
+ it "includes the email token when DiscourseConnect is enabled" do
+ SiteSetting.enable_local_logins_via_code = true
+ SiteSetting.discourse_connect_url = "https://example.com/sso"
+ SiteSetting.discourse_connect_secret = "x" * 10
+ SiteSetting.enable_discourse_connect = true
+
+ expect(invite_mail.body.encoded).to include(invite.email_token)
+ end
+
+ it "includes the email token when invite acceptance uses a password" do
+ SiteSetting.enable_local_logins_via_code = false
+
+ expect(invite_mail.body.encoded).to include(invite.email_token)
+ end
end
context "with custom invite message" do
diff --git a/spec/models/invite_redeemer_spec.rb b/spec/models/invite_redeemer_spec.rb
index 7d0d4e8f3d5..e1175cc36b6 100644
--- a/spec/models/invite_redeemer_spec.rb
+++ b/spec/models/invite_redeemer_spec.rb
@@ -300,6 +300,46 @@ RSpec.describe InviteRedeemer do
InviteRedeemer.new(invite: invite, email: invite.email, username: username, name: name)
end
+ it "rejects an unverified supplied email when the user's primary email does not match the invite" do
+ invite = Fabricate(:invite, email: "[email protected]")
+ user = Fabricate(:user, email: "[email protected]")
+ redeemer = described_class.new(invite:, email: invite.email, redeeming_user: user)
+
+ expect { redeemer.redeem }.to raise_error(
+ ActiveRecord::RecordNotSaved,
+ I18n.t("invite.not_matching_email"),
+ )
+ expect(invite.reload).not_to be_redeemed
+ end
+
+ it "rejects an unverified supplied email when the user's primary email is outside the invite domain" do
+ invite = Fabricate(:invite, email: nil, domain: "allowed.example")
+ user = Fabricate(:user, email: "[email protected]")
+ redeemer = described_class.new(invite:, email: "[email protected]", redeeming_user: user)
+
+ expect { redeemer.redeem }.to raise_error(
+ ActiveRecord::RecordNotSaved,
+ I18n.t("invite.domain_not_allowed"),
+ )
+ expect(invite.reload).not_to be_redeemed
+ end
+
+ it "redeems an invite for an existing user's verified secondary email" do
+ invite = Fabricate(:invite, email: "[email protected]")
+ user = Fabricate(:user, email: "[email protected]")
+ Fabricate(:secondary_email, user:, email: invite.email)
+ redeemer =
+ described_class.new(
+ invite:,
+ email: invite.email,
+ email_verified: true,
+ redeeming_user: user,
+ )
+
+ expect(redeemer.redeem).to eq(user)
+ expect(invite.reload).to be_redeemed
+ end
+
context "with email" do
fab!(:invite) { Fabricate(:invite, email: "[email protected]") }
context "when must_approve_users setting is enabled" do
diff --git a/spec/requests/invites_controller_spec.rb b/spec/requests/invites_controller_spec.rb
index cac75f4071a..0f3a1f98873 100644
--- a/spec/requests/invites_controller_spec.rb
+++ b/spec/requests/invites_controller_spec.rb
@@ -46,6 +46,43 @@ RSpec.describe InvitesController do
end
end
+ it "does not treat a legacy email token as verification when invite codes are enabled" do
+ SiteSetting.enable_local_logins_via_code = true
+ user_field = Fabricate(:user_field)
+ staged_user = Fabricate(:user, staged: true, email: invite.email)
+ staged_user.set_user_field(user_field.id, "private value")
+ staged_user.save_custom_fields
+
+ get "/invites/#{invite.invite_key}?t=#{invite.email_token}"
+
+ expect(response.status).to eq(200)
+ expect(response.body).to have_tag("script#data-preloaded") do |element|
+ json = JSON.parse(element.current_scope.text)
+ invite_info = JSON.parse(json["invite_info"])
+ expect(invite_info["email"]).to eq("i*****g@a***********e.ooo")
+ expect(invite_info["email_verified_by_link"]).to eq(false)
+ expect(invite_info["username"]).not_to eq(staged_user.username)
+ expect(invite_info["user_fields"]).to be_nil
+ end
+ end
+
+ %i[enable_local_logins enable_local_logins_via_email].each do |setting|
+ it "verifies legacy email tokens when #{setting} is disabled after enabling codes" do
+ SiteSetting.enable_local_logins_via_code = true
+ SiteSetting.public_send("#{setting}=", false)
+ SiteSetting.enable_google_oauth2_logins = true
+
+ get "/invites/#{invite.invite_key}?t=#{invite.email_token}"
+
+ expect(response.status).to eq(200)
+ expect(response.body).to have_tag("script#data-preloaded") do |element|
+ invite_info = JSON.parse(JSON.parse(element.current_scope.text)["invite_info"])
+ expect(invite_info["email"]).to eq(invite.email)
+ expect(invite_info["email_verified_by_link"]).to eq(true)
+ end
+ end
+ end
+
context "when email data is present in authentication data" do
before { server_session[:authentication] = { email: invite.email } }
@@ -1314,6 +1351,38 @@ RSpec.describe InvitesController do
end
describe "#perform_accept_invitation" do
+ context "when anonymous invite acceptance uses email codes" do
+ fab!(:invite)
+
+ before { SiteSetting.enable_local_logins_via_code = true }
+
+ it "accepts the legacy form when email login is disabled after enabling codes" do
+ SiteSetting.enable_local_logins_via_email = false
+
+ put "/invites/show/#{invite.invite_key}.json",
+ params: {
+ email_token: invite.email_token,
+ password: "verystrongpassword",
+ }
+
+ expect(response.status).to eq(200)
+ expect(invite.reload).to be_redeemed
+ expect(session[:current_user_id]).to eq(User.find_by_email(invite.email).id)
+ end
+
+ it "does not allow the legacy password acceptance endpoint" do
+ put "/invites/show/#{invite.invite_key}.json",
+ params: {
+ email_token: invite.email_token,
+ password: "verystrongpassword",
+ }
+
+ expect(response.status).to eq(404)
+ expect(invite.reload).not_to be_redeemed
+ expect(User.find_by_email(invite.email)).to be_nil
+ end
+ end
+
context "with an invalid invite" do
it "redirects to the root" do
put "/invites/show/doesntexist.json"
@@ -1491,7 +1560,8 @@ RSpec.describe InvitesController do
expect(user.user_associated_accounts.first.provider_name).to eq("google_oauth2")
end
- it "returns the right response even if local logins has been disabled" do
+ it "accepts external authentication when local logins are disabled after enabling codes" do
+ SiteSetting.enable_local_logins_via_code = true
SiteSetting.enable_local_logins = false
invite.update!(email: authenticated_email)
diff --git a/spec/requests/session_controller_spec.rb b/spec/requests/session_controller_spec.rb
index 5c117d8e692..17cde373b0c 100644
--- a/spec/requests/session_controller_spec.rb
+++ b/spec/requests/session_controller_spec.rb
@@ -634,6 +634,58 @@ RSpec.describe SessionController do
expect(EmailLoginCode.for_email(user.email).count).to eq(1)
end
+ context "when requesting a code for an email invite" do
+ let(:invite) { Fabricate(:invite, email: "[email protected]") }
+
+ it "uses the invite's email instead of a supplied email" do
+ expect_enqueued_with(job: :send_email_login_code, args: { to_address: invite.email }) do
+ post "/session/login-code.json",
+ params: honeypot_magic(email: "[email protected]", invite_key: invite.invite_key)
+ end
+
+ expect(response.status).to eq(200)
+ expect(response.parsed_body["success"]).to eq("OK")
+ expect(EmailLoginCode.for_email(invite.email).count).to eq(1)
+ expect(EmailLoginCode.for_email("[email protected]")).to be_empty
+ end
+
+ it "returns the generic success response when the invite is not redeemable" do
+ invite.update!(expires_at: 1.day.ago)
+
+ post "/session/login-code.json", params: honeypot_magic(invite_key: invite.invite_key)
+
+ expect(response.status).to eq(200)
+ expect(response.parsed_body["success"]).to eq("OK")
+ expect(EmailLoginCode.for_email(invite.email)).to be_empty
+ end
+
+ it "returns generic success without emailing a code for a normalized-only match" do
+ SiteSetting.normalize_emails = true
+ user.update!(email: "[email protected]")
+ invite.update!(email: "[email protected]")
+
+ expect_not_enqueued_with(job: :send_email_login_code) do
+ post "/session/login-code.json", params: honeypot_magic(invite_key: invite.invite_key)
+ end
+
+ expect(response.status).to eq(200)
+ expect(response.parsed_body["success"]).to eq("OK")
+ expect(EmailLoginCode.for_email(invite.email)).to be_empty
+ end
+
+ it "sends a code when the invite belongs to an existing user whose domain is blocked" do
+ Fabricate(:user, email: invite.email)
+ SiteSetting.blocked_email_domains = "example.com"
+
+ expect_enqueued_with(job: :send_email_login_code, args: { to_address: invite.email }) do
+ post "/session/login-code.json", params: honeypot_magic(invite_key: invite.invite_key)
+ end
+
+ expect(response.status).to eq(200)
+ expect(EmailLoginCode.for_email(invite.email).count).to eq(1)
+ end
+ end
+
it "does not generate a code for an address that only matches after normalization" do
SiteSetting.normalize_emails = true
user.update!(email: "[email protected]")
@@ -841,6 +893,168 @@ RSpec.describe SessionController do
expect(EmailLoginCode.active.for_email(user.email)).to be_empty
end
+ context "when verifying a code for an email invite" do
+ let(:invite) { Fabricate(:invite, email: "[email protected]") }
+ let(:topic) { Fabricate(:topic) }
+ let(:login_code) { EmailLoginCode.generate!(email: invite.email) }
+
+ before { invite.update!(topics: [topic]) }
+
+ it "creates a passwordless account, redeems the invite, and returns its destination" do
+ post "/session/login-code/verify.json",
+ params: {
+ invite_key: invite.invite_key,
+ email: "[email protected]",
+ code:,
+ }
+
+ invited_user = User.find_by_email(invite.email)
+
+ expect(response.status).to eq(200)
+ expect(response.parsed_body["account_created"]).to eq(true)
+ expect(response.parsed_body["redirect_url"]).to eq(topic.relative_url)
+ expect(session[:current_user_id]).to eq(invited_user.id)
+ expect(invited_user).to be_active
+ expect(invited_user).to be_email_confirmed
+ expect(invited_user.user_password).to be_nil
+ expect(invite.reload).to be_redeemed
+ expect(login_code.reload.consumed_at).to be_present
+ end
+
+ it "activates an existing inactive invitee and keeps them signed in" do
+ user.update!(email: invite.email, active: false)
+
+ post "/session/login-code/verify.json", params: { invite_key: invite.invite_key, code: }
+
+ expect(response.status).to eq(200)
+ expect(response.parsed_body["error"]).to be_nil
+ expect(invite.reload).to be_redeemed
+ expect(login_code.reload.consumed_at).to be_present
+
+ get "/session/current.json"
+
+ expect(response.status).to eq(200)
+ expect(response.parsed_body.dig("current_user", "id")).to eq(user.id)
+ end
+
+ it "redeems an invite addressed to an existing user's secondary email" do
+ Fabricate(:secondary_email, user:, email: invite.email)
+
+ post "/session/login-code/verify.json", params: { invite_key: invite.invite_key, code: }
+
+ expect(response.status).to eq(200)
+ expect(response.parsed_body["error"]).to be_nil
+ expect(invite.reload).to be_redeemed
+ expect(login_code.reload.consumed_at).to be_present
+
+ get "/session/current.json"
+
+ expect(response.status).to eq(200)
+ expect(response.parsed_body.dig("current_user", "id")).to eq(user.id)
+ end
+
+ it "does not consume the code when the invite expires before verification" do
+ invite.update!(expires_at: 1.day.ago)
+
+ post "/session/login-code/verify.json", params: { invite_key: invite.invite_key, code: }
+
+ expect(response.status).to eq(200)
+ expect(response.parsed_body["error"]).to eq(I18n.t("email_login_code.invalid_code"))
+ expect(session[:current_user_id]).to be_nil
+ expect(login_code.reload.consumed_at).to be_nil
+ end
+ end
+
+ it "explains when the user has already redeemed a reusable invite without consuming the code" do
+ invite = Fabricate(:invite, email: nil, max_redemptions_allowed: 5)
+ Fabricate(:invited_user, invite:, user:)
+
+ post "/session/login-code/verify.json",
+ params: {
+ invite_key: invite.invite_key,
+ email: user.email,
+ code:,
+ }
+
+ expect(response.status).to eq(200)
+ expect(response.parsed_body["error"]).to eq(I18n.t("invite.existing_user_already_redemeed"))
+ expect(session[:current_user_id]).to be_nil
+ expect(login_code.reload.consumed_at).to be_nil
+ end
+
+ context "when verifying a code for a domain-scoped invite" do
+ let(:invite) { Fabricate(:invite, email: nil, domain: "allowed.example") }
+ let(:login_code) { EmailLoginCode.generate!(email: "[email protected]") }
+
+ it "accepts a verified secondary email when the primary email is outside the allowed domain" do
+ user.update!(email: "[email protected]")
+ secondary_email = Fabricate(:secondary_email, user:, email: "[email protected]")
+ secondary_code = EmailLoginCode.generate!(email: secondary_email.email)
+
+ post "/session/login-code/verify.json",
+ params: {
+ invite_key: invite.invite_key,
+ email: secondary_email.email,
+ code: secondary_code.code,
+ }
+
+ expect(response.status).to eq(200)
+ expect(response.parsed_body["error"]).to be_nil
+ expect(invite.reload).to be_redeemed
+ expect(secondary_code.reload.consumed_at).to be_present
+
+ get "/session/current.json"
+
+ expect(response.status).to eq(200)
+ expect(response.parsed_body.dig("current_user", "id")).to eq(user.id)
+ end
+
+ it "rejects an email outside the allowed domain without consuming its code" do
+ post "/session/login-code/verify.json",
+ params: {
+ invite_key: invite.invite_key,
+ email: login_code.email,
+ code:,
+ }
+
+ expect(response.status).to eq(200)
+ expect(response.parsed_body["error"]).to eq(I18n.t("email_login_code.invalid_code"))
+ expect(session[:current_user_id]).to be_nil
+ expect(login_code.reload.consumed_at).to be_nil
+ end
+ end
+
+ context "when an existing invited user has TOTP enabled" do
+ let(:invite) { Fabricate(:invite, email: "[email protected]") }
+ let(:login_code) { EmailLoginCode.generate!(email: invite.email) }
+ let!(:user_second_factor) { Fabricate(:user_second_factor_totp, user:) }
+
+ before { user.update!(email: invite.email) }
+
+ it "requires the second factor before redeeming the invite" do
+ post "/session/login-code/verify.json", params: { invite_key: invite.invite_key, code: }
+
+ expect(response.status).to eq(200)
+ expect(response.parsed_body["second_factor_required"]).to eq(true)
+ expect(session[:current_user_id]).to be_nil
+ expect(invite.reload).not_to be_redeemed
+ expect(EmailLoginCode.active.for_email(invite.email)).to contain_exactly(login_code)
+
+ post "/session/login-code/verify.json",
+ params: {
+ invite_key: invite.invite_key,
+ code:,
+ second_factor_token: ROTP::TOTP.new(user_second_factor.data).now,
+ second_factor_method: UserSecondFactor.methods[:totp],
+ }
+
+ expect(response.status).to eq(200)
+ expect(session[:current_user_id]).to eq(user.id)
+ expect(invite.reload).to be_redeemed
+ expect(login_code.reload.consumed_at).to be_present
+ end
+ end
+
it "follows a pending DiscourseConnect provider handoff for an existing user" do
begin_discourse_connect_provider_handoff
@@ -850,6 +1064,36 @@ RSpec.describe SessionController do
expect(response.location).to start_with("http://ask.example.com/sso")
end
+ context "when a pending DiscourseConnect provider handoff meets an invite" do
+ let(:invite) { Fabricate(:invite, email: "[email protected]") }
+ let(:login_code) { EmailLoginCode.generate!(email: invite.email) }
+
+ it "hands the provider URL to a newly created account instead of the invite topic" do
+ invite.update!(topics: [Fabricate(:topic)])
+ begin_discourse_connect_provider_handoff
+
+ post "/session/login-code/verify.json", params: { invite_key: invite.invite_key, code: }
+
+ expect(response.status).to eq(200)
+ expect(response.parsed_body["account_created"]).to eq(true)
+ expect(response.parsed_body["redirect_url"]).to include("/session/sso_provider?sso=")
+ expect(cookies[:sso_payload]).to be_blank
+ end
+
+ it "follows the handoff for an existing user rather than dropping it" do
+ user.update!(email: invite.email)
+ begin_discourse_connect_provider_handoff
+
+ post "/session/login-code/verify.json", params: { invite_key: invite.invite_key, code: }
+
+ expect(response.status).to eq(302)
+ expect(response.location).to start_with("http://ask.example.com/sso")
+ expect(session[:current_user_id]).to eq(user.id)
+ expect(invite.reload).to be_redeemed
+ expect(cookies[:sso_payload]).to be_blank
+ end
+ end
+
it "does not log in with a code issued for a normalized email alias" do
SiteSetting.normalize_emails = true
user.update!(email: "[email protected]")
diff --git a/spec/services/invite/redeem_with_email_code_spec.rb b/spec/services/invite/redeem_with_email_code_spec.rb
new file mode 100644
index 00000000000..980213fb37b
--- /dev/null
+++ b/spec/services/invite/redeem_with_email_code_spec.rb
@@ -0,0 +1,254 @@
+# frozen_string_literal: true
+
+RSpec.describe Invite::RedeemWithEmailCode do
+ describe described_class::Contract, type: :model do
+ it { is_expected.to validate_presence_of(:invite_key) }
+ it { 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) }
+ end
+
+ describe ".call" do
+ subject(:result) { described_class.call(params:, **dependencies) }
+
+ fab!(:invite) { Fabricate(:invite, email: "[email protected]") }
+
+ let(:params) { { invite_key: invite.invite_key, email:, code: } }
+ let(:dependencies) { { ip_address: "127.0.0.1", server_session: {} } }
+ let(:email) { invite.email }
+ let(:login_code) { EmailLoginCode.generate!(email:) }
+ let(:code) { login_code.code }
+
+ context "when the contract isn't valid" do
+ let(:code) { "12345" }
+
+ it { is_expected.to fail_a_contract }
+ end
+
+ context "when the invite cannot be found" do
+ let(:params) { { invite_key: "missing", email:, code: } }
+
+ it { is_expected.to fail_to_find_a_model(:invite) }
+ end
+
+ context "when the invite is no longer redeemable" do
+ before { invite.update!(expires_at: 1.day.ago) }
+
+ it { is_expected.to fail_to_find_a_model(:invite) }
+ end
+
+ context "when the email does not match the email invite" do
+ let(:email) { "[email protected]" }
+
+ it { is_expected.to fail_a_policy(:email_can_redeem_invite) }
+ end
+
+ context "when the email does not match a domain-scoped invite" do
+ fab!(:invite) { Fabricate(:invite, email: nil, domain: "allowed.example") }
+
+ let(:email) { "[email protected]" }
+
+ it { is_expected.to fail_a_policy(:email_can_redeem_invite) }
+ end
+
+ context "when there is no active code for the email" do
+ before { login_code.consume! }
+
+ it { is_expected.to fail_to_find_a_model(:login_code) }
+ end
+
+ context "when the code is wrong" do
+ let(:code) { login_code.code == "000000" ? "000001" : "000000" }
+
+ it { is_expected.to fail_a_policy(:code_matches) }
+ end
+
+ context "when the email matches an account only after normalization" do
+ fab!(:invite) { Fabricate(:invite, email: nil) }
+ 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 redeem the invite" do
+ result
+
+ expect(login_code.reload.consumed_at).to be_nil
+ expect(invite.reload.redemption_count).to eq(0)
+ end
+ end
+
+ context "when registrations are disabled for a new account" 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 redeem the invite" do
+ result
+
+ expect(login_code.reload.consumed_at).to be_nil
+ expect(invite.reload.redemption_count).to eq(0)
+ end
+ end
+
+ context "when the email is blocked before redemption" do
+ before { SiteSetting.blocked_email_domains = "example.com" }
+
+ it { is_expected.to fail_a_policy(:can_register_new_account) }
+ end
+
+ context "when a required signup field is missing" do
+ fab!(:user_field)
+
+ it { is_expected.to fail_a_policy(:required_fields_provided) }
+
+ it "does not consume the code" do
+ result
+
+ expect(login_code.reload.consumed_at).to be_nil
+ end
+ end
+
+ context "when required signup fields are provided" do
+ fab!(:user_field)
+
+ let(:params) do
+ {
+ invite_key: invite.invite_key,
+ email:,
+ code:,
+ user_fields: {
+ user_field.id.to_s => "Engineer",
+ },
+ }
+ end
+
+ it { is_expected.to run_successfully }
+
+ it "saves the field on the invited user" do
+ expect(result[:user].custom_fields["user_field_#{user_field.id}"]).to eq("Engineer")
+ end
+ end
+
+ 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
+ end
+
+ context "when a required full name is provided" do
+ let(:params) { { invite_key: invite.invite_key, email:, code:, name: "Invited Person" } }
+
+ before { SiteSetting.full_name_requirement = "required_at_signup" }
+
+ it { is_expected.to run_successfully }
+
+ it "saves the full name" do
+ expect(result[:user].name).to eq("Invited Person")
+ end
+ end
+
+ context "when a new user redeems the invite" do
+ it { is_expected.to run_successfully }
+
+ it "consumes the code and redeems the invite" do
+ expect { result }.to change { login_code.reload.consumed_at }.from(nil).and(
+ change { invite.reload.redemption_count }.from(0).to(1),
+ )
+ end
+
+ it "creates an active passwordless user with a confirmed email" do
+ user = result[:user]
+
+ expect(user).to be_active
+ expect(user).to be_email_confirmed
+ expect(user.email).to eq(email)
+ expect(user.user_password).to be_nil
+ expect(user.registration_ip_address.to_s).to eq(dependencies[:ip_address])
+ end
+
+ it "does not enqueue password instructions or an activation email" do
+ expect { result }.to not_change { Jobs::InvitePasswordInstructionsEmail.jobs.size }.and(
+ not_change { Jobs::CriticalUserEmail.jobs.size },
+ )
+ end
+ end
+
+ context "when an existing user redeems the invite" do
+ fab!(:existing_user) { Fabricate(:user, email: "[email protected]") }
+
+ it { is_expected.to run_successfully }
+
+ it "returns the existing user and consumes the code" do
+ expect(result[:user]).to eq(existing_user)
+ expect(result[:existing_user]).to eq(existing_user)
+ expect(login_code.reload.consumed_at).to be_present
+ end
+
+ it "redeems the invite even when registrations are disabled" do
+ SiteSetting.allow_new_registrations = false
+
+ expect(result).to run_successfully
+ expect(invite.reload).to be_redeemed
+ end
+ end
+
+ context "when an invite grants group membership" do
+ fab!(:group)
+
+ before do
+ group.add_owner(invite.invited_by)
+ Fabricate(:invited_group, invite:, group:)
+ end
+
+ it "adds the invited user to the group" do
+ expect(result[:user].reload.groups).to include(group)
+ end
+ end
+
+ context "when an invite grants access to a topic" do
+ fab!(:topic)
+
+ before { invite.update!(topics: [topic]) }
+
+ it "creates the invited-to-topic notification" do
+ result
+
+ expect(
+ Notification.exists?(
+ user: result[:user],
+ topic:,
+ notification_type: Notification.types[:invited_to_topic],
+ ),
+ ).to eq(true)
+ 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 active unapproved user pending review" do
+ user = result[:user]
+
+ expect(user).to be_active
+ expect(user).not_to be_approved
+ expect(ReviewableUser.pending.find_by(target: user)).to be_present
+ end
+ end
+ end
+end
diff --git a/spec/services/invite/request_email_code_spec.rb b/spec/services/invite/request_email_code_spec.rb
new file mode 100644
index 00000000000..403aa32d9e0
--- /dev/null
+++ b/spec/services/invite/request_email_code_spec.rb
@@ -0,0 +1,155 @@
+# frozen_string_literal: true
+
+RSpec.describe Invite::RequestEmailCode do
+ describe described_class::Contract, type: :model do
+ it { is_expected.to validate_presence_of(:invite_key) }
+ end
+
+ describe ".call" do
+ subject(:result) { described_class.call(params:, **dependencies) }
+
+ fab!(:invite) { Fabricate(:invite, email: "[email protected]") }
+
+ let(:params) { { invite_key: invite.invite_key, email: supplied_email } }
+ let(:dependencies) { { ip_address: "127.0.0.1" } }
+ let(:email) { invite.email }
+ let(:supplied_email) { email }
+
+ context "when the contract isn't valid" do
+ let(:params) { { invite_key: "" } }
+
+ it { is_expected.to fail_a_contract }
+ end
+
+ context "when the invite cannot be found" do
+ let(:params) { { invite_key: "missing", email: } }
+
+ it { is_expected.to fail_to_find_a_model(:invite) }
+ end
+
+ context "when the invite has expired" do
+ before { invite.update!(expires_at: 1.day.ago) }
+
+ it { is_expected.to fail_to_find_a_model(:invite) }
+ end
+
+ context "when the supplied email does not match the email invite" do
+ let(:supplied_email) { "[email protected]" }
+
+ it { is_expected.to run_successfully }
+
+ it "sends the code to the invite's email" do
+ expect { result }.to change { EmailLoginCode.for_email(email).count }.by(1).and(
+ not_change { EmailLoginCode.for_email(supplied_email).count },
+ )
+ end
+ end
+
+ context "when an invite link has an invalid email" do
+ fab!(:invite) { Fabricate(:invite, email: nil) }
+
+ let(:supplied_email) { "not-an-email" }
+
+ it { is_expected.to fail_a_policy(:email_can_redeem_invite) }
+ end
+
+ context "when an invite link is restricted to another domain" do
+ fab!(:invite) { Fabricate(:invite, email: nil, domain: "allowed.example") }
+
+ let(:supplied_email) { "[email protected]" }
+
+ it { is_expected.to fail_a_policy(:email_can_redeem_invite) }
+ end
+
+ context "when the email only matches an existing account after normalization" do
+ fab!(:invite) { Fabricate(:invite, email: "[email protected]") }
+ fab!(:user) { Fabricate(:user, email: "[email protected]") }
+
+ before { SiteSetting.normalize_emails = true }
+
+ it "rejects the address without creating or emailing a code" do
+ expect_not_enqueued_with(job: :send_email_login_code) do
+ expect { result }.not_to change { EmailLoginCode.count }
+ end
+ expect(result).to fail_a_policy(:email_can_redeem_invite)
+ end
+ end
+
+ context "when the email is an explicitly registered secondary address" do
+ fab!(:user)
+ fab!(:secondary_email) { Fabricate(:secondary_email, user:, email: "[email protected]") }
+
+ before { SiteSetting.normalize_emails = true }
+
+ it "creates and emails a code" do
+ expect_enqueued_with(job: :send_email_login_code, args: { to_address: email }) do
+ expect { result }.to change { EmailLoginCode.for_email(email).count }.by(1)
+ end
+ expect(result).to run_successfully
+ end
+ end
+
+ context "when the registration IP has reached its account limit" do
+ let(:ip_address) { "192.0.2.1" }
+ let(:dependencies) { { ip_address: } }
+
+ before do
+ Fabricate(:user, ip_address:, trust_level: TrustLevel[0])
+ SiteSetting.max_new_accounts_per_registration_ip = 1
+ end
+
+ it { is_expected.to fail_a_policy(:can_register_from_ip) }
+
+ it "does not create a code" do
+ expect { result }.not_to change { EmailLoginCode.count }
+ end
+ end
+
+ context "when the email belongs to an existing user at a limited IP" do
+ fab!(:user) { Fabricate(:user, email: "[email protected]") }
+
+ let(:ip_address) { "192.0.2.1" }
+ let(:dependencies) { { ip_address: } }
+
+ before do
+ Fabricate(:user, ip_address:, trust_level: TrustLevel[0])
+ SiteSetting.max_new_accounts_per_registration_ip = 1
+ end
+
+ it { is_expected.to run_successfully }
+
+ it "triggers the email-login extension event" do
+ events = DiscourseEvent.track_events(:before_email_login) { result }
+
+ expect(events).to contain_exactly(event_name: :before_email_login, params: [user])
+ end
+ end
+
+ context "when an existing user's email domain is blocked" do
+ fab!(:user) { Fabricate(:user, email: "[email protected]") }
+
+ before { SiteSetting.blocked_email_domains = "example.com" }
+
+ it { is_expected.to run_successfully }
+ end
+
+ context "when the email invite is redeemable" do
+ it { is_expected.to run_successfully }
+
+ it "creates a code and enqueues its email" do
+ expect_enqueued_with(job: :send_email_login_code, args: { to_address: email }) do
+ expect { result }.to change { EmailLoginCode.for_email(email).count }.by(1)
+ end
+ end
+ end
+
+ context "when a domain-scoped invite link is redeemable" do
+ fab!(:invite) { Fabricate(:invite, email: nil, domain: "example.com") }
+
+ let(:email) { "[email protected]" }
+ let(:supplied_email) { email }
+
+ it { is_expected.to run_successfully }
+ end
+ end
+end
diff --git a/spec/system/accept_invitation_via_email_code_spec.rb b/spec/system/accept_invitation_via_email_code_spec.rb
new file mode 100644
index 00000000000..76c659c9f06
--- /dev/null
+++ b/spec/system/accept_invitation_via_email_code_spec.rb
@@ -0,0 +1,44 @@
+# frozen_string_literal: true
+
+RSpec.describe "Accept invitation via email code" do
+ fab!(:invite) { Fabricate(:invite, email: "[email protected]") }
+ fab!(:topic, :topic_with_op)
+
+ let(:invite_form) { PageObjects::Pages::InviteForm.new }
+ let(:topic_page) { PageObjects::Pages::Topic.new }
+
+ before do
+ SiteSetting.enable_local_logins_via_email = true
+ SiteSetting.enable_local_logins_via_code = true
+ invite.update!(topics: [topic])
+ Jobs.run_immediately!
+ end
+
+ it "lets an invited person verify their email without choosing a password" do
+ invite_form.open(invite.invite_key)
+
+ expect(invite_form).to have_email_code_request
+ expect(invite_form).to have_introduction
+ expect(invite_form).to have_no_password_field
+
+ invite_form.request_email_code
+ expect(invite_form).to have_email_code_entry
+ expect(invite_form).to have_no_introduction
+ expect(invite_form).to have_progress_steps(completed: 1)
+
+ mail = ActionMailer::Base.deliveries.last
+ expect(mail.to).to contain_exactly(invite.email)
+
+ invite_form.enter_email_code(mail.subject[/\d{6}/])
+ expect(invite_form).to have_account_ready_step
+ expect(invite_form).to have_no_introduction
+ expect(invite_form).to have_progress_steps(completed: 2)
+
+ invite_form.choose_code_signup_username("invited-person")
+ invite_form.continue_code_signup
+
+ expect(page).to have_current_path(topic.relative_url)
+ expect(topic_page).to have_post_number(1)
+ expect(page).to have_css(".header-dropdown-toggle.current-user")
+ end
+end
diff --git a/spec/system/page_objects/pages/invite_form.rb b/spec/system/page_objects/pages/invite_form.rb
index c514625ac61..37ed6a6126f 100644
--- a/spec/system/page_objects/pages/invite_form.rb
+++ b/spec/system/page_objects/pages/invite_form.rb
@@ -35,6 +35,51 @@ module PageObjects
def has_successful_message?
has_css?(".invite-success")
end
+
+ def has_email_code_request?
+ has_css?(".code-login-form__email-step .code-login-form__continue")
+ end
+
+ def has_no_password_field?
+ has_no_field?("new-account-password")
+ end
+
+ def has_introduction?
+ has_css?(".login-welcome-header") && has_css?(".invited-by") && has_css?(".email-message")
+ end
+
+ def has_no_introduction?
+ has_no_css?(".login-welcome-header, .invited-by, .email-message")
+ end
+
+ def has_progress_steps?(completed:)
+ has_css?(".signup-progress-bar__segment", count: 3) &&
+ has_css?(".signup-progress-bar__segment.--completed", count: completed)
+ end
+
+ def request_email_code
+ find(".code-login-form__email-step .code-login-form__continue").click
+ end
+
+ def has_email_code_entry?
+ has_css?(".code-login-form__code-step .d-otp-input")
+ end
+
+ def enter_email_code(code)
+ find(".d-otp-input").fill_in(with: code)
+ end
+
+ def has_account_ready_step?
+ has_css?(".code-login-form__complete-step")
+ end
+
+ def choose_code_signup_username(username)
+ find("#code-login-username").fill_in(with: username)
+ end
+
+ def continue_code_signup
+ find(".code-login-form__continue-to-site").click
+ end
end
end
end