summaryrefslogtreecommitdiff
path: root/app/controllers/admin/impersonation_tokens_controller.rb
blob: ddc555add5cbad1c07768c45db8146a82e7587b8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# frozen_string_literal: true

class Admin::ImpersonationTokensController < Admin::ApplicationController
  before_action :user
  before_action :verify_impersonation_enabled!

  feature_category :authentication_and_authorization

  def index
    set_index_vars
  end

  def create
    @impersonation_token = finder.build(impersonation_token_params)

    if @impersonation_token.save
      render json: { new_token: @impersonation_token.token,
                     active_access_tokens: active_impersonation_tokens }, status: :ok
    else
      render json: { errors: @impersonation_token.errors.full_messages }, status: :unprocessable_entity
    end
  end

  def revoke
    @impersonation_token = finder.find(params[:id])

    if @impersonation_token.revoke!
      flash[:notice] = format(_("Revoked impersonation token %{token_name}!"), token_name: @impersonation_token.name)
    else
      flash[:alert] = format(_("Could not revoke impersonation token %{token_name}."), token_name: @impersonation_token.name)
    end

    redirect_to admin_user_impersonation_tokens_path
  end

  private

  # rubocop: disable CodeReuse/ActiveRecord
  def user
    @user ||= User.find_by!(username: params[:user_id])
  end
  # rubocop: enable CodeReuse/ActiveRecord

  def verify_impersonation_enabled!
    access_denied! unless helpers.impersonation_enabled?
  end

  def finder(options = {})
    PersonalAccessTokensFinder.new({ user: user, impersonation: true }.merge(options))
  end

  def active_impersonation_tokens
    tokens = finder(state: 'active', sort: 'expires_at_asc_id_desc').execute
    ::ImpersonationAccessTokenSerializer.new.represent(tokens)
  end

  def impersonation_token_params
    params.require(:personal_access_token).permit(:name, :expires_at, :impersonation, scopes: [])
  end

  def set_index_vars
    @scopes = Gitlab::Auth.available_scopes_for(current_user)

    @impersonation_token ||= finder.build
    @active_impersonation_tokens = active_impersonation_tokens
  end
end