Skip to content

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

FEATURE: Log in with a one-time email code (#40804)

Keegan Georgef4bd916c88f6
diff --git a/app/assets/stylesheets/common/login/_index.scss b/app/assets/stylesheets/common/login/_index.scss
index a56a658078e..e186190c3e5 100644
--- a/app/assets/stylesheets/common/login/_index.scss
+++ b/app/assets/stylesheets/common/login/_index.scss
@@ -1,2 +1,3 @@
+@import "code-login-form";
@import "invite-signup";
@import "omniauth-confirm";
diff --git a/app/assets/stylesheets/common/login/code-login-form.scss b/app/assets/stylesheets/common/login/code-login-form.scss
new file mode 100644
index 00000000000..9389874c40c
--- /dev/null
+++ b/app/assets/stylesheets/common/login/code-login-form.scss
@@ -0,0 +1,54 @@
+.code-login-form {
+ display: flex;
+ flex-direction: column;
+ gap: 1em;
+
+ &__email-step {
+ display: flex;
+ flex-direction: column;
+ gap: 1em;
+ }
+
+ &__code-step,
+ &__second-factor-step {
+ display: flex;
+ flex-direction: column;
+ align-items: flex-start;
+ gap: 1em;
+ }
+
+ &__title {
+ margin: 0;
+ }
+
+ &__instructions {
+ margin: 0;
+ color: var(--primary-high);
+ }
+
+ &__error {
+ color: var(--danger);
+
+ &:empty {
+ display: none;
+ }
+ }
+
+ &__notice {
+ margin: 0;
+ color: var(--success);
+ }
+
+ &__actions {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 0.5em;
+ }
+
+ &__email-actions {
+ display: flex;
+ flex-wrap: wrap;
+ align-items: center;
+ gap: 0.5em;
+ }
+}
diff --git a/app/controllers/admin/email_templates_controller.rb b/app/controllers/admin/email_templates_controller.rb
index b7e1a67979c..00f08044b9c 100644
--- a/app/controllers/admin/email_templates_controller.rb
+++ b/app/controllers/admin/email_templates_controller.rb
@@ -14,6 +14,7 @@ class Admin::EmailTemplatesController < Admin::AdminController
custom_invite_forum_mailer
custom_invite_mailer
download_backup_mailer
+ email_login_code_mailer
invite_forum_mailer
invite_mailer
invite_password_instructions
diff --git a/app/controllers/session_controller.rb b/app/controllers/session_controller.rb
index d20d56a9551..3200b8773b6 100644
--- a/app/controllers/session_controller.rb
+++ b/app/controllers/session_controller.rb
@@ -3,7 +3,10 @@
class SessionController < ApplicationController
before_action :check_local_login_allowed,
only: %i[create forgot_password passkey_challenge passkey_login]
+ before_action :ensure_login_code_allowed, only: %i[create_login_code verify_login_code]
before_action :rate_limit_login, only: %i[create email_login]
+ before_action :rate_limit_login_code_request, only: %i[create_login_code]
+ before_action :rate_limit_login_code_verify, only: %i[verify_login_code]
skip_before_action :redirect_to_login_if_required
skip_before_action :redirect_to_profile_if_required
skip_before_action :preload_json,
@@ -13,7 +16,7 @@ class SessionController < ApplicationController
skip_before_action :check_xhr, only: %i[second_factor_auth_show]
allow_in_readonly_mode :email_login
- allow_in_staff_writes_only_mode :create, :forgot_password
+ allow_in_staff_writes_only_mode :create, :forgot_password, :create_login_code, :verify_login_code
ACTIVATE_USER_KEY = "activate_user"
FORGOT_PASSWORD_EMAIL_LIMIT_PER_DAY = 6
@@ -491,6 +494,34 @@ class SessionController < ApplicationController
render json: { error: I18n.t("email_login.invalid_token", base_url: Discourse.base_url) }
end
+ def create_login_code
+ expires_now
+
+ # Render the same response as a successful request so bots can't probe
+ # the endpoint. Sending no email at all for honeypot failures matches
+ # the behavior for emails we refuse to deliver to.
+ return render json: success_json if login_code_honeypot_fails?
+
+ EmailLoginCode::Request.call(service_params) do |result|
+ on_success { render json: success_json }
+ on_failed_contract do |contract|
+ render json: failed_json.merge(errors: contract.errors.full_messages), status: :bad_request
+ end
+ end
+ end
+
+ def verify_login_code
+ expires_now
+
+ EmailLoginCode::Verify.call(service_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
+ end
+ on_failure { render json: invalid_login_code }
+ end
+ end
+
def one_time_password
@otp_username = otp_username = Discourse.redis.get "otp_#{params[:token]}"
@@ -820,6 +851,99 @@ class SessionController < ApplicationController
SiteSetting.must_approve_users? && !user.approved? && !user.admin?
end
+ def ensure_login_code_allowed
+ raise Discourse::NotFound if !SiteSetting.enable_local_logins_via_code
+ # Code login is a delivery variant of email login, so it also requires
+ # `enable_local_logins_via_email` (checked via `check_login_via_email`).
+ check_local_login_allowed(check_login_via_email: true)
+ redirect_to path("/") if current_user
+ end
+
+ def rate_limit_login_code_request
+ 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
+ if email.present?
+ RateLimiter.new(
+ nil,
+ "login-code-email-#{Digest::SHA256.hexdigest(email)}",
+ 3,
+ 1.hour,
+ ).performed!
+ end
+ end
+
+ def rate_limit_login_code_verify
+ RateLimiter.new(nil, "login-code-verify-hour-#{request.remote_ip}", 30, 1.hour).performed!
+ RateLimiter.new(nil, "login-code-verify-min-#{request.remote_ip}", 6, 1.minute).performed!
+ end
+
+ def login_code_honeypot_fails?
+ return false if is_api?
+ params[:password_confirmation] != honeypot_value ||
+ params[:challenge] != challenge_value.try(:reverse)
+ end
+
+ def process_verified_login_code(matched_user)
+ if matched_user &&
+ (matched_user.totp_or_backup_codes_enabled? || matched_user.security_keys_enabled?)
+ if missing_second_factor_params?
+ return render json: login_code_second_factor_info(matched_user)
+ end
+
+ rate_limit_second_factor!(matched_user)
+ if !authenticate_second_factor(matched_user).ok
+ return render json: @second_factor_failure_payload
+ end
+ end
+
+ EmailLoginCode::Redeem.call(service_params) do |result|
+ on_success { |user:| login_with_login_code(user) }
+ on_failure { render json: invalid_login_code }
+ end
+ end
+
+ def login_code_second_factor_info(user)
+ response = { second_factor_required: true }
+
+ if user.totp_or_backup_codes_enabled?
+ response[:totp_enabled] = user.totp_enabled?
+ response[:backup_codes_enabled] = user.backup_codes_enabled?
+ end
+
+ if user.security_keys_enabled?
+ DiscourseWebauthn.stage_challenge(user, server_session)
+ response.merge!(
+ DiscourseWebauthn.allowed_credentials(user, server_session).merge(
+ security_key_required: true,
+ ),
+ )
+ end
+
+ response
+ end
+
+ def missing_second_factor_params?
+ params[:second_factor_token].blank?
+ end
+
+ def login_with_login_code(user)
+ 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
+ else
+ login(user)
+ end
+ end
+
+ def invalid_login_code
+ { error: I18n.t("email_login_code.invalid_code") }
+ end
+
def invalid_credentials
render json: { error: I18n.t("login.incorrect_username_email_or_password") }
end
diff --git a/app/jobs/regular/send_email_login_code.rb b/app/jobs/regular/send_email_login_code.rb
new file mode 100644
index 00000000000..5e7c119676d
--- /dev/null
+++ b/app/jobs/regular/send_email_login_code.rb
@@ -0,0 +1,16 @@
+# frozen_string_literal: true
+
+module Jobs
+ class SendEmailLoginCode < ::Jobs::Base
+ sidekiq_options queue: "critical"
+
+ def execute(args)
+ raise Discourse::InvalidParameters.new(:to_address) if args[:to_address].blank?
+ raise Discourse::InvalidParameters.new(:code) if args[:code].blank?
+ return if !SiteSetting.enable_local_logins_via_code
+
+ message = EmailLoginCodeMailer.send_code(args[:to_address], args[:code])
+ Email::Sender.new(message, :email_login_code).send
+ end
+ end
+end
diff --git a/app/jobs/scheduled/clean_up_email_login_codes.rb b/app/jobs/scheduled/clean_up_email_login_codes.rb
new file mode 100644
index 00000000000..7440ff03c83
--- /dev/null
+++ b/app/jobs/scheduled/clean_up_email_login_codes.rb
@@ -0,0 +1,11 @@
+# frozen_string_literal: true
+
+module Jobs
+ class CleanUpEmailLoginCodes < ::Jobs::Scheduled
+ every 1.day
+
+ def execute(args)
+ EmailLoginCode.where("expires_at < ?", 1.day.ago).delete_all
+ end
+ end
+end
diff --git a/app/mailers/email_login_code_mailer.rb b/app/mailers/email_login_code_mailer.rb
new file mode 100644
index 00000000000..867633e8328
--- /dev/null
+++ b/app/mailers/email_login_code_mailer.rb
@@ -0,0 +1,16 @@
+# frozen_string_literal: true
+
+class EmailLoginCodeMailer < ActionMailer::Base
+ include Email::BuildEmailHelper
+
+ layout "email_template"
+
+ def send_code(email, code)
+ build_email(
+ email,
+ template: "email_login_code_mailer",
+ code: code,
+ minutes: EmailLoginCode::VALID_FOR.in_minutes.to_i,
+ )
+ end
+end
diff --git a/app/models/email_login_code.rb b/app/models/email_login_code.rb
new file mode 100644
index 00000000000..d304a84644d
--- /dev/null
+++ b/app/models/email_login_code.rb
@@ -0,0 +1,100 @@
+# frozen_string_literal: true
+
+class EmailLoginCode < ActiveRecord::Base
+ class CodeAccessError < StandardError
+ end
+
+ CODE_LENGTH = 6
+ MAX_ATTEMPTS = 5
+ VALID_FOR = 10.minutes
+
+ validates :email, :code_hash, presence: true
+
+ scope :active,
+ -> do
+ where(consumed_at: nil).where("expires_at > ?", Time.zone.now).where(
+ "attempts < ?",
+ MAX_ATTEMPTS,
+ )
+ end
+ scope :for_email, ->(email) { where("lower(email) = ?", email.downcase) }
+
+ def self.generate!(email:)
+ email = email.downcase
+
+ code = SecureRandom.random_number(10**CODE_LENGTH).to_s.rjust(CODE_LENGTH, "0")
+
+ record = nil
+ transaction do
+ where("lower(email) = ?", email).delete_all
+ record = create!(email: email, code_hash: hash_code(code), expires_at: VALID_FOR.from_now)
+ end
+
+ record.instance_variable_set(:@code, code)
+ record
+ end
+
+ def self.hash_code(code)
+ # Keyed with the server secret so a database snapshot alone can't be used
+ # to enumerate the small (6-digit) code space offline.
+ OpenSSL::HMAC.hexdigest("SHA256", GlobalSetting.safe_secret_key_base, code)
+ end
+
+ def code
+ raise CodeAccessError.new if @code.blank?
+
+ @code
+ end
+
+ # Verifies a submitted code against this record. Burns one attempt up front
+ # (atomically, so parallel guesses cannot exceed MAX_ATTEMPTS) and refunds it
+ # on success so a pending second factor round-trip can verify again.
+ def verify(submitted)
+ return false if consumed_at.present? || expires_at <= Time.zone.now
+
+ attempts = DB.query_single(<<~SQL, id: id, max: MAX_ATTEMPTS).first
+ UPDATE email_login_codes
+ SET attempts = attempts + 1
+ WHERE id = :id AND attempts < :max
+ RETURNING attempts
+ SQL
+ return false if attempts.nil?
+ self.attempts = attempts
+
+ if ActiveSupport::SecurityUtils.secure_compare(code_hash, self.class.hash_code(submitted))
+ update_columns(attempts: 0)
+ true
+ else
+ false
+ end
+ end
+
+ # Atomically marks the code consumed. Returns true only for the caller that
+ # wins the race, so two concurrent redemptions of the same code can't both
+ # succeed.
+ def consume!
+ now = Time.zone.now
+ won = self.class.where(id: id, consumed_at: nil).update_all(consumed_at: now) == 1
+ self.consumed_at = now if won
+ won
+ end
+end
+
+# == Schema Information
+#
+# Table name: email_login_codes
+#
+# id :bigint not null, primary key
+# attempts :integer default(0), not null
+# code_hash :string not null
+# consumed_at :datetime
+# email :string not null
+# expires_at :datetime not null
+# created_at :datetime not null
+# updated_at :datetime not null
+#
+# Indexes
+#
+# index_email_login_codes_on_expires_at (expires_at)
+# index_email_login_codes_on_lower_email (lower((email)::text))
+#
diff --git a/app/services/email_login_code/redeem.rb b/app/services/email_login_code/redeem.rb
new file mode 100644
index 00000000000..57f2250af55
--- /dev/null
+++ b/app/services/email_login_code/redeem.rb
@@ -0,0 +1,41 @@
+# frozen_string_literal: true
+
+class EmailLoginCode::Redeem
+ include Service::Base
+
+ params base_class: EmailLoginCode::Verify::Contract
+
+ model :login_code
+ policy :code_matches
+ model :user, :fetch_user
+ step :consume_code
+ only_if(:user_requires_activation?) { step :activate_user }
+
+ private
+
+ 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_user(params:)
+ User::Action::FindByEmail.call(email: params.email)
+ 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 user_requires_activation?(user:)
+ !user.active?
+ end
+
+ def activate_user(user:)
+ user.activate
+ end
+end
diff --git a/app/services/email_login_code/request.rb b/app/services/email_login_code/request.rb
new file mode 100644
index 00000000000..87a6a85be02
--- /dev/null
+++ b/app/services/email_login_code/request.rb
@@ -0,0 +1,54 @@
+# frozen_string_literal: true
+
+class EmailLoginCode::Request
+ include Service::Base
+
+ params do
+ attribute :email, :string
+
+ before_validation { self.email = email.to_s.strip.downcase }
+
+ validates :email,
+ presence: true,
+ length: {
+ maximum: 513,
+ },
+ format: {
+ with: EmailAddressValidator.email_regex,
+ }
+ end
+
+ model :user, optional: true
+
+ # 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
+ model :login_code, :generate_login_code
+ step :send_login_code_email
+ end
+
+ private
+
+ def fetch_user(params:)
+ User::Action::FindByEmail.call(email: params.email)
+ end
+
+ def existing_account?(user:)
+ user.present?
+ end
+
+ def trigger_before_email_login(user:)
+ DiscourseEvent.trigger(:before_email_login, user)
+ end
+
+ def generate_login_code(params:)
+ EmailLoginCode.generate!(email: params.email)
+ 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/app/services/email_login_code/verify.rb b/app/services/email_login_code/verify.rb
new file mode 100644
index 00000000000..264c60cabc5
--- /dev/null
+++ b/app/services/email_login_code/verify.rb
@@ -0,0 +1,36 @@
+# frozen_string_literal: true
+
+class EmailLoginCode::Verify
+ include Service::Base
+
+ params do
+ attribute :email, :string
+ attribute :code, :string
+
+ before_validation do
+ self.email = email.to_s.strip.downcase
+ self.code = code.to_s.strip
+ end
+
+ validates :email, presence: true, format: { with: EmailAddressValidator.email_regex }
+ validates :code, presence: true, format: { with: /\A\d{#{EmailLoginCode::CODE_LENGTH}}\z/o }
+ end
+
+ model :login_code
+ policy :code_matches
+ model :user, optional: true
+
+ private
+
+ 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_user(params:)
+ User::Action::FindByEmail.call(email: params.email)
+ end
+end
diff --git a/app/services/user/action/find_by_email.rb b/app/services/user/action/find_by_email.rb
new file mode 100644
index 00000000000..cddd995062f
--- /dev/null
+++ b/app/services/user/action/find_by_email.rb
@@ -0,0 +1,25 @@
+# frozen_string_literal: true
+
+class User::Action::FindByEmail < Service::ActionBase
+ option :email
+
+ def call
+ users.with_email(email).first || normalized_email_match
+ end
+
+ private
+
+ def users
+ User.real.where(staged: false)
+ end
+
+ def normalized_email_match
+ return if !SiteSetting.normalize_emails
+
+ local_part, domain = email.split("@", 2)
+ return if local_part.blank? || domain.blank?
+
+ normalized_email = "#{local_part.gsub(".", "").gsub(/\+.*/, "")}@#{domain}"
+ users.joins(:user_emails).where(user_emails: { normalized_email: normalized_email }).first
+ end
+end
diff --git a/config/locales/client.en.yml b/config/locales/client.en.yml
index 58ca03c3e19..76523080a48 100644
--- a/config/locales/client.en.yml
+++ b/config/locales/client.en.yml
@@ -2917,6 +2917,19 @@ en:
logging_in_as: Logging in as %{email}
confirm_button: Finish Login
+ code_login:
+ email_label: "Email"
+ continue_button: "Continue"
+ check_your_email: "Check your email"
+ code_instructions: "We sent a 6-digit code to <b>%{email}</b>. Enter it below to continue."
+ verify_button: "Continue"
+ resend: "Resend code"
+ resend_countdown: "Resend code (%{count}s)"
+ code_resent: "We sent a new code."
+ 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"
+
login:
header_title: "Welcome back"
title: "Log In"
diff --git a/config/locales/server.en.yml b/config/locales/server.en.yml
index 63058c00e1f..3389c6f9427 100644
--- a/config/locales/server.en.yml
+++ b/config/locales/server.en.yml
@@ -1055,6 +1055,9 @@ en:
invalid_token: 'Oops! The link you used no longer works. You can <a href="%{base_url}/login">Log In</a> now. If you forgot your password, you can <a href="%{base_url}/password-reset">request a link</a> to reset it.'
title: "Email login"
+ email_login_code:
+ invalid_code: "That code is incorrect or has expired. Request a new code and try again."
+
user_auth_tokens:
browser:
chrome: "Google Chrome"
@@ -2135,6 +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'."
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."
@@ -2959,6 +2963,8 @@ en:
discourse_connect_url_is_empty: "You must set a 'discourse connect url' before enabling this setting."
discourse_connect_secret_is_too_short: "You must set a 'discourse connect secret' of at least 10 characters before enabling this setting."
enable_local_logins_disabled: "You must first enable 'enable local logins' before enabling this setting."
+ enable_local_logins_via_email_disabled: "You must first enable 'enable local logins via email' before enabling this setting."
+ discourse_connect_enabled: "You must disable 'enable discourse connect' before enabling this setting."
min_username_length_exists: "You cannot set 'min username length' above the shortest username (%{username})."
min_group_name_length_exists: "You cannot set 'min username length' above the shortest group name (%{group_name})."
min_username_length_range: "You cannot set 'min username length' above 'max username length'."
@@ -3417,6 +3423,16 @@ en:
If you want to continue receiving email updates, you may ignore this email.
+ email_login_code_mailer:
+ title: "Email Login Code Mailer"
+ subject_template: "%{code} is your login code"
+ text_body_template: |
+ Use this code to finish logging in to %{site_name}:
+
+ ## %{code}
+
+ This code expires in %{minutes} minutes. If you didn't request it, you can safely ignore this email.
+
invite_mailer:
title: "Invite Mailer"
subject_template: "%{inviter_name} invited you to '%{topic_title}' on %{site_domain_name}"
diff --git a/config/routes.rb b/config/routes.rb
index 25e15019bae..4f81f49a8ce 100644
--- a/config/routes.rb
+++ b/config/routes.rb
@@ -574,6 +574,8 @@ Discourse::Application.routes.draw do
get "session/hp" => "session#get_honeypot_value"
get "session/email-login/:token" => "session#email_login_info"
post "session/email-login/:token" => "session#email_login"
+ post "session/login-code" => "session#create_login_code"
+ post "session/login-code/verify" => "session#verify_login_code"
get "session/otp/:token" => "session#one_time_password", :constraints => { token: /[0-9a-f]+/ }
post "session/otp/:token" => "session#one_time_password", :constraints => { token: /[0-9a-f]+/ }
get "session/2fa" => "session#second_factor_auth_show"
diff --git a/config/site_settings.yml b/config/site_settings.yml
index d4dedae9930..6095ae6e4ae 100644
--- a/config/site_settings.yml
+++ b/config/site_settings.yml
@@ -665,6 +665,12 @@ login:
default: true
validator: "EnableLocalLoginsViaEmailValidator"
area: "login"
+ enable_local_logins_via_code:
+ client: true
+ default: false
+ hidden: true
+ validator: "EnableLocalLoginsViaCodeValidator"
+ area: "login"
enable_passkeys:
client: true
default: true
diff --git a/db/migrate/20260610205840_create_email_login_codes.rb b/db/migrate/20260610205840_create_email_login_codes.rb
new file mode 100644
index 00000000000..b83d9f654c5
--- /dev/null
+++ b/db/migrate/20260610205840_create_email_login_codes.rb
@@ -0,0 +1,16 @@
+# frozen_string_literal: true
+class CreateEmailLoginCodes < ActiveRecord::Migration[8.0]
+ def change
+ create_table :email_login_codes do |t|
+ t.string :email, null: false
+ t.string :code_hash, null: false
+ t.integer :attempts, null: false, default: 0
+ t.datetime :expires_at, null: false
+ t.datetime :consumed_at
+ t.timestamps
+ end
+
+ add_index :email_login_codes, "lower(email)"
+ add_index :email_login_codes, :expires_at
+ end
+end
diff --git a/db/structure.sql b/db/structure.sql
index 94a988fea4f..cde806f01a2 100644
--- a/db/structure.sql
+++ b/db/structure.sql
@@ -4808,6 +4808,41 @@ CREATE SEQUENCE public.email_change_requests_id_seq
ALTER SEQUENCE public.email_change_requests_id_seq OWNED BY public.email_change_requests.id;
+--
+-- Name: email_login_codes; Type: TABLE; Schema: public; Owner: -
+--
+
+CREATE TABLE public.email_login_codes (
+ id bigint NOT NULL,
+ email character varying NOT NULL,
+ code_hash character varying NOT NULL,
+ attempts integer DEFAULT 0 NOT NULL,
+ expires_at timestamp(6) without time zone NOT NULL,
+ consumed_at timestamp(6) without time zone,
+ created_at timestamp(6) without time zone NOT NULL,
+ updated_at timestamp(6) without time zone NOT NULL
+);
+
+
+--
+-- Name: email_login_codes_id_seq; Type: SEQUENCE; Schema: public; Owner: -
+--
+
+CREATE SEQUENCE public.email_login_codes_id_seq
+ START WITH 1
+ INCREMENT BY 1
+ NO MINVALUE
+ NO MAXVALUE
+ CACHE 1;
+
+
+--
+-- Name: email_login_codes_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: -
+--
+
+ALTER SEQUENCE public.email_login_codes_id_seq OWNED BY public.email_login_codes.id;
+
+
--
-- Name: email_logs; Type: TABLE; Schema: public; Owner: -
--
@@ -12672,6 +12707,13 @@ ALTER TABLE ONLY public.drafts ALTER COLUMN id SET DEFAULT nextval('public.draft
ALTER TABLE ONLY public.email_change_requests ALTER COLUMN id SET DEFAULT nextval('public.email_change_requests_id_seq'::regclass);
+--
+-- Name: email_login_codes id; Type: DEFAULT; Schema: public; Owner: -
+--
+
+ALTER TABLE ONLY public.email_login_codes ALTER COLUMN id SET DEFAULT nextval('public.email_login_codes_id_seq'::regclass);
+
+
--
-- Name: email_logs id; Type: DEFAULT; Schema: public; Owner: -
--
@@ -14950,6 +14992,14 @@ ALTER TABLE ONLY public.email_change_requests
ADD CONSTRAINT email_change_requests_pkey PRIMARY KEY (id);
+--
+-- Name: email_login_codes email_login_codes_pkey; Type: CONSTRAINT; Schema: public; Owner: -
+--
+
+ALTER TABLE ONLY public.email_login_codes
+ ADD CONSTRAINT email_login_codes_pkey PRIMARY KEY (id);
+
+
--
-- Name: email_logs email_logs_pkey; Type: CONSTRAINT; Schema: public; Owner: -
--
@@ -18523,6 +18573,20 @@ CREATE UNIQUE INDEX index_drafts_on_user_id_and_draft_key ON public.drafts USING
CREATE INDEX index_email_change_requests_on_user_id ON public.email_change_requests USING btree (user_id);
+--
+-- Name: index_email_login_codes_on_expires_at; Type: INDEX; Schema: public; Owner: -
+--
+
+CREATE INDEX index_email_login_codes_on_expires_at ON public.email_login_codes USING btree (expires_at);
+
+
+--
+-- Name: index_email_login_codes_on_lower_email; Type: INDEX; Schema: public; Owner: -
+--
+
+CREATE INDEX index_email_login_codes_on_lower_email ON public.email_login_codes USING btree (lower((email)::text));
+
+
--
-- Name: index_email_logs_on_bounce_key; Type: INDEX; Schema: public; Owner: -
--
@@ -21915,6 +21979,7 @@ SET search_path TO "$user", public;
INSERT INTO "schema_migrations" (version) VALUES
('20260617053237'),
('20260612092612'),
+('20260610205840'),
('20260610075829'),
('20260609050938'),
('20260607161322'),
diff --git a/frontend/discourse/app/components/code-login-form.gjs b/frontend/discourse/app/components/code-login-form.gjs
new file mode 100644
index 00000000000..5cb40305d79
--- /dev/null
+++ b/frontend/discourse/app/components/code-login-form.gjs
@@ -0,0 +1,423 @@
+import Component from "@glimmer/component";
+import { tracked } from "@glimmer/tracking";
+import { hash } from "@ember/helper";
+import { action } from "@ember/object";
+import { cancel } from "@ember/runloop";
+import { trustHTML } from "@ember/template";
+import Form from "discourse/components/form";
+import SecondFactorForm from "discourse/components/second-factor-form";
+import SecurityKeyForm from "discourse/components/security-key-form";
+import { ajax } from "discourse/lib/ajax";
+import { popupAjaxError } from "discourse/lib/ajax-error";
+import cookie, { removeCookie } from "discourse/lib/cookie";
+import escape from "discourse/lib/escape";
+import getURL from "discourse/lib/get-url";
+import discourseLater from "discourse/lib/later";
+import { emailValid } from "discourse/lib/utilities";
+import { getWebauthnCredential } from "discourse/lib/webauthn";
+import { 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 { i18n } from "discourse-i18n";
+
+const RESEND_COOLDOWN_SECONDS = 30;
+
+export default class CodeLoginForm extends Component {
+ @tracked step = "email";
+ @tracked email = this.args.initialEmail ?? "";
+ @tracked verifying = false;
+ @tracked codeError;
+ @tracked notice;
+ @tracked resendCooldown = 0;
+ @tracked otpGeneration = 0;
+
+ @tracked secondFactorMethod = SECOND_FACTOR_METHODS.TOTP;
+ @tracked secondFactorToken;
+ @tracked securityKeyCredential;
+ @tracked totpEnabled = false;
+ @tracked backupCodesEnabled = false;
+ @tracked securityKeyRequired = false;
+ @tracked securityKeyChallenge;
+ @tracked securityKeyAllowedCredentialIds;
+
+ code = "";
+ #cooldownTimer;
+
+ willDestroy() {
+ super.willDestroy(...arguments);
+ cancel(this.#cooldownTimer);
+ }
+
+ get isEmailStep() {
+ return this.step === "email";
+ }
+
+ get isCodeStep() {
+ return this.step === "code";
+ }
+
+ get isSecondFactorStep() {
+ return this.step === "second-factor";
+ }
+
+ // Whether a second factor other than the security key is available to fall
+ // back to (TOTP or backup codes).
+ get otherSecondFactorAllowed() {
+ return this.totpEnabled || this.backupCodesEnabled;
+ }
+
+ // Re-rendering DOtp with a fresh identity is the only way to clear it
+ get otpGenerationArray() {
+ return [this.otpGeneration];
+ }
+
+ get codeInstructions() {
+ return trustHTML(
+ i18n("code_login.code_instructions", { email: escape(this.email) })
+ );
+ }
+
+ get resendLabel() {
+ if (this.resendCooldown > 0) {
+ return i18n("code_login.resend_countdown", {
+ count: this.resendCooldown,
+ });
+ }
+ return i18n("code_login.resend");
+ }
+
+ get resendDisabled() {
+ return this.resendCooldown > 0 || this.verifying;
+ }
+
+ @action
+ validateEmail(name, value, { addError }) {
+ if (value && !emailValid(value)) {
+ addError("email", {
+ title: i18n("code_login.email_label"),
+ message: i18n("user.email.invalid"),
+ });
+ }
+ }
+
+ @action
+ async submitEmail(data) {
+ this.email = data.email.trim();
+ await this.sendCode();
+ }
+
+ @action
+ async resendCode() {
+ if (this.resendDisabled) {
+ return;
+ }
+
+ if (await this.sendCode()) {
+ this.notice = i18n("code_login.code_resent");
+ this.code = "";
+ this.otpGeneration++;
+ }
+ }
+
+ @action
+ changeEmail() {
+ cancel(this.#cooldownTimer);
+ this.resendCooldown = 0;
+ this.code = "";
+ this.codeError = null;
+ this.notice = null;
+ this.otpGeneration++;
+ this.step = "email";
+ }
+
+ @action
+ codeChanged(value) {
+ this.code = value;
+ this.codeError = null;
+ }
+
+ @action
+ async verifyCode(code) {
+ if (typeof code === "string") {
+ this.code = code;
+ }
+
+ if (this.code.length < 6 || this.verifying) {
+ return;
+ }
+
+ this.verifying = true;
+ this.codeError = null;
+ this.notice = null;
+
+ const data = {
+ email: this.email,
+ code: this.code,
+ timezone: moment.tz.guess(),
+ };
+
+ if (this.isSecondFactorStep) {
+ data.second_factor_token =
+ this.securityKeyCredential || this.secondFactorToken;
+ data.second_factor_method = this.secondFactorMethod;
+ }
+
+ try {
+ const result = await ajax("/session/login-code/verify", {
+ type: "POST",
+ data,
+ });
+
+ if (result?.second_factor_required && !this.isSecondFactorStep) {
+ this.totpEnabled = result.totp_enabled;
+ this.backupCodesEnabled = result.backup_codes_enabled;
+ this.securityKeyRequired = result.security_key_required;
+ this.securityKeyChallenge = result.challenge;
+ this.securityKeyAllowedCredentialIds = result.allowed_credential_ids;
+ this.secondFactorMethod = result.security_key_required
+ ? SECOND_FACTOR_METHODS.SECURITY_KEY
+ : SECOND_FACTOR_METHODS.TOTP;
+ this.step = "second-factor";
+ return;
+ }
+
+ if (result?.error) {
+ if (this.isSecondFactorStep) {
+ this.securityKeyCredential = null;
+ this.codeError = result.error;
+ } else {
+ this.codeError = result.error;
+ this.code = "";
+ this.otpGeneration++;
+ }
+ 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("/"));
+ }
+ } catch (e) {
+ popupAjaxError(e);
+ } finally {
+ this.verifying = false;
+ }
+ }
+
+ @action
+ submitSecondFactor() {
+ this.securityKeyCredential = null;
+ return this.verifyCode();
+ }
+
+ @action
+ secondFactorTokenChanged(value) {
+ this.secondFactorToken = value;
+ this.codeError = null;
+ }
+
+ @action
+ setShowSecurityKey(value) {
+ this.securityKeyRequired = value;
+ }
+
+ @action
+ setSecondFactorMethod(value) {
+ this.secondFactorMethod = value;
+ }
+
+ @action
+ authenticateSecurityKey() {
+ getWebauthnCredential(
+ this.securityKeyChallenge,
+ this.securityKeyAllowedCredentialIds,
+ (credentialData) => {
+ this.securityKeyCredential = credentialData;
+ this.verifyCode();
+ },
+ (errorMessage) => {
+ this.codeError = errorMessage;
+ }
+ );
+ }
+
+ async sendCode() {
+ this.codeError = null;
+ this.notice = null;
+
+ try {
+ const honeypot = await ajax("/session/hp.json");
+ await ajax("/session/login-code", {
+ type: "POST",
+ data: {
+ email: this.email,
+ password_confirmation: honeypot.value,
+ challenge: honeypot.challenge.split("").reverse().join(""),
+ },
+ });
+
+ this.step = "code";
+ this.startResendCooldown();
+ return true;
+ } catch (e) {
+ popupAjaxError(e);
+ return false;
+ }
+ }
+
+ startResendCooldown() {
+ cancel(this.#cooldownTimer);
+ this.resendCooldown = RESEND_COOLDOWN_SECONDS;
+ this.tickCooldown();
+ }
+
+ tickCooldown() {
+ if (this.resendCooldown <= 0) {
+ return;
+ }
+
+ this.#cooldownTimer = discourseLater(() => {
+ this.resendCooldown -= 1;
+ this.tickCooldown();
+ }, 1000);
+ }
+
+ <template>
+ <div class="code-login-form">
+ {{#if this.isEmailStep}}
+ <Form
+ @data={{hash email=this.email}}
+ @onSubmit={{this.submitEmail}}
+ class="code-login-form__email-step"
+ as |form|
+ >
+ <form.Field
+ @name="email"
+ @title={{i18n "code_login.email_label"}}
+ @type="input-email"
+ @validation="required"
+ @validate={{this.validateEmail}}
+ @format="full"
+ as |field|
+ >
+ <field.Control
+ autofocus="autofocus"
+ autocomplete="username email"
+ />
+ </form.Field>
+
+ <div class="code-login-form__email-actions">
+ <form.Submit
+ @label="code_login.continue_button"
+ class="btn-primary code-login-form__continue"
+ />
+
+ {{#if @onUsePassword}}
+ <DButton
+ @action={{@onUsePassword}}
+ @label="code_login.use_password_instead"
+ class="btn-flat code-login-form__password-toggle"
+ />
+ {{/if}}
+ </div>
+ </Form>
+ {{else if this.isCodeStep}}
+ <div class="code-login-form__code-step">
+ <h2 class="code-login-form__title">
+ {{i18n "code_login.check_your_email"}}
+ </h2>
+ <p class="code-login-form__instructions">
+ {{this.codeInstructions}}
+ </p>
+
+ {{#each this.otpGenerationArray as |generation|}}
+ <DOtp
+ @onChange={{this.codeChanged}}
+ @onFill={{this.verifyCode}}
+ id="code-login-otp-{{generation}}"
+ />
+ {{/each}}
+
+ <div class="code-login-form__error" aria-live="polite" role="alert">
+ {{this.codeError}}
+ </div>
+
+ {{#if this.notice}}
+ <p class="code-login-form__notice" aria-live="polite">
+ {{this.notice}}
+ </p>
+ {{/if}}
+
+ <DButton
+ @action={{this.verifyCode}}
+ @label="code_login.verify_button"
+ @isLoading={{this.verifying}}
+ type="submit"
+ class="btn-primary code-login-form__verify"
+ />
+
+ <div class="code-login-form__actions">
+ <DButton
+ @action={{this.resendCode}}
+ @translatedLabel={{this.resendLabel}}
+ @disabled={{this.resendDisabled}}
+ class="btn-flat code-login-form__resend"
+ />
+ <DButton
+ @action={{this.changeEmail}}
+ @label="code_login.use_different_email"
+ class="btn-flat code-login-form__change-email"
+ />
+ </div>
+ </div>
+ {{else}}
+ <div class="code-login-form__second-factor-step">
+ {{#if this.codeError}}
+ <div class="code-login-form__error" role="alert">
+ {{this.codeError}}
+ </div>
+ {{/if}}
+
+ {{#if this.securityKeyRequired}}
+ <SecurityKeyForm
+ @setShowSecurityKey={{this.setShowSecurityKey}}
+ @setSecondFactorMethod={{this.setSecondFactorMethod}}
+ @backupEnabled={{this.backupCodesEnabled}}
+ @totpEnabled={{this.totpEnabled}}
+ @otherMethodAllowed={{this.otherSecondFactorAllowed}}
+ @action={{this.authenticateSecurityKey}}
+ />
+ {{else}}
+ <SecondFactorForm
+ @secondFactorMethod={{this.secondFactorMethod}}
+ @secondFactorToken={{this.secondFactorToken}}
+ @backupEnabled={{this.backupCodesEnabled}}
+ @totpEnabled={{this.totpEnabled}}
+ @isLogin={{true}}
+ >
+ <DSecondFactorInput
+ @onChange={{this.secondFactorTokenChanged}}
+ @secondFactorMethod={{this.secondFactorMethod}}
+ value={{this.secondFactorToken}}
+ />
+ </SecondFactorForm>
+
+ <DButton
+ @action={{this.submitSecondFactor}}
+ @label="email_login.confirm_button"
+ @isLoading={{this.verifying}}
+ type="submit"
+ class="btn-primary code-login-form__verify"
+ />
+ {{/if}}
+ </div>
+ {{/if}}
+ </div>
+ </template>
+}
diff --git a/frontend/discourse/app/components/local-login-form.gjs b/frontend/discourse/app/components/local-login-form.gjs
index b6b3fa49456..36dd77287dc 100644
--- a/frontend/discourse/app/components/local-login-form.gjs
+++ b/frontend/discourse/app/components/local-login-form.gjs
@@ -131,6 +131,12 @@ export default class LocalLoginForm extends Component {
this.args.login();
}
+ @action
+ showCodeLogin(event) {
+ event?.preventDefault();
+ this.args.onShowCodeLogin();
+ }
+
@action
handleForgotPassword(event) {
event?.preventDefault();
@@ -192,15 +198,26 @@ export default class LocalLoginForm extends Component {
{{i18n "login.email_placeholder"}}
</label>
{{#if @canLoginLocalWithEmail}}
- <a
- href
- class={{if @loginName "" "no-login-filled"}}
- tabindex="3"
- id="email-login-link"
- {{on "click" this.emailLogin}}
- >
- {{i18n "email_login.login_link"}}
- </a>
+ {{#if @onShowCodeLogin}}
+ <a
+ href
+ tabindex="3"
+ id="one-time-code-link"
+ {{on "click" this.showCodeLogin}}
+ >
+ {{i18n "code_login.email_me_code"}}
+ </a>
+ {{else}}
+ <a
+ href
+ class={{if @loginName "" "no-login-filled"}}
+ tabindex="3"
+ id="email-login-link"
+ {{on "click" this.emailLogin}}
+ >
+ {{i18n "email_login.login_link"}}
+ </a>
+ {{/if}}
{{/if}}
</div>
<div class="input-group">
diff --git a/frontend/discourse/app/controllers/login.js b/frontend/discourse/app/controllers/login.js
index 89c1853562e..d666791b767 100644
--- a/frontend/discourse/app/controllers/login.js
+++ b/frontend/discourse/app/controllers/login.js
@@ -49,12 +49,21 @@ export default class LoginPageController extends Controller {
@tracked secondFactorToken;
@tracked flash;
@tracked flashType;
+ @tracked showCodeLoginForm = false;
@computed("siteSettings.enable_local_logins")
get canLoginLocal() {
return this.siteSettings.enable_local_logins;
}
+ get canUseCodeLogin() {
+ return (
+ this.siteSettings.enable_local_logins_via_code &&
+ this.siteSettings.enable_local_logins_via_email &&
+ this.siteSettings.enable_local_logins
+ );
+ }
+
@computed("siteSettings.enable_local_logins_via_email")
get canLoginLocalWithEmail() {
return this.siteSettings.enable_local_logins_via_email;
@@ -80,7 +89,8 @@ export default class LoginPageController extends Controller {
if (
this.hasAtLeastOneLoginButton &&
!this.showSecondFactor &&
- !this.showSecurityKey
+ !this.showSecurityKey &&
+ !this.showCodeLoginForm
) {
classes.push("has-alt-auth");
}
@@ -90,6 +100,9 @@ export default class LoginPageController extends Controller {
if (this.showSecondFactor || this.showSecurityKey) {
classes.push("second-factor");
}
+ if (this.showCodeLoginForm) {
+ classes.push("code-login");
+ }
return classes.join(" ");
}
@@ -159,6 +172,16 @@ export default class LoginPageController extends Controller {
}
}
+ @action
+ showCodeLogin() {
+ this.showCodeLoginForm = true;
+ }
+
+ @action
+ usePassword() {
+ this.showCodeLoginForm = false;
+ }
+
@action
securityKeyCredentialChanged(value) {
this.securityKeyCredential = value;
diff --git a/frontend/discourse/app/templates/login.gjs b/frontend/discourse/app/templates/login.gjs
index 6939d229550..4b58fb40584 100644
--- a/frontend/discourse/app/templates/login.gjs
+++ b/frontend/discourse/app/templates/login.gjs
@@ -1,5 +1,6 @@
import { hash } from "@ember/helper";
import { trustHTML } from "@ember/template";
+import CodeLoginForm from "discourse/components/code-login-form";
import LocalLoginForm from "discourse/components/local-login-form";
import LoginButtons from "discourse/components/login-buttons";
import LoginPageCta from "discourse/components/login-page-cta";
@@ -9,7 +10,7 @@ import bodyClass from "discourse/helpers/body-class";
import hideApplicationHeaderButtons from "discourse/helpers/hide-application-header-buttons";
import hideApplicationSidebar from "discourse/helpers/hide-application-sidebar";
import lazyHash from "discourse/helpers/lazy-hash";
-import { and } from "discourse/truth-helpers";
+import { and, not } from "discourse/truth-helpers";
import DFlashMessage from "discourse/ui-kit/d-flash-message";
import dConcatClass from "discourse/ui-kit/helpers/d-concat-class";
import { i18n } from "discourse-i18n";
@@ -58,7 +59,11 @@ export default <template>
@outletArgs={{lazyHash [email protected]}}
/>
</WelcomeHeader>
- {{#if @controller.showLoginButtons}}
+ {{#if
+ (and
+ @controller.showLoginButtons (not @controller.showCodeLoginForm)
+ )
+ }}
<LoginButtons
@externalLogin={{@controller.externalLogin}}
@@ -86,33 +91,48 @@ export default <template>
@name="login-wrapper"
@outletArgs={{lazyHash [email protected]}}
>
- <LocalLoginForm
- @loginName={{@controller.loginName}}
- @loginNameChanged={{@controller.loginNameChanged}}
- @canLoginLocalWithEmail={{@controller.canLoginLocalWithEmail}}
- @canUsePasskeys={{@controller.canUsePasskeys}}
- @passkeyLogin={{@controller.passkeyLogin}}
- @loginPassword={{@controller.loginPassword}}
- @loginPasswordChanged={{@controller.loginPasswordChanged}}
- @secondFactorMethod={{@controller.secondFactorMethod}}
- @secondFactorToken={{@controller.secondFactorToken}}
- @secondFactorTokenChanged={{@controller.secondFactorTokenChanged}}
- @backupEnabled={{@controller.backupEnabled}}
- @totpEnabled={{@controller.totpEnabled}}
- @securityKeyAllowedCredentialIds={{@controller.securityKeyAllowedCredentialIds}}
- @securityKeyChallenge={{@controller.securityKeyChallenge}}
- @showSecurityKey={{@controller.showSecurityKey}}
- @otherMethodAllowed={{@controller.otherMethodAllowed}}
- @showSecondFactor={{@controller.showSecondFactor}}
- @handleForgotPassword={{@controller.handleForgotPassword}}
- @login={{@controller.localLogin}}
- @flashChanged={{@controller.flashChanged}}
- @flashTypeChanged={{@controller.flashTypeChanged}}
- @securityKeyCredentialChanged={{@controller.securityKeyCredentialChanged}}
- />
+ {{#if @controller.showCodeLoginForm}}
+ <CodeLoginForm
+ @initialEmail={{@controller.loginName}}
+ @onUsePassword={{@controller.usePassword}}
+ />
+ {{else}}
+ <LocalLoginForm
+ @onShowCodeLogin={{if
+ @controller.canUseCodeLogin
+ @controller.showCodeLogin
+ }}
+ @loginName={{@controller.loginName}}
+ @loginNameChanged={{@controller.loginNameChanged}}
+ @canLoginLocalWithEmail={{@controller.canLoginLocalWithEmail}}
+ @canUsePasskeys={{@controller.canUsePasskeys}}
+ @passkeyLogin={{@controller.passkeyLogin}}
+ @loginPassword={{@controller.loginPassword}}
+ @loginPasswordChanged={{@controller.loginPasswordChanged}}
+ @secondFactorMethod={{@controller.secondFactorMethod}}
+ @secondFactorToken={{@controller.secondFactorToken}}
+ @secondFactorTokenChanged={{@controller.secondFactorTokenChanged}}
+ @backupEnabled={{@controller.backupEnabled}}
+ @totpEnabled={{@controller.totpEnabled}}
+ @securityKeyAllowedCredentialIds={{@controller.securityKeyAllowedCredentialIds}}
+ @securityKeyChallenge={{@controller.securityKeyChallenge}}
+ @showSecurityKey={{@controller.showSecurityKey}}
+ @otherMethodAllowed={{@controller.otherMethodAllowed}}
+ @showSecondFactor={{@controller.showSecondFactor}}
+ @handleForgotPassword={{@controller.handleForgotPassword}}
+ @login={{@controller.localLogin}}
+ @flashChanged={{@controller.flashChanged}}
+ @flashTypeChanged={{@controller.flashTypeChanged}}
+ @securityKeyCredentialChanged={{@controller.securityKeyCredentialChanged}}
+ />
+ {{/if}}
</PluginOutlet>
- {{#if @controller.site.desktopView}}
+ {{#if
+ (and
+ @controller.site.desktopView (not @controller.showCodeLoginForm)
+ )
+ }}
<LoginPageCta
@canLoginLocal={{@controller.canLoginLocal}}
@showSecurityKey={{@controller.showSecurityKey}}
@@ -128,7 +148,13 @@ export default <template>
</div>
{{/if}}
- {{#if (and @controller.showLoginButtons @controller.site.desktopView)}}
+ {{#if
+ (and
+ @controller.showLoginButtons
+ @controller.site.desktopView
+ (not @controller.showCodeLoginForm)
+ )
+ }}
{{#unless @controller.canLoginLocal}}
<div class="login-left-side">
@@ -148,7 +174,9 @@ export default <template>
{{/if}}
{{/if}}
- {{#if @controller.site.mobileView}}
+ {{#if
+ (and @controller.site.mobileView (not @controller.showCodeLoginForm))
+ }}
{{#unless @controller.hasNoLoginOptions}}
<LoginPageCta
@canLoginLocal={{@controller.canLoginLocal}}
diff --git a/frontend/discourse/tests/helpers/form-kit-assertions.js b/frontend/discourse/tests/helpers/form-kit-assertions.js
index 1afdf4901d8..d6c3a0ba29a 100644
--- a/frontend/discourse/tests/helpers/form-kit-assertions.js
+++ b/frontend/discourse/tests/helpers/form-kit-assertions.js
@@ -82,6 +82,7 @@ class FieldHelper {
case "input":
case "input-number":
case "input-text":
+ case "input-email":
return this.element.querySelector(".form-kit__control-input").value;
case "icon":
return (
diff --git a/frontend/discourse/tests/helpers/form-kit-helper.js b/frontend/discourse/tests/helpers/form-kit-helper.js
index 2220b2ae444..638331ebc2f 100644
--- a/frontend/discourse/tests/helpers/form-kit-helper.js
+++ b/frontend/discourse/tests/helpers/form-kit-helper.js
@@ -80,6 +80,7 @@ class Field {
switch (this.controlType) {
case "input":
case "input-text":
+ case "input-email":
case "input-number":
case "password":
case "checkbox":
@@ -106,6 +107,7 @@ class Field {
// String-based controls fall through to return raw value
case "input":
case "input-text":
+ case "input-email":
case "password":
case "code":
case "textarea":
diff --git a/frontend/discourse/tests/integration/components/code-login-form-test.gjs b/frontend/discourse/tests/integration/components/code-login-form-test.gjs
new file mode 100644
index 00000000000..3e8f6d78669
--- /dev/null
+++ b/frontend/discourse/tests/integration/components/code-login-form-test.gjs
@@ -0,0 +1,102 @@
+import { click, fillIn, render } from "@ember/test-helpers";
+import { module, test } from "qunit";
+import CodeLoginForm from "discourse/components/code-login-form";
+import { setupRenderingTest } from "discourse/tests/helpers/component-test";
+import pretender, { response } from "discourse/tests/helpers/create-pretender";
+import formKit from "discourse/tests/helpers/form-kit-helper";
+import { i18n } from "discourse-i18n";
+
+function stubCodeRequest() {
+ pretender.get("/session/hp.json", () =>
+ response({ value: "hp-value", challenge: "abc", expires_in: 300 })
+ );
+ pretender.post("/session/login-code", () => response({ success: "OK" }));
+}
+
+async function goToCodeStep() {
+ await render(<template><CodeLoginForm /></template>);
+ await fillIn(
+ ".code-login-form__email-step .form-kit__control-input",
+ );
+ await formKit().submit();
+}
+
+module("Integration | Component | CodeLoginForm", function (hooks) {
+ setupRenderingTest(hooks);
+
+ test("renders the email step initially", async function (assert) {
+ await render(
+ <template><CodeLoginForm @initialEmail="[email protected]" /></template>
+ );
+
+ assert.dom(".code-login-form__email-step").exists();
+ assert.form().field("email").hasValue("[email protected]");
+ assert.dom(".d-otp-input").doesNotExist();
+ });
+
+ test("rejects an invalid email address", async function (assert) {
+ await render(<template><CodeLoginForm /></template>);
+
+ await formKit().field("email").fillIn("not-an-email");
+ await formKit().submit();
+
+ assert.form().field("email").hasError(i18n("user.email.invalid"));
+ assert.dom(".code-login-form__email-step").exists();
+ });
+
+ test("advances to the code step after submitting an email", async function (assert) {
+ stubCodeRequest();
+
+ await goToCodeStep();
+
+ assert.dom(".code-login-form__code-step").exists();
+ assert
+ .dom(".code-login-form__instructions")
+ .includesText("[email protected]");
+ assert.dom(".d-otp-input").exists();
+ assert.dom(".code-login-form__resend").exists();
+ });
+
+ test("shows an error and clears the input for a wrong code", async function (assert) {
+ stubCodeRequest();
+ pretender.post("/session/login-code/verify", () =>
+ response({ error: i18n("email_login_code.invalid_code") })
+ );
+
+ await goToCodeStep();
+ await fillIn(".d-otp-input", "000000");
+
+ assert
+ .dom(".code-login-form__error")
+ .hasText(i18n("email_login_code.invalid_code"));
+ assert.dom(".d-otp-input").hasValue("", "the code input is cleared");
+ });
+
+ test("shows the second factor form when required", async function (assert) {
+ stubCodeRequest();
+ pretender.post("/session/login-code/verify", () =>
+ response({
+ second_factor_required: true,
+ totp_enabled: true,
+ backup_codes_enabled: false,
+ })
+ );
+
+ await goToCodeStep();
+ await fillIn(".d-otp-input", "123456");
+
+ assert.dom(".code-login-form__second-factor-step").exists();
+ assert.dom("#second-factor").exists();
+ });
+
+ test("returns to the email step when using a different email", async function (assert) {
+ stubCodeRequest();
+
+ await goToCodeStep();
+ await click(".code-login-form__change-email");
+
+ assert.dom(".code-login-form__email-step").exists();
+ assert.form().field("email").hasValue("[email protected]");
+ });
+});
diff --git a/lib/validators/enable_local_logins_via_code_validator.rb b/lib/validators/enable_local_logins_via_code_validator.rb
new file mode 100644
index 00000000000..28dcd355008
--- /dev/null
+++ b/lib/validators/enable_local_logins_via_code_validator.rb
@@ -0,0 +1,26 @@
+# frozen_string_literal: true
+
+class EnableLocalLoginsViaCodeValidator
+ def initialize(opts = {})
+ @opts = opts
+ end
+
+ def valid_value?(val)
+ return true if val == "f"
+
+ @error_message_key =
+ if !SiteSetting.enable_local_logins
+ "site_settings.errors.enable_local_logins_disabled"
+ elsif !SiteSetting.enable_local_logins_via_email
+ "site_settings.errors.enable_local_logins_via_email_disabled"
+ elsif SiteSetting.enable_discourse_connect
+ "site_settings.errors.discourse_connect_enabled"
+ end
+
+ @error_message_key.nil?
+ end
+
+ def error_message
+ I18n.t(@error_message_key) if @error_message_key
+ end
+end
diff --git a/spec/jobs/regular/send_email_login_code_spec.rb b/spec/jobs/regular/send_email_login_code_spec.rb
new file mode 100644
index 00000000000..b958a3c44a5
--- /dev/null
+++ b/spec/jobs/regular/send_email_login_code_spec.rb
@@ -0,0 +1,36 @@
+# frozen_string_literal: true
+
+RSpec.describe Jobs::SendEmailLoginCode do
+ before { SiteSetting.enable_local_logins_via_code = true }
+
+ it "raises an error without a to_address" do
+ expect { described_class.new.execute(code: "123456") }.to raise_error(
+ Discourse::InvalidParameters,
+ /to_address/,
+ )
+ end
+
+ it "raises an error without a code" do
+ expect { described_class.new.execute(to_address: "[email protected]") }.to raise_error(
+ Discourse::InvalidParameters,
+ /code/,
+ )
+ end
+
+ it "does not send an email when the setting is disabled" do
+ SiteSetting.enable_local_logins_via_code = false
+
+ described_class.new.execute(to_address: "[email protected]", code: "123456")
+
+ expect(ActionMailer::Base.deliveries).to be_empty
+ end
+
+ it "sends an email containing the code" do
+ described_class.new.execute(to_address: "[email protected]", code: "123456")
+
+ email = ActionMailer::Base.deliveries.last
+ expect(email.to).to contain_exactly("[email protected]")
+ expect(email.subject).to include("123456")
+ expect(email.body.to_s).to include("123456")
+ end
+end
diff --git a/spec/lib/read_only_mixin_spec.rb b/spec/lib/read_only_mixin_spec.rb
index 6166571a86f..9a9621940fc 100644
--- a/spec/lib/read_only_mixin_spec.rb
+++ b/spec/lib/read_only_mixin_spec.rb
@@ -48,6 +48,10 @@ describe ReadOnlyMixin do
[SessionController, :create],
# Allows staff to reset their password (part 1/2)
[SessionController, :forgot_password],
+ # Allows staff to log in via an emailed one-time code (part 1/2)
+ [SessionController, :create_login_code],
+ # Allows staff to log in via an emailed one-time code (part 2/2)
+ [SessionController, :verify_login_code],
# Allows staff to log in via OAuth
[Users::OmniauthCallbacksController, :complete],
# Allows staff to log in via email link
diff --git a/spec/lib/validators/enable_local_logins_via_code_validator_spec.rb b/spec/lib/validators/enable_local_logins_via_code_validator_spec.rb
new file mode 100644
index 00000000000..50bcc38835b
--- /dev/null
+++ b/spec/lib/validators/enable_local_logins_via_code_validator_spec.rb
@@ -0,0 +1,74 @@
+# frozen_string_literal: true
+
+RSpec.describe EnableLocalLoginsViaCodeValidator do
+ subject(:validator) { described_class.new }
+
+ describe "#valid_value?" do
+ describe "when 'enable_local_logins' is false" do
+ before { SiteSetting.enable_local_logins = false }
+
+ it "allows disabling" do
+ expect(validator.valid_value?("f")).to eq(true)
+ end
+
+ it "does not allow enabling" do
+ expect(validator.valid_value?("t")).to eq(false)
+
+ expect(validator.error_message).to eq(
+ I18n.t("site_settings.errors.enable_local_logins_disabled"),
+ )
+ end
+ end
+
+ describe "when 'enable_local_logins_via_email' is false" do
+ before { SiteSetting.enable_local_logins_via_email = false }
+
+ it "allows disabling" do
+ expect(validator.valid_value?("f")).to eq(true)
+ end
+
+ it "does not allow enabling" do
+ expect(validator.valid_value?("t")).to eq(false)
+
+ expect(validator.error_message).to eq(
+ I18n.t("site_settings.errors.enable_local_logins_via_email_disabled"),
+ )
+ end
+ end
+
+ describe "when 'enable_discourse_connect' is true" do
+ before do
+ SiteSetting.discourse_connect_url = "https://www.example.com/sso"
+ SiteSetting.discourse_connect_secret = "x" * 10
+ SiteSetting.enable_discourse_connect = true
+ end
+
+ it "allows disabling" do
+ expect(validator.valid_value?("f")).to eq(true)
+ end
+
+ it "does not allow enabling" do
+ expect(validator.valid_value?("t")).to eq(false)
+
+ expect(validator.error_message).to eq(
+ I18n.t("site_settings.errors.discourse_connect_enabled"),
+ )
+ end
+ end
+
+ describe "when local logins are enabled and discourse connect is disabled" do
+ before do
+ SiteSetting.enable_local_logins = true
+ SiteSetting.enable_discourse_connect = false
+ end
+
+ it "allows disabling" do
+ expect(validator.valid_value?("f")).to eq(true)
+ end
+
+ it "allows enabling" do
+ expect(validator.valid_value?("t")).to eq(true)
+ end
+ end
+ end
+end
diff --git a/spec/models/email_login_code_spec.rb b/spec/models/email_login_code_spec.rb
new file mode 100644
index 00000000000..964ddc6b314
--- /dev/null
+++ b/spec/models/email_login_code_spec.rb
@@ -0,0 +1,145 @@
+# frozen_string_literal: true
+
+RSpec.describe EmailLoginCode do
+ describe ".generate!" do
+ it "creates a record with a hashed 6-digit code" do
+ record = described_class.generate!(email: "[email protected]")
+
+ expect(record).to be_persisted
+ expect(record.code).to match(/\A\d{6}\z/)
+ expect(record.code_hash).to eq(described_class.hash_code(record.code))
+ end
+
+ it "downcases the email" do
+ record = described_class.generate!(email: "[email protected]")
+
+ expect(record.email).to eq("[email protected]")
+ end
+
+ it "deletes prior codes for the same email case-insensitively" do
+ old_record = described_class.generate!(email: "[email protected]")
+ other_record = described_class.generate!(email: "[email protected]")
+
+ new_record = described_class.generate!(email: "[email protected]")
+
+ expect(described_class.all).to contain_exactly(other_record, new_record)
+ end
+
+ it "expires the code after 10 minutes" do
+ freeze_time
+
+ record = described_class.generate!(email: "[email protected]")
+
+ expect(record.expires_at).to eq_time(described_class::VALID_FOR.from_now)
+ end
+
+ it "does not expose the plaintext code on a re-fetched instance" do
+ described_class.generate!(email: "[email protected]")
+
+ expect { described_class.last.code }.to raise_error(described_class::CodeAccessError)
+ end
+ end
+
+ describe ".active" do
+ fab!(:login_code) { EmailLoginCode.generate!(email: "[email protected]") }
+
+ it "includes fresh codes" do
+ expect(described_class.active).to contain_exactly(login_code)
+ end
+
+ it "excludes consumed codes" do
+ login_code.consume!
+
+ expect(described_class.active).to be_empty
+ end
+
+ it "excludes expired codes" do
+ login_code.update!(expires_at: 1.minute.ago)
+
+ expect(described_class.active).to be_empty
+ end
+
+ it "excludes locked out codes" do
+ login_code.update!(attempts: described_class::MAX_ATTEMPTS)
+
+ expect(described_class.active).to be_empty
+ end
+ end
+
+ describe ".for_email" do
+ fab!(:login_code) { EmailLoginCode.generate!(email: "[email protected]") }
+
+ it "matches case-insensitively" do
+ expect(described_class.for_email("[email protected]")).to contain_exactly(login_code)
+ expect(described_class.for_email("[email protected]")).to be_empty
+ end
+ end
+
+ describe "#verify" do
+ let(:login_code) { EmailLoginCode.generate!(email: "[email protected]") }
+ let(:code) { login_code.code }
+ let(:wrong_code) { code == "000000" ? "000001" : "000000" }
+
+ it "returns false for a wrong code and burns an attempt" do
+ expect(login_code.verify(wrong_code)).to eq(false)
+ expect(login_code.reload.attempts).to eq(1)
+ end
+
+ it "returns true for the correct code and resets attempts" do
+ login_code.verify(wrong_code)
+
+ expect(login_code.verify(code)).to eq(true)
+ expect(login_code.reload.attempts).to eq(0)
+ end
+
+ it "locks out after max attempts even with the correct code" do
+ described_class::MAX_ATTEMPTS.times { login_code.verify(wrong_code) }
+
+ expect(login_code.verify(code)).to eq(false)
+ expect(login_code.reload.attempts).to eq(described_class::MAX_ATTEMPTS)
+ end
+
+ it "returns false for a consumed code without burning attempts" do
+ login_code.consume!
+
+ expect(login_code.verify(code)).to eq(false)
+ expect(login_code.reload.attempts).to eq(0)
+ end
+
+ it "returns false for an expired code without burning attempts" do
+ login_code.update!(expires_at: 1.minute.ago)
+
+ expect(login_code.verify(code)).to eq(false)
+ expect(login_code.reload.attempts).to eq(0)
+ end
+ end
+
+ describe "#consume!" do
+ fab!(:login_code) { EmailLoginCode.generate!(email: "[email protected]") }
+
+ it "marks the code as consumed" do
+ freeze_time
+
+ login_code.consume!
+
+ expect(login_code.reload.consumed_at).to eq_time(Time.zone.now)
+ end
+
+ it "only succeeds once, so concurrent redemptions can't both win" do
+ expect(login_code.consume!).to eq(true)
+ # a second caller holding the same (stale) record loses the race
+ expect(login_code.consume!).to eq(false)
+ end
+ end
+
+ describe ".hash_code" do
+ it "keys the hash with the server secret rather than a bare digest" do
+ hash = described_class.hash_code("123456")
+
+ expect(hash).not_to eq(Digest::SHA256.hexdigest("123456"))
+ expect(hash).to eq(
+ OpenSSL::HMAC.hexdigest("SHA256", GlobalSetting.safe_secret_key_base, "123456"),
+ )
+ end
+ end
+end
diff --git a/spec/requests/session_controller_spec.rb b/spec/requests/session_controller_spec.rb
index c2489c91139..80e1e02baa1 100644
--- a/spec/requests/session_controller_spec.rb
+++ b/spec/requests/session_controller_spec.rb
@@ -534,6 +534,302 @@ RSpec.describe SessionController do
end
end
+ describe "#create_login_code" do
+ before { SiteSetting.enable_local_logins_via_code = true }
+
+ def honeypot_magic(params)
+ get "/session/hp.json"
+ json = response.parsed_body
+ params[:password_confirmation] = json["value"]
+ params[:challenge] = json["challenge"].reverse
+ params
+ end
+
+ it "returns a 404 when login via code is disabled" do
+ SiteSetting.enable_local_logins_via_code = false
+
+ post "/session/login-code.json", params: { email: user.email }
+
+ expect(response.status).to eq(404)
+ end
+
+ context "when local logins are disabled" do
+ before { SiteSetting.enable_local_logins = false }
+
+ it "returns a 403" do
+ post "/session/login-code.json", params: { email: user.email }
+
+ expect(response.status).to eq(403)
+ end
+ end
+
+ context "when email login is disabled" do
+ before { SiteSetting.enable_local_logins_via_email = false }
+
+ it "returns a 403" do
+ post "/session/login-code.json", params: { email: user.email }
+
+ expect(response.status).to eq(403)
+ end
+ end
+
+ context "when SSO is enabled" do
+ before do
+ SiteSetting.discourse_connect_url = "https://www.example.com/sso"
+ SiteSetting.discourse_connect_secret = "x" * 10
+ SiteSetting.enable_discourse_connect = true
+ end
+
+ it "returns a 403" do
+ post "/session/login-code.json", params: { email: user.email }
+
+ expect(response.status).to eq(403)
+ end
+ end
+
+ context "when the user is already logged in" do
+ it "redirects home without generating a code" do
+ sign_in(user)
+
+ post "/session/login-code.json", params: { email: user.email }
+
+ expect(response).to redirect_to("/")
+ expect(EmailLoginCode.count).to eq(0)
+ end
+ end
+
+ it "returns a 400 for an invalid email" do
+ post "/session/login-code.json", params: honeypot_magic(email: "not-an-email")
+
+ expect(response.status).to eq(400)
+ end
+
+ it "responds with success but no code when the honeypot fails" do
+ post "/session/login-code.json", params: { email: user.email }
+
+ expect(response.status).to eq(200)
+ expect(response.parsed_body["success"]).to eq("OK")
+ expect(EmailLoginCode.count).to eq(0)
+ end
+
+ it "generates a code and enqueues the email for an existing user" do
+ expect_enqueued_with(job: :send_email_login_code, args: { to_address: user.email }) do
+ post "/session/login-code.json", params: honeypot_magic(email: user.email)
+ end
+
+ expect(response.status).to eq(200)
+ expect(response.parsed_body["success"]).to eq("OK")
+ expect(EmailLoginCode.for_email(user.email).count).to eq(1)
+ end
+
+ it "renders the same response for existing and unknown emails" do
+ post "/session/login-code.json", params: honeypot_magic(email: user.email)
+ expect(response.status).to eq(200)
+ existing_email_body = response.body
+
+ post "/session/login-code.json", params: honeypot_magic(email: "[email protected]")
+
+ expect(response.status).to eq(200)
+ expect(response.body).to eq(existing_email_body)
+ end
+
+ context "when rate limited" do
+ before { RateLimiter.enable }
+
+ it "rate limits requests per IP per minute" do
+ 3.times do |i|
+ post "/session/login-code.json", params: { email: "user#{i}@example.com" }
+ expect(response.status).to eq(200)
+ end
+
+ post "/session/login-code.json", params: { email: "[email protected]" }
+
+ expect(response.status).to eq(429)
+ end
+
+ it "rate limits requests per email" do
+ freeze_time
+
+ 3.times do
+ post "/session/login-code.json", params: { email: user.email }
+ expect(response.status).to eq(200)
+ freeze_time 2.minutes.from_now
+ end
+
+ post "/session/login-code.json", params: { email: user.email }
+
+ expect(response.status).to eq(429)
+ end
+ end
+ end
+
+ describe "#verify_login_code" do
+ let(:login_code) { EmailLoginCode.generate!(email: user.email) }
+ let(:code) { login_code.code }
+
+ before { SiteSetting.enable_local_logins_via_code = true }
+
+ it "returns a 404 when login via code is disabled" do
+ SiteSetting.enable_local_logins_via_code = false
+
+ post "/session/login-code/verify.json", params: { email: user.email, code: "123456" }
+
+ expect(response.status).to eq(404)
+ end
+
+ context "when local logins are disabled" do
+ before { SiteSetting.enable_local_logins = false }
+
+ it "returns a 403" do
+ post "/session/login-code/verify.json", params: { email: user.email, code: "123456" }
+
+ expect(response.status).to eq(403)
+ end
+ end
+
+ context "when email login is disabled" do
+ before { SiteSetting.enable_local_logins_via_email = false }
+
+ it "returns a 403" do
+ post "/session/login-code/verify.json", params: { email: user.email, code: "123456" }
+
+ expect(response.status).to eq(403)
+ end
+ end
+
+ context "when SSO is enabled" do
+ before do
+ SiteSetting.discourse_connect_url = "https://www.example.com/sso"
+ SiteSetting.discourse_connect_secret = "x" * 10
+ SiteSetting.enable_discourse_connect = true
+ end
+
+ it "returns a 403" do
+ post "/session/login-code/verify.json", params: { email: user.email, code: "123456" }
+
+ expect(response.status).to eq(403)
+ end
+ end
+
+ it "redirects home when the user is already logged in" do
+ sign_in(user)
+
+ post "/session/login-code/verify.json", params: { email: user.email, code: "123456" }
+
+ expect(response).to redirect_to("/")
+ end
+
+ it "returns a 400 for a malformed code" do
+ post "/session/login-code/verify.json", params: { email: user.email, code: "abc" }
+
+ expect(response.status).to eq(400)
+ end
+
+ it "renders an error when no code was requested" do
+ post "/session/login-code/verify.json", params: { email: user.email, code: "123456" }
+
+ 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
+ end
+
+ it "renders an error for a wrong code" do
+ wrong_code = code == "000000" ? "000001" : "000000"
+
+ post "/session/login-code/verify.json", params: { email: user.email, code: wrong_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
+ end
+
+ it "logs in an existing user with a correct code" do
+ post "/session/login-code/verify.json", params: { email: user.email, code: }
+
+ expect(response.status).to eq(200)
+ expect(response.parsed_body.dig("user", "username")).to eq(user.username)
+ expect(session[:current_user_id]).to eq(user.id)
+ expect(EmailLoginCode.active.for_email(user.email)).to be_empty
+ end
+
+ it "does not log in a suspended user" do
+ user.update!(suspended_till: 2.days.from_now, suspended_at: Time.zone.now)
+
+ post "/session/login-code/verify.json", params: { email: user.email, code: }
+
+ expect(response.status).to eq(200)
+ expect(response.parsed_body["reason"]).to eq("suspended")
+ expect(session[:current_user_id]).to be_nil
+ end
+
+ it "does not log in an unapproved user when approval is required" do
+ SiteSetting.must_approve_users = true
+
+ post "/session/login-code/verify.json", params: { email: user.email, code: }
+
+ expect(response.status).to eq(200)
+ expect(response.parsed_body["error"]).to eq(I18n.t("login.not_approved"))
+ expect(session[:current_user_id]).to be_nil
+ end
+
+ 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
+ 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"))
+ expect(session[:current_user_id]).to be_nil
+ expect(User.find_by_email("[email protected]")).to be_nil
+ end
+ end
+
+ context "when the user has TOTP enabled" do
+ let!(:user_second_factor) { Fabricate(:user_second_factor_totp, user: user) }
+
+ it "requires a second factor without consuming the code" do
+ post "/session/login-code/verify.json", params: { email: user.email, code: }
+
+ expect(response.status).to eq(200)
+ expect(response.parsed_body["second_factor_required"]).to eq(true)
+ expect(response.parsed_body["totp_enabled"]).to eq(true)
+ expect(session[:current_user_id]).to be_nil
+ expect(EmailLoginCode.active.for_email(user.email)).to contain_exactly(login_code)
+ end
+
+ it "logs in with a valid TOTP token" do
+ post "/session/login-code/verify.json", params: { email: user.email, code: }
+ expect(session[:current_user_id]).to be_nil
+
+ post "/session/login-code/verify.json",
+ params: {
+ email: user.email,
+ 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)
+ end
+
+ it "rejects an invalid TOTP token" do
+ post "/session/login-code/verify.json",
+ params: {
+ email: user.email,
+ code:,
+ second_factor_token: "0000",
+ second_factor_method: UserSecondFactor.methods[:totp],
+ }
+
+ expect(response.status).to eq(200)
+ expect(response.parsed_body["error"]).to eq(I18n.t("login.invalid_second_factor_code"))
+ expect(session[:current_user_id]).to be_nil
+ end
+ end
+ end
+
describe "logoff support" do
it "can log off users cleanly" do
user = Fabricate(:user)
diff --git a/spec/services/email_login_code/redeem_spec.rb b/spec/services/email_login_code/redeem_spec.rb
new file mode 100644
index 00000000000..fe6be25fba6
--- /dev/null
+++ b/spec/services/email_login_code/redeem_spec.rb
@@ -0,0 +1,72 @@
+# frozen_string_literal: true
+
+RSpec.describe EmailLoginCode::Redeem do
+ describe described_class::Contract, type: :model do
+ 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) }
+ end
+
+ 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!(:login_code) { EmailLoginCode.generate!(email:) }
+
+ let(:code) { login_code.code }
+
+ context "when contract isn't valid" do
+ let(:code) { "12345" }
+
+ it { is_expected.to fail_a_contract }
+ 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 does not belong to a user" do
+ let(:email) { "[email protected]" }
+
+ it { is_expected.to fail_to_find_a_model(:user) }
+
+ it "does not consume the code" do
+ expect { result }.not_to change { login_code.reload.consumed_at }
+ end
+ end
+
+ context "when the email belongs to an existing active user" do
+ 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
+ end
+
+ context "when the email belongs to an existing inactive user" do
+ fab!(:user) { Fabricate(:user, active: false) }
+
+ it { is_expected.to run_successfully }
+
+ it "activates the user and consumes the code" do
+ expect(result[:user].id).to eq(user.id)
+ expect(user.reload).to be_active
+ expect(login_code.reload.consumed_at).to be_present
+ end
+ end
+ end
+end
diff --git a/spec/services/email_login_code/request_spec.rb b/spec/services/email_login_code/request_spec.rb
new file mode 100644
index 00000000000..63ba6b9c9af
--- /dev/null
+++ b/spec/services/email_login_code/request_spec.rb
@@ -0,0 +1,94 @@
+# frozen_string_literal: true
+
+RSpec.describe EmailLoginCode::Request do
+ describe described_class::Contract, type: :model do
+ it { is_expected.to validate_presence_of(:email) }
+ it { is_expected.to validate_length_of(:email).is_at_most(513) }
+ it { is_expected.to allow_values("[email protected]", "[email protected]").for(:email) }
+ it { is_expected.not_to allow_values("not-an-email", "foo@").for(:email) }
+ end
+
+ describe ".call" do
+ subject(:result) { described_class.call(params:, **dependencies) }
+
+ fab!(:user)
+
+ let(:params) { { email: } }
+ let(:dependencies) { { ip_address: "127.0.0.1" } }
+ let(:email) { user.email }
+
+ context "when contract isn't valid" do
+ let(:email) { "not-an-email" }
+
+ it { is_expected.to fail_a_contract }
+ end
+
+ context "when the email belongs to an existing user" do
+ it { is_expected.to run_successfully }
+
+ it "generates a login code for the email" do
+ expect { result }.to change { EmailLoginCode.for_email(user.email).count }.by(1)
+ end
+
+ it "enqueues the login code email" do
+ expect_enqueued_with(job: :send_email_login_code, args: { to_address: user.email }) do
+ result
+ end
+ end
+
+ it "triggers the :before_email_login 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 the email matches an existing user after normalization" do
+ let(:email) { "[email protected]" }
+
+ before do
+ SiteSetting.normalize_emails = true
+ user.update!(email: "[email protected]")
+ end
+
+ it { is_expected.to run_successfully }
+
+ it "treats it as an existing account" do
+ events = DiscourseEvent.track_events(:before_email_login) { result }
+
+ expect(events).to contain_exactly(event_name: :before_email_login, params: [user])
+ expect(EmailLoginCode.for_email(email).count).to eq(1)
+ end
+ end
+
+ context "when the email does not belong to a user" 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 }
+
+ expect(EmailLoginCode.count).to eq(0)
+ end
+
+ it "does not trigger the :before_email_login event" do
+ events = DiscourseEvent.track_events(:before_email_login) { result }
+
+ expect(events).to be_empty
+ end
+ end
+
+ context "when the email belongs to a staged user" do
+ fab!(:staged_user, :staged)
+
+ let(:email) { staged_user.email }
+
+ it { is_expected.to run_successfully }
+
+ it "does not generate a code, since staged users cannot log in" do
+ expect { result }.not_to change(EmailLoginCode, :count)
+ end
+ end
+ end
+end
diff --git a/spec/services/email_login_code/verify_spec.rb b/spec/services/email_login_code/verify_spec.rb
new file mode 100644
index 00000000000..01cad5f1149
--- /dev/null
+++ b/spec/services/email_login_code/verify_spec.rb
@@ -0,0 +1,67 @@
+# frozen_string_literal: true
+
+RSpec.describe EmailLoginCode::Verify do
+ describe described_class::Contract, type: :model do
+ it { is_expected.to validate_presence_of(:email) }
+ it { is_expected.to validate_presence_of(:code) }
+ it { is_expected.to allow_values("[email protected]").for(:email) }
+ it { is_expected.not_to allow_values("not-an-email").for(:email) }
+ it { is_expected.to allow_values("123456", " 123456 ").for(:code) }
+ it { is_expected.not_to allow_values("12345", "1234567", "abcdef").for(:code) }
+ end
+
+ describe ".call" do
+ subject(:result) { described_class.call(params:) }
+
+ fab!(:user)
+
+ let(:params) { { email:, code: } }
+ let(:email) { user.email }
+
+ let!(:login_code) { EmailLoginCode.generate!(email:) }
+
+ let(:code) { login_code.code }
+
+ context "when contract isn't valid" do
+ let(:code) { "12345" }
+
+ it { is_expected.to fail_a_contract }
+ 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) }
+
+ it "burns an attempt" do
+ expect { result }.to change { login_code.reload.attempts }.by(1)
+ end
+ end
+
+ context "when the code is correct for an existing user" do
+ it { is_expected.to run_successfully }
+
+ it "returns the user without consuming the code" do
+ expect(result[:user]).to eq(user)
+ expect(login_code.reload.consumed_at).to be_nil
+ end
+ end
+
+ context "when the code is correct for an unknown email" do
+ let(:email) { "[email protected]" }
+
+ it { is_expected.to run_successfully }
+
+ it "returns no user and keeps the code active" do
+ expect(result[:user]).to be_nil
+ expect(EmailLoginCode.active.for_email(email)).to contain_exactly(login_code)
+ end
+ end
+ end
+end
diff --git a/spec/system/code_login_spec.rb b/spec/system/code_login_spec.rb
new file mode 100644
index 00000000000..109497e6420
--- /dev/null
+++ b/spec/system/code_login_spec.rb
@@ -0,0 +1,114 @@
+# frozen_string_literal: true
+
+require "rotp"
+
+describe "Login via email code" do
+ include ThemeScreenshotMarker
+
+ fab!(:user) { Fabricate(:user, password: "supersecurepassword") }
+
+ before do
+ SiteSetting.enable_local_logins_via_email = true
+ SiteSetting.enable_local_logins_via_code = true
+ Jobs.run_immediately!
+ EmailToken.confirm(Fabricate(:email_token, user: user).token)
+ 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 start_code_login(email)
+ visit("/login")
+ expect(page).to have_css("#login-account-name")
+ screenshot_marker(label: "code-login-password-form")
+
+ find("#one-time-code-link").click
+ expect(page).to have_css(".code-login-form__email-step")
+ screenshot_marker(label: "code-login-email-step")
+
+ 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")
+ screenshot_marker(label: "code-login-code-step")
+ end
+
+ it "logs an existing user in without a password" do
+ start_code_login(user.email)
+ expect(page).to have_css(".code-login-form__resend[disabled]")
+
+ fill_code(latest_emailed_code(user.email))
+
+ expect(page).to have_css(".header-dropdown-toggle.current-user")
+ expect(User.find_by_email(user.email)).to eq(user)
+ end
+
+ it "shows an error for a wrong code, then accepts the correct one" do
+ start_code_login(user.email)
+ code = latest_emailed_code(user.email)
+ wrong_code = code == "000000" ? "000001" : "000000"
+
+ fill_code(wrong_code)
+ expect(page).to have_css(
+ ".code-login-form__error",
+ text: I18n.t("email_login_code.invalid_code"),
+ )
+ screenshot_marker(label: "code-login-wrong-code")
+
+ fill_code(code)
+ expect(page).to have_css(".header-dropdown-toggle.current-user")
+ end
+
+ context "when the user has a second factor" do
+ fab!(:user_second_factor) { Fabricate(:user_second_factor_totp, user: user) }
+
+ it "prompts for the second factor before logging in" do
+ start_code_login(user.email)
+ fill_code(latest_emailed_code(user.email))
+
+ expect(page).to have_css(".code-login-form__second-factor-step")
+ screenshot_marker(label: "code-login-second-factor")
+
+ find(".second-factor-token-input").fill_in(with: ROTP::TOTP.new(user_second_factor.data).now)
+ find(".code-login-form__second-factor-step .code-login-form__verify").click
+
+ expect(page).to have_css(".header-dropdown-toggle.current-user")
+ end
+ end
+
+ it "can switch to the code form and back to password login" do
+ visit("/login")
+ expect(page).to have_css("#login-account-name")
+
+ find("#one-time-code-link").click
+ expect(page).to have_css(".code-login-form__email-step")
+
+ find(".code-login-form__password-toggle").click
+ expect(page).to have_css("#login-account-name")
+
+ find("#login-account-name").fill_in(with: user.username)
+ find("#login-account-password").fill_in(with: "supersecurepassword")
+ find("#login-button").click
+
+ expect(page).to have_css(".header-dropdown-toggle.current-user")
+ end
+
+ context "when the setting is disabled" do
+ before { SiteSetting.enable_local_logins_via_code = false }
+
+ it "does not offer the code option" do
+ visit("/login")
+
+ expect(page).to have_css("#login-account-name")
+ expect(page).to have_css("#email-login-link", visible: :all)
+ expect(page).to have_no_css("#one-time-code-link", visible: :all)
+ end
+ end
+end