Add impersonation feature for admins

This commit is contained in:
Max Wofford 2025-02-27 03:40:45 -05:00
parent d4a4351625
commit d6dd54289c
4 changed files with 31 additions and 0 deletions

View file

@ -27,6 +27,24 @@ class SessionsController < ApplicationController
end
end
def impersonate
unless current_user.admin?
redirect_to root_path, alert: "You are not authorized to impersonate users"
return
end
session[:impersonater_user_id] ||= current_user.id
user = User.find(params[:id])
session[:user_id] = user.id
redirect_to root_path, notice: "Impersonating #{user.username}"
end
def stop_impersonating
session[:user_id] = session[:impersonater_user_id]
session[:impersonater_user_id] = nil
redirect_to root_path, notice: "Stopped impersonating"
end
def destroy
session[:user_id] = nil
redirect_to root_path, notice: "Signed out!"

View file

@ -37,6 +37,9 @@
(DB: <%= pluralize(QueryCount::Counter.counter, "query") %>, <%= QueryCount::Counter.counter_cache %> cached)
(CACHE: <%= cache_stats[:hits] %> hits, <%= cache_stats[:misses] %> misses)
</p>
<% if session[:impersonater_user_id] %>
<%= link_to "Stop impersonating", stop_impersonating_path, class: "impersonate-link" %>
<% end %>
</div>
</footer>
</body>

View file

@ -4,4 +4,11 @@
class: "avatar",
alt: "#{user.username}'s avatar" if user.avatar_url %>
<%= user.username if user.username %>
<% unless current_user != user %>
<% admin_tool('', 'span') do %>
<%= link_to impersonate_user_path(user), class: "impersonate-link" do %>
🥸
<% end %>
<% end %>
<% end %>
</div>

View file

@ -11,7 +11,10 @@ Rails.application.routes.draw do
constraints AdminConstraint do
mount Avo::Engine, at: Avo.configuration.root_path
mount GoodJob::Engine => "good_job"
get "/impersonate/:id", to: "sessions#impersonate", as: :impersonate_user
end
get "/stop_impersonating", to: "sessions#stop_impersonating", as: :stop_impersonating
# Reveal health status on /up that returns 200 if the app boots with no exceptions, otherwise 500.
# Can be used by load balancers and uptime monitors to verify that the app is live.