jwt_controller.rb 1.8 KB
Newer Older
K
Kamil Trzcinski 已提交
1 2 3
class JwtController < ApplicationController
  skip_before_action :authenticate_user!
  skip_before_action :verify_authenticity_token
K
Kamil Trzcinski 已提交
4
  before_action :authenticate_project_or_user
K
Kamil Trzcinski 已提交
5

6
  SERVICES = {
K
Kamil Trzcinski 已提交
7
    Auth::ContainerRegistryAuthenticationService::AUDIENCE => Auth::ContainerRegistryAuthenticationService,
D
Douwe Maan 已提交
8
  }.freeze
9

K
Kamil Trzcinski 已提交
10
  def auth
11
    service = SERVICES[params[:service]]
K
Kamil Trzcinski 已提交
12
    return head :not_found unless service
K
Kamil Trzcinski 已提交
13

14 15
    result = service.new(@authentication_result.project, @authentication_result.actor, auth_params)
      .execute(authentication_abilities: @authentication_result.authentication_abilities)
K
Kamil Trzcinski 已提交
16

17
    render json: result, status: result[:http_status]
K
Kamil Trzcinski 已提交
18 19
  end

20
  private
K
Kamil Trzcinski 已提交
21

K
Kamil Trzcinski 已提交
22
  def authenticate_project_or_user
23
    @authentication_result = Gitlab::Auth::Result.new(nil, nil, :none, Gitlab::Auth.read_authentication_abilities)
24

K
Kamil Trzcinski 已提交
25
    authenticate_with_http_basic do |login, password|
26
      @authentication_result = Gitlab::Auth.find_for_git_client(login, password, project: nil, ip: request.ip)
K
Kamil Trzcinski 已提交
27

28
      render_unauthorized unless @authentication_result.success? &&
29
          (@authentication_result.actor.nil? || @authentication_result.actor.is_a?(User))
K
Kamil Trzcinski 已提交
30
    end
31 32 33 34 35
  rescue Gitlab::Auth::MissingPersonalTokenError
    render_missing_personal_token
  end

  def render_missing_personal_token
36 37 38 39 40 41
    render json: {
      errors: [
        { code: 'UNAUTHORIZED',
          message: "HTTP Basic: Access denied\n" \
                   "You have 2FA enabled, please use a personal access token for Git over HTTP.\n" \
                   "You can generate one at #{profile_personal_access_tokens_url}" }
42 43
      ]
    }, status: 401
44 45 46 47 48 49 50
  end

  def render_unauthorized
    render json: {
      errors: [
        { code: 'UNAUTHORIZED',
          message: 'HTTP Basic: Access denied' }
51 52
      ]
    }, status: 401
K
Kamil Trzcinski 已提交
53 54
  end

55
  def auth_params
56
    params.permit(:service, :scope, :account, :client_id)
K
Kamil Trzcinski 已提交
57 58
  end
end