Skip to content

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

FEATURE: Discourse ID setting page (#36316)

Régis Hanol297608d8db91
diff --git a/app/assets/stylesheets/admin/admin_base.scss b/app/assets/stylesheets/admin/admin_base.scss
index 449302b7c18..ca29de25244 100644
--- a/app/assets/stylesheets/admin/admin_base.scss
+++ b/app/assets/stylesheets/admin/admin_base.scss
@@ -1298,3 +1298,4 @@ a.inline-editable-field {
@import "admin/admin_config_color_palettes";
@import "admin/admin_config_components";
@import "admin/upcoming-changes";
+@import "admin/discourse_id";
diff --git a/app/assets/stylesheets/admin/discourse_id.scss b/app/assets/stylesheets/admin/discourse_id.scss
new file mode 100644
index 00000000000..dfaee4f1c01
--- /dev/null
+++ b/app/assets/stylesheets/admin/discourse_id.scss
@@ -0,0 +1,44 @@
+.discourse-id-admin {
+ .discourse-id-header {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ margin-bottom: 1em;
+
+ .admin-config-area-card__title {
+ margin: 0;
+ }
+ }
+
+ .discourse-id-stats {
+ display: flex;
+ gap: 1em;
+
+ &__item {
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ flex: 1;
+ padding: 1em 1.5em;
+ background: var(--primary-very-low);
+ border-radius: var(--d-border-radius);
+ }
+
+ &__value {
+ font-size: var(--font-up-4);
+ font-weight: 700;
+ color: var(--primary);
+ }
+
+ &__label {
+ font-size: var(--font-down-1);
+ color: var(--primary-medium);
+ text-align: center;
+ margin-top: 0.25em;
+ }
+ }
+
+ .discourse-id-footer {
+ margin-top: 1em;
+ }
+}
diff --git a/app/controllers/admin/config/discourse_id_controller.rb b/app/controllers/admin/config/discourse_id_controller.rb
new file mode 100644
index 00000000000..70e13614496
--- /dev/null
+++ b/app/controllers/admin/config/discourse_id_controller.rb
@@ -0,0 +1,67 @@
+# frozen_string_literal: true
+
+class Admin::Config::DiscourseIdController < Admin::AdminController
+ def show
+ render json: {
+ enabled: SiteSetting.enable_discourse_id,
+ configured: credentials_configured?,
+ stats: {
+ total_users: total_users_count,
+ signups_30_days: signups_last_30_days,
+ logins_30_days: logins_last_30_days,
+ },
+ }
+ end
+
+ def regenerate_credentials
+ DiscourseId::RegenerateCredentials.call(guardian:) do
+ on_success { render json: success_json }
+ on_failed_policy(:credentials_configured?) do
+ render json: failed_json.merge(error: I18n.t("discourse_id.errors.not_configured")),
+ status: :unprocessable_entity
+ end
+ on_failed_step(:request_challenge) do |step|
+ render json: failed_json.merge(error: step.error), status: :unprocessable_entity
+ end
+ on_failed_step(:regenerate_with_challenge) do |step|
+ render json: failed_json.merge(error: step.error), status: :unprocessable_entity
+ end
+ on_failure do
+ render json: failed_json.merge(error: I18n.t("discourse_id.errors.regenerate_failed")),
+ status: :unprocessable_entity
+ end
+ end
+ end
+
+ def update_settings
+ params.permit(:enabled)
+
+ SiteSetting.enable_discourse_id = params[:enabled] if params.key?(:enabled)
+
+ render json: success_json
+ end
+
+ private
+
+ def credentials_configured?
+ SiteSetting.discourse_id_client_id.present? && SiteSetting.discourse_id_client_secret.present?
+ end
+
+ def total_users_count
+ UserAssociatedAccount.where(provider_name: "discourse_id").count
+ end
+
+ def signups_last_30_days
+ UserAssociatedAccount
+ .where(provider_name: "discourse_id")
+ .where("created_at > ?", 30.days.ago)
+ .count
+ end
+
+ def logins_last_30_days
+ UserAssociatedAccount
+ .where(provider_name: "discourse_id")
+ .where("last_used > ?", 30.days.ago)
+ .count
+ end
+end
diff --git a/app/services/discourse_id/concerns/challenge_flow.rb b/app/services/discourse_id/concerns/challenge_flow.rb
new file mode 100644
index 00000000000..c715bc91096
--- /dev/null
+++ b/app/services/discourse_id/concerns/challenge_flow.rb
@@ -0,0 +1,91 @@
+# frozen_string_literal: true
+
+module DiscourseId
+ module Concerns
+ module ChallengeFlow
+ extend ActiveSupport::Concern
+
+ private
+
+ def request_challenge
+ response =
+ post_json(
+ "/challenge",
+ { domain: Discourse.current_hostname }.tap do |body|
+ body[:path] = Discourse.base_path if Discourse.base_path.present?
+ end,
+ )
+
+ return fail!(response[:error]) if response[:error]
+
+ json = response[:data]
+
+ if json["domain"] != Discourse.current_hostname
+ error =
+ "Domain mismatch in challenge response (expected: #{Discourse.current_hostname}, got: #{json["domain"]})"
+ log_error("request_challenge", error)
+ return fail!(error)
+ end
+
+ if Discourse.base_path.present? && json["path"] != Discourse.base_path
+ error =
+ "Path mismatch in challenge response (expected: #{Discourse.base_path}, got: #{json["path"]})"
+ log_error("request_challenge", error)
+ return fail!(error)
+ end
+
+ context[:token] = json["token"]
+ end
+
+ def store_challenge_token(token:)
+ Discourse.redis.setex("discourse_id_challenge_token", 600, token)
+ end
+
+ def post_json(path, body)
+ uri = URI("#{discourse_id_url}#{path}")
+ use_ssl = Rails.env.production? || uri.scheme == "https"
+
+ request = Net::HTTP::Post.new(uri)
+ request.content_type = "application/json"
+ request.body = body.to_json
+
+ begin
+ response =
+ Net::HTTP.start(uri.hostname, uri.port, use_ssl:) { |http| http.request(request) }
+ rescue StandardError => e
+ error = "Request to '#{uri}' failed: #{e.message}."
+ log_error(path, error)
+ return { error: }
+ end
+
+ if response.code.to_i != 200
+ error = "Request to '#{path}' failed: #{response.code}\nError: #{response.body}"
+ log_error(path, error)
+ return { error: }
+ end
+
+ begin
+ { data: JSON.parse(response.body) }
+ rescue JSON::ParserError => e
+ error = "Response from '#{path}' invalid JSON: #{e.message}"
+ log_error(path, error)
+ { error: }
+ end
+ end
+
+ def discourse_id_url
+ @discourse_id_url ||= DiscourseId.provider_url
+ end
+
+ def log_error(step, message)
+ Rails.logger.error(
+ "Discourse ID #{service_name} failed at step '#{step}'. Error: #{message}",
+ )
+ end
+
+ def service_name
+ self.class.name.demodulize.underscore.humanize.downcase
+ end
+ end
+ end
+end
diff --git a/app/services/discourse_id/regenerate_credentials.rb b/app/services/discourse_id/regenerate_credentials.rb
new file mode 100644
index 00000000000..cec2f9d3c66
--- /dev/null
+++ b/app/services/discourse_id/regenerate_credentials.rb
@@ -0,0 +1,46 @@
+# frozen_string_literal: true
+
+class DiscourseId::RegenerateCredentials
+ include Service::Base
+ include DiscourseId::Concerns::ChallengeFlow
+
+ policy :credentials_configured?
+ step :request_challenge
+ step :store_challenge_token
+ step :regenerate_with_challenge
+ step :store_new_credentials
+ step :log_action
+
+ private
+
+ def credentials_configured?
+ SiteSetting.discourse_id_client_id.present? && SiteSetting.discourse_id_client_secret.present?
+ end
+
+ def regenerate_with_challenge(token:)
+ response =
+ post_json(
+ "/regenerate",
+ {
+ client_id: SiteSetting.discourse_id_client_id,
+ client_secret: SiteSetting.discourse_id_client_secret,
+ challenge_token: token,
+ },
+ )
+
+ return fail!(response[:error]) if response[:error]
+
+ context[:data] = response[:data]
+ end
+
+ def store_new_credentials(data:)
+ SiteSetting.discourse_id_client_secret = data["client_secret"]
+ end
+
+ def log_action(guardian:)
+ StaffActionLogger.new(guardian.user).log_custom(
+ "discourse_id_regenerate_credentials",
+ client_id: SiteSetting.discourse_id_client_id,
+ )
+ end
+end
diff --git a/app/services/discourse_id/register.rb b/app/services/discourse_id/register.rb
index bad37d4d20c..bfb0ec38807 100644
--- a/app/services/discourse_id/register.rb
+++ b/app/services/discourse_id/register.rb
@@ -2,6 +2,7 @@
class DiscourseId::Register
include Service::Base
+ include DiscourseId::Concerns::ChallengeFlow
params do
attribute :force, :boolean, default: false
@@ -13,6 +14,7 @@ class DiscourseId::Register
step :store_challenge_token
step :register_with_challenge
step :store_credentials
+ step :log_action
private
@@ -23,64 +25,7 @@ class DiscourseId::Register
SiteSetting.discourse_id_client_id.blank? && SiteSetting.discourse_id_client_secret.blank?
end
- def request_challenge
- uri = URI("#{discourse_id_url}/challenge")
- use_ssl = Rails.env.production? || uri.scheme == "https"
-
- body = { domain: Discourse.current_hostname }
- body[:path] = Discourse.base_path if Discourse.base_path.present?
-
- request = Net::HTTP::Post.new(uri)
- request.content_type = "application/json"
- request.body = body.to_json
-
- begin
- response = Net::HTTP.start(uri.hostname, uri.port, use_ssl:) { |http| http.request(request) }
- rescue StandardError => e
- error = "Challenge request to '#{uri}' failed: #{e.message}."
- log_error("request_challenge", error)
- return fail!(error:)
- end
-
- if response.code.to_i != 200
- error = "Failed to request challenge: #{response.code}\nError: #{response.body}"
- log_error("request_challenge", error)
- return fail!(error:)
- end
-
- begin
- json = JSON.parse(response.body)
- rescue JSON::ParserError => e
- error = "Challenge response invalid JSON: #{e.message}"
- log_error("request_challenge", error)
- return fail!(error:)
- end
-
- if json["domain"] != Discourse.current_hostname
- error =
- "Domain mismatch in challenge response (expected: #{Discourse.current_hostname}, got: #{json["domain"]})"
- log_error("request_challenge", error)
- return fail!(error:)
- end
-
- if Discourse.base_path.present? && json["path"] != Discourse.base_path
- error =
- "Path mismatch in challenge response (expected: #{Discourse.base_path}, got: #{json["path"]})"
- log_error("request_challenge", error)
- return fail!(error:)
- end
-
- context[:token] = json["token"]
- end
-
- def store_challenge_token(token:)
- Discourse.redis.setex("discourse_id_challenge_token", 600, token)
- end
-
def register_with_challenge(token:, params:)
- uri = URI("#{discourse_id_url}/register")
- use_ssl = Rails.env.production? || uri.scheme == "https"
-
body = {
client_name: SiteSetting.title,
redirect_uri: "#{Discourse.base_url}/auth/discourse_id/callback",
@@ -96,31 +41,11 @@ class DiscourseId::Register
body[:client_secret] = SiteSetting.discourse_id_client_secret
end
- request = Net::HTTP::Post.new(uri)
- request.content_type = "application/json"
- request.body = body.compact.to_json
+ response = post_json("/register", body.compact)
- begin
- response = Net::HTTP.start(uri.hostname, uri.port, use_ssl:) { |http| http.request(request) }
- rescue StandardError => e
- error = "Registration request to '#{uri}' failed: #{e.message}."
- log_error("register_with_challenge", error)
- return fail!(error:)
- end
-
- if response.code.to_i != 200
- error = "Registration failed: #{response.code}\nError: #{response.body}"
- log_error("register_with_challenge", error)
- return fail!(error:)
- end
+ return fail!(response[:error]) if response[:error]
- begin
- context[:data] = JSON.parse(response.body)
- rescue JSON::ParserError => e
- error = "Registration response invalid JSON: #{e.message}"
- log_error("register_with_challenge", error)
- fail!(error:)
- end
+ context[:data] = response[:data]
end
def store_credentials(data:, params:)
@@ -130,11 +55,13 @@ class DiscourseId::Register
SiteSetting.discourse_id_client_secret = data["client_secret"]
end
- def discourse_id_url
- @url ||= SiteSetting.discourse_id_provider_url.presence || "https://id.discourse.com"
- end
+ def log_action(guardian:, params:, data:)
+ return if params.update
+ return if guardian.blank?
- def log_error(step, message)
- Rails.logger.error("Discourse ID registration failed at step '#{step}'. Error: #{message}")
+ StaffActionLogger.new(guardian.user).log_custom(
+ "discourse_id_register",
+ client_id: data["client_id"],
+ )
end
end
diff --git a/app/services/discourse_id/revoke.rb b/app/services/discourse_id/revoke.rb
index 0ff1f1da05e..422efd34f53 100644
--- a/app/services/discourse_id/revoke.rb
+++ b/app/services/discourse_id/revoke.rb
@@ -40,6 +40,7 @@ class DiscourseId::Revoke
model :associated_account
step :revoke_auth_tokens
+ step :log_revocation
private
@@ -55,4 +56,13 @@ class DiscourseId::Revoke
def revoke_auth_tokens(associated_account:)
UserAuthToken.where(user_id: associated_account.user_id).destroy_all
end
+
+ def log_revocation(associated_account:, params:)
+ return unless SiteSetting.discourse_id_verbose_logging
+
+ Rails.logger.info(
+ "Discourse ID: Revoked auth tokens for user_id=#{associated_account.user_id} " \
+ "(provider_uid=#{params.identifier})",
+ )
+ end
end
diff --git a/config/locales/client.en.yml b/config/locales/client.en.yml
index 6c9de85f70e..9d9fe893892 100644
--- a/config/locales/client.en.yml
+++ b/config/locales/client.en.yml
@@ -5846,6 +5846,19 @@ en:
title: "Social logins"
discourseconnect:
title: "Discourse Connect"
+ discourse_id:
+ title: "Discourse ID"
+ discourse_id:
+ title: "Discourse ID"
+ stats:
+ total_users: "Total users"
+ signups_30_days: "Signups (30 days)"
+ logins_30_days: "Logins (30 days)"
+ regenerate_credentials: "Regenerate credentials"
+ regenerate_confirm: "Are you sure you want to regenerate your Discourse ID credentials? This will generate a new client secret. Regenerating credentials isn't normally required but can be useful for enhanced security."
+ description: "Discourse ID is a single sign-on service that allows users to log in to multiple Discourse sites using a single account. Common social login providers like Google, Facebook, Apple, and Github are supported without additional configuration."
+ learn_more: "Learn more"
+ regenerate_success: "Credentials regenerated successfully."
logo:
title: "Logo"
header_description: "Configure the logos and icons used throughout your site"
@@ -7723,6 +7736,7 @@ en:
stop_impersonating: "stop impersonating"
upcoming_change_toggled: "upcoming change toggled"
change_site_setting_groups: "change site setting groups"
+ discourse_id_regenerate_credentials: "regenerate Discourse ID credentials"
screened_emails:
title: "Screened emails"
description: "When someone tries to create a new account, the following email addresses will be checked and the registration will be blocked, or some other action performed."
diff --git a/config/locales/server.en.yml b/config/locales/server.en.yml
index 4ff1e01e2b3..92be2f26091 100644
--- a/config/locales/server.en.yml
+++ b/config/locales/server.en.yml
@@ -5894,3 +5894,6 @@ en:
discourse_id:
already_registered: "This site is already registered with Discourse ID"
+ errors:
+ not_configured: "Discourse ID is not configured. Please enable Discourse ID first."
+ regenerate_failed: "Failed to regenerate credentials. Please try again later."
diff --git a/config/routes.rb b/config/routes.rb
index cd1d819782b..e1217dacbb1 100644
--- a/config/routes.rb
+++ b/config/routes.rb
@@ -423,6 +423,10 @@ Discourse::Application.routes.draw do
get "login-and-authentication" => "site_settings#index"
get "login-and-authentication/authenticators" => "site_settings#index"
get "login-and-authentication/discourseconnect" => "site_settings#index"
+ get "login-and-authentication/discourse-id" => "discourse_id#show"
+ post "login-and-authentication/discourse-id/regenerate" =>
+ "discourse_id#regenerate_credentials"
+ put "login-and-authentication/discourse-id/settings" => "discourse_id#update_settings"
DiscoursePluginRegistry.admin_config_login_routes.each do |location|
get "login-and-authentication/#{location}" => "site_settings#index"
diff --git a/frontend/discourse/admin/routes/admin-config/login/discourse-id.js b/frontend/discourse/admin/routes/admin-config/login/discourse-id.js
new file mode 100644
index 00000000000..b4ed3c73048
--- /dev/null
+++ b/frontend/discourse/admin/routes/admin-config/login/discourse-id.js
@@ -0,0 +1,8 @@
+import Route from "@ember/routing/route";
+import { ajax } from "discourse/lib/ajax";
+
+export default class AdminConfigLoginDiscourseIdRoute extends Route {
+ model() {
+ return ajax("/admin/config/login-and-authentication/discourse-id");
+ }
+}
diff --git a/frontend/discourse/admin/routes/admin-route-map.js b/frontend/discourse/admin/routes/admin-route-map.js
index 3e59548ca04..2fc10ea30dd 100644
--- a/frontend/discourse/admin/routes/admin-route-map.js
+++ b/frontend/discourse/admin/routes/admin-route-map.js
@@ -246,6 +246,7 @@ export default function () {
});
this.route("authenticators");
this.route("discourseconnect");
+ this.route("discourse-id");
// Lets plugins register routes via register_admin_config_login_route
this.route("plugin-tab", {
path: "/*wildcard",
diff --git a/frontend/discourse/admin/templates/admin-config/login.gjs b/frontend/discourse/admin/templates/admin-config/login.gjs
index ac01c4ac258..fa2da1d2b02 100644
--- a/frontend/discourse/admin/templates/admin-config/login.gjs
+++ b/frontend/discourse/admin/templates/admin-config/login.gjs
@@ -26,6 +26,10 @@ export default class extends Component {
@route="adminConfig.login.settings"
@label="admin.config.login.sub_pages.common_settings.title"
/>
+ <NavItem
+ @route="adminConfig.login.discourse-id"
+ @label="admin.config.login.sub_pages.discourse_id.title"
+ />
<NavItem
@route="adminConfig.login.authenticators"
@label="admin.config.login.sub_pages.authenticators.title"
diff --git a/frontend/discourse/admin/templates/admin-config/login/discourse-id.gjs b/frontend/discourse/admin/templates/admin-config/login/discourse-id.gjs
new file mode 100644
index 00000000000..b8cdb6cbc9b
--- /dev/null
+++ b/frontend/discourse/admin/templates/admin-config/login/discourse-id.gjs
@@ -0,0 +1,140 @@
+import Component from "@glimmer/component";
+import { tracked } from "@glimmer/tracking";
+import { on } from "@ember/modifier";
+import { action } from "@ember/object";
+import { service } from "@ember/service";
+import DButton from "discourse/components/d-button";
+import DToggleSwitch from "discourse/components/d-toggle-switch";
+import { ajax } from "discourse/lib/ajax";
+import { popupAjaxError } from "discourse/lib/ajax-error";
+import { i18n } from "discourse-i18n";
+
+class DiscourseIdAdmin extends Component {
+ @service dialog;
+ @service toasts;
+
+ @tracked isRegenerating = false;
+ @tracked enabled;
+
+ constructor() {
+ super(...arguments);
+ this.enabled = this.args.model.enabled;
+ }
+
+ get regenerateDisabled() {
+ return !this.args.model.configured || this.isRegenerating;
+ }
+
+ @action
+ async regenerateCredentials() {
+ this.dialog.confirm({
+ message: i18n("admin.config.discourse_id.regenerate_confirm"),
+ didConfirm: async () => {
+ this.isRegenerating = true;
+ try {
+ await ajax(
+ "/admin/config/login-and-authentication/discourse-id/regenerate",
+ {
+ type: "POST",
+ }
+ );
+ this.toasts.success({
+ data: {
+ message: i18n("admin.config.discourse_id.regenerate_success"),
+ },
+ duration: 3000,
+ });
+ } catch (error) {
+ popupAjaxError(error);
+ } finally {
+ this.isRegenerating = false;
+ }
+ },
+ });
+ }
+
+ @action
+ async toggleEnabled() {
+ this.enabled = !this.enabled;
+ try {
+ await ajax(
+ "/admin/config/login-and-authentication/discourse-id/settings",
+ {
+ type: "PUT",
+ data: { enabled: this.enabled },
+ }
+ );
+ } catch (error) {
+ this.enabled = !this.enabled;
+ popupAjaxError(error);
+ }
+ }
+
+ <template>
+ <div class="admin-config-area discourse-id-admin">
+ <div class="admin-config-area__primary-content">
+ <section class="admin-config-area-card">
+ <div class="discourse-id-header">
+ <h3 class="admin-config-area-card__title">
+ {{i18n "admin.config.discourse_id.title"}}
+ </h3>
+ <DToggleSwitch
+ @state={{this.enabled}}
+ {{on "click" this.toggleEnabled}}
+ />
+ </div>
+
+ <p class="admin-config-area-card__description">
+ {{i18n "admin.config.discourse_id.description"}}
+ <a
+ href="https://id.discourse.com"
+ target="_blank"
+ rel="noopener noreferrer"
+ >{{i18n "admin.config.discourse_id.learn_more"}}</a>
+ </p>
+
+ <div class="admin-config-area-card__content">
+ <div class="discourse-id-stats">
+ <div class="discourse-id-stats__item">
+ <span class="discourse-id-stats__value">
+ {{@model.stats.total_users}}
+ </span>
+ <span class="discourse-id-stats__label">
+ {{i18n "admin.config.discourse_id.stats.total_users"}}
+ </span>
+ </div>
+ <div class="discourse-id-stats__item">
+ <span class="discourse-id-stats__value">
+ {{@model.stats.signups_30_days}}
+ </span>
+ <span class="discourse-id-stats__label">
+ {{i18n "admin.config.discourse_id.stats.signups_30_days"}}
+ </span>
+ </div>
+ <div class="discourse-id-stats__item">
+ <span class="discourse-id-stats__value">
+ {{@model.stats.logins_30_days}}
+ </span>
+ <span class="discourse-id-stats__label">
+ {{i18n "admin.config.discourse_id.stats.logins_30_days"}}
+ </span>
+ </div>
+ </div>
+
+ <div class="discourse-id-footer">
+ <DButton
+ @action={{this.regenerateCredentials}}
+ @label="admin.config.discourse_id.regenerate_credentials"
+ @disabled={{this.regenerateDisabled}}
+ @isLoading={{this.isRegenerating}}
+ class="btn-default btn-small"
+ />
+ </div>
+ </div>
+ </section>
+ </div>
+ </div>
+ </template>
+}
+
+export default <template><DiscourseIdAdmin @model={{@model}} /></template>
diff --git a/lib/auth/discourse_id_authenticator.rb b/lib/auth/discourse_id_authenticator.rb
index 34cedd6e7be..d9f3d3dfecb 100644
--- a/lib/auth/discourse_id_authenticator.rb
+++ b/lib/auth/discourse_id_authenticator.rb
@@ -48,7 +48,7 @@ class Auth::DiscourseIdAuthenticator < Auth::ManagedAuthenticator
end
def site
- SiteSetting.discourse_id_provider_url.presence || "https://id.discourse.com"
+ DiscourseId.provider_url
end
def register_middleware(omniauth)
diff --git a/lib/discourse_id.rb b/lib/discourse_id.rb
new file mode 100644
index 00000000000..643233ff236
--- /dev/null
+++ b/lib/discourse_id.rb
@@ -0,0 +1,9 @@
+# frozen_string_literal: true
+
+module DiscourseId
+ DEFAULT_PROVIDER_URL = "https://id.discourse.com"
+
+ def self.provider_url
+ SiteSetting.discourse_id_provider_url.presence || DEFAULT_PROVIDER_URL
+ end
+end
diff --git a/spec/lib/discourse_id_spec.rb b/spec/lib/discourse_id_spec.rb
new file mode 100644
index 00000000000..63e963046b1
--- /dev/null
+++ b/spec/lib/discourse_id_spec.rb
@@ -0,0 +1,15 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseId do
+ describe ".provider_url" do
+ it "returns the default URL when setting is blank" do
+ SiteSetting.discourse_id_provider_url = ""
+ expect(described_class.provider_url).to eq("https://id.discourse.com")
+ end
+
+ it "returns the configured URL when setting is present" do
+ SiteSetting.discourse_id_provider_url = "https://custom.example.com"
+ expect(described_class.provider_url).to eq("https://custom.example.com")
+ end
+ end
+end
diff --git a/spec/requests/admin/config/discourse_id_controller_spec.rb b/spec/requests/admin/config/discourse_id_controller_spec.rb
new file mode 100644
index 00000000000..bc099fd942c
--- /dev/null
+++ b/spec/requests/admin/config/discourse_id_controller_spec.rb
@@ -0,0 +1,153 @@
+# frozen_string_literal: true
+
+RSpec.describe Admin::Config::DiscourseIdController do
+ fab!(:admin)
+ fab!(:moderator)
+ fab!(:user)
+
+ let(:client_id) { SecureRandom.hex }
+ let(:client_secret) { SecureRandom.hex }
+
+ before do
+ SiteSetting.discourse_id_client_id = client_id
+ SiteSetting.discourse_id_client_secret = client_secret
+ SiteSetting.enable_discourse_id = true
+ end
+
+ describe "#show" do
+ context "when logged in as an admin" do
+ before { sign_in(admin) }
+
+ it "returns configuration and stats" do
+ recent_user = Fabricate(:user)
+ old_user = Fabricate(:user)
+ Fabricate(
+ :user_associated_account,
+ user: recent_user,
+ provider_name: "discourse_id",
+ provider_uid: SecureRandom.hex,
+ created_at: 10.days.ago,
+ last_used: 5.days.ago,
+ )
+ Fabricate(
+ :user_associated_account,
+ user: old_user,
+ provider_name: "discourse_id",
+ provider_uid: SecureRandom.hex,
+ created_at: 60.days.ago,
+ last_used: 60.days.ago,
+ )
+
+ get "/admin/config/login-and-authentication/discourse-id.json"
+
+ expect(response.status).to eq(200)
+ expect(response.parsed_body).to include(
+ "enabled" => true,
+ "configured" => true,
+ "stats" => {
+ "total_users" => 2,
+ "signups_30_days" => 1,
+ "logins_30_days" => 1,
+ },
+ )
+ end
+
+ it "returns configured as false when credentials are missing" do
+ SiteSetting.discourse_id_client_id = ""
+
+ get "/admin/config/login-and-authentication/discourse-id.json"
+
+ expect(response.status).to eq(200)
+ expect(response.parsed_body["configured"]).to eq(false)
+ end
+ end
+
+ it "is admin only" do
+ get "/admin/config/login-and-authentication/discourse-id.json"
+ expect(response.status).to eq(404)
+
+ sign_in(user)
+ get "/admin/config/login-and-authentication/discourse-id.json"
+ expect(response.status).to eq(404)
+
+ sign_in(moderator)
+ get "/admin/config/login-and-authentication/discourse-id.json"
+ expect(response.status).to eq(403)
+ end
+ end
+
+ describe "#regenerate_credentials" do
+ context "when logged in as an admin" do
+ before { sign_in(admin) }
+
+ it "regenerates credentials successfully" do
+ stub_request(:post, "#{DiscourseId.provider_url}/challenge").to_return(
+ status: 200,
+ body: { domain: Discourse.current_hostname, token: "token" }.to_json,
+ )
+ stub_request(:post, "#{DiscourseId.provider_url}/regenerate").to_return(
+ status: 200,
+ body: { client_id:, client_secret: "new_secret" }.to_json,
+ )
+
+ post "/admin/config/login-and-authentication/discourse-id/regenerate.json"
+
+ expect(response.status).to eq(200)
+ expect(response.parsed_body["success"]).to eq("OK")
+ end
+
+ it "returns error when credentials are not configured" do
+ SiteSetting.discourse_id_client_id = ""
+
+ post "/admin/config/login-and-authentication/discourse-id/regenerate.json"
+
+ expect(response.status).to eq(422)
+ expect(response.parsed_body["error"]).to be_present
+ end
+ end
+
+ it "is admin only" do
+ post "/admin/config/login-and-authentication/discourse-id/regenerate.json"
+ expect(response.status).to eq(404)
+
+ sign_in(moderator)
+ post "/admin/config/login-and-authentication/discourse-id/regenerate.json"
+ expect(response.status).to eq(403)
+ end
+ end
+
+ describe "#update_settings" do
+ context "when logged in as an admin" do
+ before { sign_in(admin) }
+
+ it "updates the enabled setting" do
+ SiteSetting.enable_discourse_id = false
+
+ put "/admin/config/login-and-authentication/discourse-id/settings.json",
+ params: {
+ enabled: true,
+ }
+
+ expect(response.status).to eq(200)
+ expect(SiteSetting.enable_discourse_id).to eq(true)
+ end
+ end
+
+ it "is admin only" do
+ put "/admin/config/login-and-authentication/discourse-id/settings.json",
+ params: {
+ enabled: false,
+ }
+ expect(response.status).to eq(404)
+ expect(SiteSetting.enable_discourse_id).to eq(true)
+
+ sign_in(moderator)
+ put "/admin/config/login-and-authentication/discourse-id/settings.json",
+ params: {
+ enabled: false,
+ }
+ expect(response.status).to eq(403)
+ expect(SiteSetting.enable_discourse_id).to eq(true)
+ end
+ end
+end
diff --git a/spec/services/discourse_id/regenerate_credentials_spec.rb b/spec/services/discourse_id/regenerate_credentials_spec.rb
new file mode 100644
index 00000000000..37a1c22615c
--- /dev/null
+++ b/spec/services/discourse_id/regenerate_credentials_spec.rb
@@ -0,0 +1,105 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseId::RegenerateCredentials do
+ describe "#call" do
+ subject(:result) { described_class.call(guardian:) }
+
+ fab!(:admin)
+
+ let(:guardian) { Guardian.new(admin) }
+ let(:challenge_token) { SecureRandom.hex }
+ let(:client_id) { SecureRandom.hex }
+ let(:client_secret) { SecureRandom.hex }
+ let(:new_client_secret) { SecureRandom.hex }
+ let(:provider_url) { DiscourseId.provider_url }
+
+ before do
+ SiteSetting.discourse_id_client_id = client_id
+ SiteSetting.discourse_id_client_secret = client_secret
+ end
+
+ context "when credentials are not configured" do
+ before { SiteSetting.discourse_id_client_id = "" }
+
+ it { is_expected.to fail_a_policy(:credentials_configured?) }
+ end
+
+ context "when challenge request fails" do
+ before { stub_request(:post, "#{provider_url}/challenge").to_return(status: 503) }
+
+ it { is_expected.to fail_a_step(:request_challenge) }
+ end
+
+ context "when challenge response has domain mismatch" do
+ before do
+ stub_request(:post, "#{provider_url}/challenge").to_return(
+ status: 200,
+ body: { domain: "wrong-domain.com", token: challenge_token }.to_json,
+ )
+ end
+
+ it { is_expected.to fail_a_step(:request_challenge) }
+ end
+
+ context "when regenerate request fails" do
+ before do
+ stub_request(:post, "#{provider_url}/challenge").to_return(
+ status: 200,
+ body: { domain: Discourse.current_hostname, token: challenge_token }.to_json,
+ )
+ stub_request(:post, "#{provider_url}/regenerate").to_return(status: 401)
+ end
+
+ it { is_expected.to fail_a_step(:regenerate_with_challenge) }
+ end
+
+ context "when successful" do
+ before do
+ stub_request(:post, "#{provider_url}/challenge").to_return(
+ status: 200,
+ body: { domain: Discourse.current_hostname, token: challenge_token }.to_json,
+ )
+ stub_request(:post, "#{provider_url}/regenerate").to_return(
+ status: 200,
+ body: { client_id:, client_secret: new_client_secret }.to_json,
+ )
+ end
+
+ it { is_expected.to run_successfully }
+
+ it "updates the client_secret and logs the action" do
+ expect { result }.to change {
+ UserHistory.where(action: UserHistory.actions[:custom_staff]).count
+ }.by(1)
+
+ expect(SiteSetting.discourse_id_client_secret).to eq(new_client_secret)
+ expect(UserHistory.last.custom_type).to eq("discourse_id_regenerate_credentials")
+ end
+ end
+
+ context "when site has a base_path" do
+ before do
+ allow(Discourse).to receive(:base_path).and_return("/forum")
+ stub_request(:post, "#{provider_url}/challenge").to_return(
+ status: 200,
+ body: {
+ domain: Discourse.current_hostname,
+ path: "/forum",
+ token: challenge_token,
+ }.to_json,
+ )
+ stub_request(:post, "#{provider_url}/regenerate").to_return(
+ status: 200,
+ body: { client_id:, client_secret: new_client_secret }.to_json,
+ )
+ end
+
+ it "includes path in challenge request" do
+ result
+ expect(WebMock).to have_requested(:post, "#{provider_url}/challenge").with { |req|
+ JSON.parse(req.body)["path"] == "/forum"
+ }
+ end
+ end
+ end
+end
diff --git a/spec/services/discourse_id/register_spec.rb b/spec/services/discourse_id/register_spec.rb
index 0dc3a23c04e..2a374656e72 100644
--- a/spec/services/discourse_id/register_spec.rb
+++ b/spec/services/discourse_id/register_spec.rb
@@ -2,8 +2,11 @@
RSpec.describe DiscourseId::Register do
describe "#call" do
- subject(:result) { described_class.call(params:) }
+ subject(:result) { described_class.call(params:, guardian:) }
+ fab!(:admin)
+
+ let(:guardian) { Guardian.new(admin) }
let(:params) { { force: false } }
let(:challenge_token) { "test_challenge_token_123" }
let(:client_id) { "test_client_id" }
@@ -51,7 +54,7 @@ RSpec.describe DiscourseId::Register do
allow(Rails.logger).to receive(:error)
result
expect(Rails.logger).to have_received(:error).with(
- /Discourse ID registration failed.*request_challenge.*Network error/m,
+ %r{Discourse ID register failed.*/challenge.*Network error}m,
)
end
end
@@ -70,7 +73,7 @@ RSpec.describe DiscourseId::Register do
allow(Rails.logger).to receive(:error)
result
expect(Rails.logger).to have_received(:error).with(
- /Discourse ID registration failed.*request_challenge.*400.*Bad Request/m,
+ %r{Discourse ID register failed.*/challenge.*400.*Bad Request}m,
)
end
end
@@ -100,7 +103,7 @@ RSpec.describe DiscourseId::Register do
allow(Rails.logger).to receive(:error)
result
expect(Rails.logger).to have_received(:error).with(
- /Discourse ID registration failed.*request_challenge.*Domain mismatch.*expected.*#{Discourse.current_hostname}.*got.*wrong-domain\.com/m,
+ /Discourse ID register failed.*request_challenge.*Domain mismatch.*expected.*#{Discourse.current_hostname}.*got.*wrong-domain\.com/m,
)
end
end
@@ -147,7 +150,7 @@ RSpec.describe DiscourseId::Register do
allow(Rails.logger).to receive(:error)
result
expect(Rails.logger).to have_received(:error).with(
- /Discourse ID registration failed.*register_with_challenge.*Connection timeout/m,
+ %r{Discourse ID register failed.*/register.*Connection timeout}m,
)
end
end