Skip to content

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

DEV: Allow impersonation without session swapping (#34213)

Ted Johanssonb24a3d81edfe
diff --git a/app/assets/javascripts/discourse/app/components/glimmer-site-header.gjs b/app/assets/javascripts/discourse/app/components/glimmer-site-header.gjs
index 0ac14230106..b16dbdcb888 100644
--- a/app/assets/javascripts/discourse/app/components/glimmer-site-header.gjs
+++ b/app/assets/javascripts/discourse/app/components/glimmer-site-header.gjs
@@ -19,6 +19,7 @@ import {
import { isDocumentRTL } from "discourse/lib/text-direction";
import swipe from "discourse/modifiers/swipe";
import Header from "./header";
+import ImpersonationNotice from "./impersonation-notice";
let _menuPanelClassesToForceDropdown = [];
const PANEL_WIDTH = 340;
@@ -86,6 +87,10 @@ export default class GlimmerSiteHeader extends Component {
}
}
+ get showImpersonationNotice() {
+ return this.currentUser?.is_impersonating;
+ }
+
@bind
debouncedRecalculateHeaderOffset() {
this.recalculationTimer = discourseDebounce(
@@ -438,6 +443,9 @@ export default class GlimmerSiteHeader extends Component {
lockBody=false
}}
>
+ {{#if this.showImpersonationNotice}}
+ <ImpersonationNotice />
+ {{/if}}
<Header
@canSignUp={{@canSignUp}}
@showSidebar={{@showSidebar}}
diff --git a/app/assets/javascripts/discourse/app/components/impersonation-notice.gjs b/app/assets/javascripts/discourse/app/components/impersonation-notice.gjs
new file mode 100644
index 00000000000..b910cd8a4c0
--- /dev/null
+++ b/app/assets/javascripts/discourse/app/components/impersonation-notice.gjs
@@ -0,0 +1,48 @@
+import Component from "@glimmer/component";
+import { tracked } from "@glimmer/tracking";
+import { action } from "@ember/object";
+import { service } from "@ember/service";
+import DButton from "discourse/components/d-button";
+import { ajax } from "discourse/lib/ajax";
+import { popupAjaxError } from "discourse/lib/ajax-error";
+import DiscourseURL from "discourse/lib/url";
+import { i18n } from "discourse-i18n";
+
+export default class ImpersonationNotice extends Component {
+ @service currentUser;
+
+ @tracked stopping = false;
+
+ get impersonatedUserName() {
+ return this.currentUser.username;
+ }
+
+ @action
+ async stopImpersonating() {
+ try {
+ this.stopping = true;
+ await ajax("/admin/impersonate", {
+ type: "DELETE",
+ });
+ DiscourseURL.redirectTo("/");
+ } catch (err) {
+ popupAjaxError(err);
+ this.stopping = false;
+ }
+ }
+
+ <template>
+ <div class="impersonation-notice">
+ <div>{{i18n
+ "impersonation.notice"
+ username=this.impersonatedUserName
+ }}</div>
+ <DButton
+ @action={{this.stopImpersonating}}
+ @isLoading={{this.stopping}}
+ @label="impersonation.stop"
+ class="btn-danger"
+ />
+ </div>
+ </template>
+}
diff --git a/app/assets/stylesheets/common/base/header.scss b/app/assets/stylesheets/common/base/header.scss
index 12a51d5f007..ec2332cf8e4 100644
--- a/app/assets/stylesheets/common/base/header.scss
+++ b/app/assets/stylesheets/common/base/header.scss
@@ -525,3 +525,16 @@ $mobile-avatar-height: 1.532em;
}
}
}
+
+.impersonation-notice {
+ background-color: var(--header_background);
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ padding: 10px;
+ text-align: center;
+
+ button {
+ margin-left: 10px;
+ }
+}
diff --git a/app/controllers/admin/impersonate_controller.rb b/app/controllers/admin/impersonate_controller.rb
index 76df6b32d83..6f031d64f64 100644
--- a/app/controllers/admin/impersonate_controller.rb
+++ b/app/controllers/admin/impersonate_controller.rb
@@ -1,6 +1,8 @@
# frozen_string_literal: true
class Admin::ImpersonateController < Admin::AdminController
+ skip_before_action :ensure_admin, only: :destroy
+
def create
params.require(:username_or_email)
@@ -12,8 +14,27 @@ class Admin::ImpersonateController < Admin::AdminController
# log impersonate
StaffActionLogger.new(current_user).log_impersonate(user)
- # Log on as the user
- log_on_user(user, impersonate: true)
+ if SiteSetting.experimental_impersonation
+ raise Discourse::InvalidAccess if current_user.is_impersonating
+
+ start_impersonating_user(user)
+ else
+ # Log on as the user
+ log_on_user(user, impersonate: true)
+ end
+
+ render body: nil
+ end
+
+ def destroy
+ raise Discourse::NotFound if !SiteSetting.experimental_impersonation
+ raise Discourse::InvalidAccess if !current_user.is_impersonating
+
+ puppet = current_user
+
+ stop_impersonating_user
+
+ StaffActionLogger.new(current_user).log_stop_impersonation(puppet)
render body: nil
end
diff --git a/app/jobs/scheduled/clear_expired_impersonations.rb b/app/jobs/scheduled/clear_expired_impersonations.rb
new file mode 100644
index 00000000000..f9c5c7c6e20
--- /dev/null
+++ b/app/jobs/scheduled/clear_expired_impersonations.rb
@@ -0,0 +1,14 @@
+# frozen_string_literal: true
+
+module Jobs
+ class ClearExpiredImpersonations < ::Jobs::Scheduled
+ every 30.minutes
+
+ def execute(args)
+ UserAuthToken.where("impersonation_expires_at < NOW()").update_all(
+ impersonated_user_id: nil,
+ impersonation_expires_at: nil,
+ )
+ end
+ end
+end
diff --git a/app/models/user.rb b/app/models/user.rb
index 882b286dc6e..799cfbc308a 100644
--- a/app/models/user.rb
+++ b/app/models/user.rb
@@ -257,6 +257,9 @@ class User < ActiveRecord::Base
# Information if user was authenticated with OAuth
attr_accessor :authenticated_with_oauth
+ # Flag used when admin is impersonating a user
+ attr_accessor :is_impersonating
+
scope :with_email,
->(email) { joins(:user_emails).where("lower(user_emails.email) IN (?)", email) }
diff --git a/app/models/user_auth_token.rb b/app/models/user_auth_token.rb
index 3462af3f54e..bda31ddcc07 100644
--- a/app/models/user_auth_token.rb
+++ b/app/models/user_auth_token.rb
@@ -4,6 +4,10 @@ require "digest/sha1"
class UserAuthToken < ActiveRecord::Base
belongs_to :user
+ # Store a reference to the raw association reader, since we're
+ # overriding `#user` later in the class definition.
+ alias_method :acting_user, :user
+
ROTATE_TIME_MINS = 10
ROTATE_TIME = ROTATE_TIME_MINS.minutes
# used when token did not arrive at client
@@ -26,6 +30,22 @@ class UserAuthToken < ActiveRecord::Base
)
end
+ def user
+ impersonated_user || acting_user
+ end
+
+ def impersonated_user
+ return if impersonated_user_id.blank?
+ return if impersonation_expires_at.blank? || impersonation_expires_at.past?
+
+ guardian = Guardian.new(acting_user)
+ puppet = User.find_by(id: impersonated_user_id)
+
+ return if !guardian.can_impersonate?(puppet)
+
+ puppet.tap { |u| u.is_impersonating = true }
+ end
+
def self.log(info)
UserAuthTokenLog.create!(info)
end
@@ -280,21 +300,24 @@ end
# Table name: user_auth_tokens
#
# id :integer not null, primary key
-# user_id :integer not null
# auth_token :string not null
-# prev_auth_token :string not null
-# user_agent :string
# auth_token_seen :boolean default(FALSE), not null
+# authenticated_with_oauth :boolean default(FALSE)
# client_ip :inet
+# impersonation_expires_at :datetime
+# prev_auth_token :string not null
# rotated_at :datetime not null
+# seen_at :datetime
+# user_agent :string
# created_at :datetime not null
# updated_at :datetime not null
-# seen_at :datetime
-# authenticated_with_oauth :boolean default(FALSE)
+# impersonated_user_id :integer
+# user_id :integer not null
#
# Indexes
#
-# index_user_auth_tokens_on_auth_token (auth_token) UNIQUE
-# index_user_auth_tokens_on_prev_auth_token (prev_auth_token) UNIQUE
-# index_user_auth_tokens_on_user_id (user_id)
+# index_user_auth_tokens_on_auth_token (auth_token) UNIQUE
+# index_user_auth_tokens_on_impersonation_expires_at (impersonation_expires_at) WHERE (impersonation_expires_at IS NOT NULL)
+# index_user_auth_tokens_on_prev_auth_token (prev_auth_token) UNIQUE
+# index_user_auth_tokens_on_user_id (user_id)
#
diff --git a/app/models/user_history.rb b/app/models/user_history.rb
index 1984a9a26e2..80a510e3de6 100644
--- a/app/models/user_history.rb
+++ b/app/models/user_history.rb
@@ -157,6 +157,7 @@ class UserHistory < ActiveRecord::Base
tag_group_change: 118,
delete_associated_accounts: 119,
change_theme_site_setting: 120,
+ stop_impersonating: 121,
)
end
@@ -280,6 +281,7 @@ class UserHistory < ActiveRecord::Base
update_flag
create_flag
change_theme_site_setting
+ stop_impersonating
]
end
diff --git a/app/serializers/current_user_serializer.rb b/app/serializers/current_user_serializer.rb
index c63a42160eb..abe8da7a2e5 100644
--- a/app/serializers/current_user_serializer.rb
+++ b/app/serializers/current_user_serializer.rb
@@ -81,7 +81,8 @@ class CurrentUserSerializer < BasicUserSerializer
:can_localize_content?,
:effective_locale,
:use_reviewable_ui_refresh,
- :can_see_ip
+ :can_see_ip,
+ :is_impersonating
delegate :user_stat, to: :object, private: true
delegate :any_posts, :draft_count, :pending_posts_count, :read_faq?, to: :user_stat
@@ -101,6 +102,10 @@ class CurrentUserSerializer < BasicUserSerializer
@options[:login_method]
end
+ def is_impersonating
+ !!object.is_impersonating
+ end
+
def groups
owned_group_ids = GroupUser.where(user_id: id, owner: true).pluck(:group_id).to_set
diff --git a/app/services/staff_action_logger.rb b/app/services/staff_action_logger.rb
index d98204e1b5b..280a24c486a 100644
--- a/app/services/staff_action_logger.rb
+++ b/app/services/staff_action_logger.rb
@@ -566,6 +566,12 @@ class StaffActionLogger
)
end
+ def log_stop_impersonation(user, opts = {})
+ UserHistory.create!(
+ params(opts).merge(action: UserHistory.actions[:stop_impersonating], target_user_id: user.id),
+ )
+ end
+
def log_roll_up(subnet, ips, opts = {})
UserHistory.create!(
params(opts).merge(
diff --git a/config/locales/client.en.yml b/config/locales/client.en.yml
index e4ee6e79e7c..da03cb3ebc1 100644
--- a/config/locales/client.en.yml
+++ b/config/locales/client.en.yml
@@ -326,6 +326,10 @@ en:
anonymous_members: ""
search: "Search"
+ impersonation:
+ notice: "You are impersonating %{username}"
+ stop: "Stop impersonating"
+
themes:
default_description: "Default"
broken_theme_alert: "Your site may not work because a theme / component has errors. Check the browser console for more information."
diff --git a/config/locales/server.en.yml b/config/locales/server.en.yml
index 8fc20e2c4a8..6970a04e419 100644
--- a/config/locales/server.en.yml
+++ b/config/locales/server.en.yml
@@ -2743,6 +2743,8 @@ en:
show_preview_for_form_templates: "Enable the preview for form templates feature"
lazy_load_categories_groups: "Lazy load category information only for users of these groups. This improves performance on sites with many categories."
experimental_auto_grid_images: "Automatically wraps images in [grid] tags when 3 or more images are uploaded in the composer."
+ experimental_impersonation: "Impersonate a user without having to log out of your admin account."
+ experimental_impersonation_time_limit_minutes: "How long before an impersonation session is automatically ended."
page_loading_indicator: "Configure the loading indicator which appears during page navigations within Discourse. 'Spinner' is a full page indicator. 'Slider' shows a narrow bar at the top of the screen."
show_user_menu_avatars: "Show user avatars in the user menu"
about_page_hidden_groups: "Do not show members of specific groups on the /about page."
diff --git a/config/routes.rb b/config/routes.rb
index 6e6595a2379..266a2fd77db 100644
--- a/config/routes.rb
+++ b/config/routes.rb
@@ -99,6 +99,9 @@ Discourse::Application.routes.draw do
get "wizard/steps/:id" => "wizard#index"
put "wizard/steps/:id" => "steps#update"
+ delete "admin/impersonate" => "admin/impersonate#destroy",
+ :constraints => ImpersonatorConstraint.new
+
namespace :admin, constraints: StaffConstraint.new do
get "" => "admin#index"
get "search" => "search#index"
diff --git a/config/site_settings.yml b/config/site_settings.yml
index 7c6b6c92f3d..884cce917a1 100644
--- a/config/site_settings.yml
+++ b/config/site_settings.yml
@@ -4094,6 +4094,12 @@ experimental:
experimental_form_templates:
client: true
default: false
+ experimental_impersonation:
+ default: false
+ hidden: true
+ experimental_impersonation_time_limit_minutes:
+ default: 15
+ hidden: true
show_preview_for_form_templates:
client: true
default: true
diff --git a/db/migrate/20250811070948_add_impersonated_user_fields_to_user_auth_token.rb b/db/migrate/20250811070948_add_impersonated_user_fields_to_user_auth_token.rb
new file mode 100644
index 00000000000..14bd4730281
--- /dev/null
+++ b/db/migrate/20250811070948_add_impersonated_user_fields_to_user_auth_token.rb
@@ -0,0 +1,11 @@
+# frozen_string_literal: true
+class AddImpersonatedUserFieldsToUserAuthToken < ActiveRecord::Migration[8.0]
+ def change
+ add_column :user_auth_tokens, :impersonated_user_id, :integer
+ add_column :user_auth_tokens, :impersonation_expires_at, :datetime
+
+ add_index :user_auth_tokens,
+ %i[impersonation_expires_at],
+ where: "impersonation_expires_at IS NOT NULL"
+ end
+end
diff --git a/lib/auth/current_user_provider.rb b/lib/auth/current_user_provider.rb
index ed214aca7b4..9594a1c5ff4 100644
--- a/lib/auth/current_user_provider.rb
+++ b/lib/auth/current_user_provider.rb
@@ -23,6 +23,14 @@ class Auth::CurrentUserProvider
def refresh_session(user, session, cookie_jar)
end
+ # Optional interface for implementing impersonation.
+ def start_impersonating_user(user)
+ end
+
+ # Optional interface for implementing impersonation.
+ def stop_impersonating_user
+ end
+
# api has special rights return true if api was detected
def is_api?
raise NotImplementedError
diff --git a/lib/auth/default_current_user_provider.rb b/lib/auth/default_current_user_provider.rb
index dc544ea0fc6..8ef8e72466f 100644
--- a/lib/auth/default_current_user_provider.rb
+++ b/lib/auth/default_current_user_provider.rb
@@ -281,6 +281,21 @@ class Auth::DefaultCurrentUserProvider
@env[CURRENT_USER_KEY] = user
end
+ def start_impersonating_user(user)
+ @user_token.update!(
+ impersonated_user_id: user.id,
+ impersonation_expires_at:
+ SiteSetting.experimental_impersonation_time_limit_minutes.minutes.from_now,
+ )
+ end
+
+ def stop_impersonating_user
+ @user_token.update!(impersonated_user_id: nil, impersonation_expires_at: nil)
+ # Clear memoization of `current_user` so we can get the acting user back in
+ # the context of the same request.
+ @env.delete(CURRENT_USER_KEY)
+ end
+
def set_auth_cookie!(unhashed_auth_token, user, cookie_jar)
data = {
token: unhashed_auth_token,
diff --git a/lib/current_user.rb b/lib/current_user.rb
index fdf78431981..05dd8d67b74 100644
--- a/lib/current_user.rb
+++ b/lib/current_user.rb
@@ -23,6 +23,14 @@ module CurrentUser
current_user_provider.log_off_user(session, cookies)
end
+ def start_impersonating_user(user)
+ current_user_provider.start_impersonating_user(user)
+ end
+
+ def stop_impersonating_user
+ current_user_provider.stop_impersonating_user
+ end
+
def is_api?
current_user_provider.is_api?
end
diff --git a/lib/impersonator_constraint.rb b/lib/impersonator_constraint.rb
new file mode 100644
index 00000000000..c862bb17eb9
--- /dev/null
+++ b/lib/impersonator_constraint.rb
@@ -0,0 +1,10 @@
+# frozen_string_literal: true
+
+class ImpersonatorConstraint
+ def matches?(request)
+ current_user = CurrentUser.lookup_from_env(request.env)
+ !!current_user&.is_impersonating
+ rescue Discourse::InvalidAccess, Discourse::ReadOnly
+ false
+ end
+end
diff --git a/spec/models/user_auth_token_spec.rb b/spec/models/user_auth_token_spec.rb
index 901e6683969..1102bccf76d 100644
--- a/spec/models/user_auth_token_spec.rb
+++ b/spec/models/user_auth_token_spec.rb
@@ -4,6 +4,68 @@ require "discourse_ip_info"
RSpec.describe UserAuthToken do
fab!(:user)
+ fab!(:admin)
+
+ describe "#user" do
+ context "when no impersonation is happening" do
+ it "returns the user associated with the session" do
+ token =
+ UserAuthToken.generate!(
+ user_id: user.id,
+ user_agent: "some user agent 2",
+ client_ip: "1.1.2.3",
+ )
+
+ expect(token.user).to eq(user)
+ expect(token.user.is_impersonating).to be_falsey
+ end
+ end
+
+ context "when impersonating another user" do
+ it "returns the user being impersonated if not expired" do
+ token =
+ UserAuthToken.generate!(
+ user_id: admin.id,
+ user_agent: "some user agent 2",
+ client_ip: "1.1.2.3",
+ )
+
+ token.update!(impersonated_user_id: user.id, impersonation_expires_at: 15.minutes.from_now)
+
+ expect(token.user).to eq(user)
+ expect(token.user.is_impersonating).to eq(true)
+ end
+
+ it "returns the user associated with the session if expired" do
+ token =
+ UserAuthToken.generate!(
+ user_id: admin.id,
+ user_agent: "some user agent 2",
+ client_ip: "1.1.2.3",
+ )
+
+ token.update!(impersonated_user_id: user.id, impersonation_expires_at: 1.hour.ago)
+
+ expect(token.user).to eq(admin)
+ expect(token.user.is_impersonating).to be_falsey
+ end
+
+ it "returns the user associated with the session if can no longer impersonate" do
+ token =
+ UserAuthToken.generate!(
+ user_id: admin.id,
+ user_agent: "some user agent 2",
+ client_ip: "1.1.2.3",
+ )
+
+ token.update!(impersonated_user_id: user.id, impersonation_expires_at: 15.minutes.from_now)
+ Guardian.any_instance.stubs(:can_impersonate?).returns(false)
+
+ expect(token.user).to eq(admin)
+ expect(token.user.is_impersonating).to be_falsey
+ end
+ end
+ end
describe ".cleanup!" do
it "can remove old expired tokens" do
diff --git a/spec/requests/admin/impersonate_controller_spec.rb b/spec/requests/admin/impersonate_controller_spec.rb
index 3be306b81ff..1f1d24dff42 100644
--- a/spec/requests/admin/impersonate_controller_spec.rb
+++ b/spec/requests/admin/impersonate_controller_spec.rb
@@ -61,6 +61,18 @@ RSpec.describe Admin::ImpersonateController do
expect(session[:current_user_id]).to eq(admin.id)
end
+ context "when using experimental impersonation feature" do
+ it "raises an invalid access error if admin is already impersonating someone" do
+ SiteSetting.experimental_impersonation = true
+ User.any_instance.stubs(:is_impersonating).returns(true)
+
+ post "/admin/impersonate.json", params: { username_or_email: user.username }
+
+ expect(response.status).to eq(403)
+ expect(session[:current_user_id]).to eq(admin.id)
+ end
+ end
+
context "with success" do
it "succeeds and logs the impersonation" do
expect do
@@ -106,4 +118,34 @@ RSpec.describe Admin::ImpersonateController do
end
end
end
+
+ describe "#destroy" do
+ before { sign_in(admin) }
+
+ it "raises a not found error when experimental impersonation is disabled" do
+ SiteSetting.experimental_impersonation = false
+
+ delete "/admin/impersonate.json"
+
+ expect(response.status).to eq(404)
+ end
+
+ it "does not pass routing constraint when current user is not impersonating" do
+ SiteSetting.experimental_impersonation = true
+ User.any_instance.stubs(:is_impersonating).returns(false)
+
+ delete "/admin/impersonate.json"
+
+ expect(response.status).to eq(404)
+ end
+
+ it "stops impersonating" do
+ SiteSetting.experimental_impersonation = true
+ User.any_instance.stubs(:is_impersonating).returns(true)
+
+ delete "/admin/impersonate.json"
+
+ expect(response.status).to eq(200)
+ end
+ end
end
diff --git a/spec/system/impersonation_spec.rb b/spec/system/impersonation_spec.rb
new file mode 100644
index 00000000000..96a658bb286
--- /dev/null
+++ b/spec/system/impersonation_spec.rb
@@ -0,0 +1,31 @@
+# frozen_string_literal: true
+
+describe "Impersonation", type: :system do
+ fab!(:admin)
+ fab!(:user)
+
+ before do
+ SiteSetting.experimental_impersonation = true
+
+ sign_in(admin)
+ end
+
+ it "allows you to start and stop impersonating with the click of a button" do
+ visit("/admin/users/#{user.id}/#{user.username}")
+
+ page.find(".btn-impersonate").click
+
+ expect(page).to have_current_path("/")
+ expect(page).to have_css(
+ ".impersonation-notice",
+ text: I18n.t("js.impersonation.notice", username: user.username),
+ )
+
+ visit("/latest")
+
+ page.find(".impersonation-notice .btn-danger").click
+
+ expect(page).to have_current_path("/")
+ expect(page).to have_no_css(".impersonation-notice")
+ end
+end