2020-05-15 11:08:04 -04:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
|
|
|
module Impersonation
|
|
|
|
include Gitlab::Utils::StrongMemoize
|
|
|
|
|
2021-09-30 14:11:31 -04:00
|
|
|
SESSION_KEYS_TO_DELETE = %w(
|
|
|
|
github_access_token gitea_access_token gitlab_access_token
|
|
|
|
bitbucket_token bitbucket_refresh_token bitbucket_server_personal_access_token
|
|
|
|
bulk_import_gitlab_access_token fogbugz_token
|
|
|
|
).freeze
|
|
|
|
|
2020-05-15 11:08:04 -04:00
|
|
|
def current_user
|
|
|
|
user = super
|
|
|
|
|
|
|
|
user.impersonator = impersonator if impersonator
|
|
|
|
|
|
|
|
user
|
|
|
|
end
|
|
|
|
|
|
|
|
protected
|
|
|
|
|
|
|
|
def check_impersonation_availability
|
2021-09-30 14:11:31 -04:00
|
|
|
return unless impersonation_in_progress?
|
2020-05-15 11:08:04 -04:00
|
|
|
|
|
|
|
unless Gitlab.config.gitlab.impersonation_enabled
|
|
|
|
stop_impersonation
|
|
|
|
access_denied! _('Impersonation has been disabled')
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
def stop_impersonation
|
|
|
|
log_impersonation_event
|
|
|
|
|
|
|
|
warden.set_user(impersonator, scope: :user)
|
|
|
|
session[:impersonator_id] = nil
|
2021-09-30 14:11:31 -04:00
|
|
|
clear_access_token_session_keys!
|
2020-05-15 11:08:04 -04:00
|
|
|
|
|
|
|
current_user
|
|
|
|
end
|
|
|
|
|
2021-09-30 14:11:31 -04:00
|
|
|
def impersonation_in_progress?
|
|
|
|
session[:impersonator_id].present?
|
|
|
|
end
|
|
|
|
|
2020-05-15 11:08:04 -04:00
|
|
|
def log_impersonation_event
|
|
|
|
Gitlab::AppLogger.info("User #{impersonator.username} has stopped impersonating #{current_user.username}")
|
|
|
|
end
|
|
|
|
|
2021-09-30 14:11:31 -04:00
|
|
|
def clear_access_token_session_keys!
|
|
|
|
access_tokens_keys = session.keys & SESSION_KEYS_TO_DELETE
|
|
|
|
|
|
|
|
access_tokens_keys.each { |key| session.delete(key) }
|
|
|
|
end
|
|
|
|
|
2020-05-15 11:08:04 -04:00
|
|
|
def impersonator
|
|
|
|
strong_memoize(:impersonator) do
|
|
|
|
User.find(session[:impersonator_id]) if session[:impersonator_id]
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|