jwt_controller.rb 1.9 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 = {
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
Z
Z.J. van de Weg 已提交
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 29 30 31
      if @authentication_result.failed? ||
          (@authentication_result.actor.present? && !@authentication_result.actor.is_a?(User))
        render_unauthorized
      end
K
Kamil Trzcinski 已提交
32
    end
33 34 35 36 37
  rescue Gitlab::Auth::MissingPersonalTokenError
    render_missing_personal_token
  end

  def render_missing_personal_token
38 39 40 41 42 43
    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}" }
44 45
      ]
    }, status: 401
46 47 48 49 50 51 52
  end

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

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