jwt_controller.rb 1.83 KB
Newer Older
Kamil Trzcinski's avatar
Kamil Trzcinski committed
1
2
3
class JwtController < ApplicationController
  skip_before_action :authenticate_user!
  skip_before_action :verify_authenticity_token
Kamil Trzcinski's avatar
Kamil Trzcinski committed
4
  before_action :authenticate_project_or_user
Kamil Trzcinski's avatar
Kamil Trzcinski committed
5

6
  SERVICES = {
Kamil Trzcinski's avatar
Kamil Trzcinski committed
7
    Auth::ContainerRegistryAuthenticationService::AUDIENCE => Auth::ContainerRegistryAuthenticationService,
Douwe Maan's avatar
Douwe Maan committed
8
  }.freeze
9

Kamil Trzcinski's avatar
Kamil Trzcinski committed
10
  def auth
11
    service = SERVICES[params[:service]]
Kamil Trzcinski's avatar
Kamil Trzcinski committed
12
    return head :not_found unless service
Kamil Trzcinski's avatar
Kamil Trzcinski committed
13

14
    result = service.new(@authentication_result.project, @authentication_result.actor, auth_params).
15
      execute(authentication_abilities: @authentication_result.authentication_abilities)
Kamil Trzcinski's avatar
Kamil Trzcinski committed
16

17
    render json: result, status: result[:http_status]
Kamil Trzcinski's avatar
Kamil Trzcinski committed
18
19
  end

20
  private
Kamil Trzcinski's avatar
Kamil Trzcinski committed
21

Kamil Trzcinski's avatar
Kamil Trzcinski committed
22
  def authenticate_project_or_user
23
    @authentication_result = Gitlab::Auth::Result.new(nil, nil, :none, Gitlab::Auth.read_authentication_abilities)
24

Kamil Trzcinski's avatar
Kamil Trzcinski committed
25
    authenticate_with_http_basic do |login, password|
26
      @authentication_result = Gitlab::Auth.find_for_git_client(login, password, project: nil, ip: request.ip)
Kamil Trzcinski's avatar
Kamil Trzcinski committed
27

28
      render_unauthorized unless @authentication_result.success? &&
29
          (@authentication_result.actor.nil? || @authentication_result.actor.is_a?(User))
Kamil Trzcinski's avatar
Kamil Trzcinski committed
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
42
43
44
45
46
47
48
49
50
    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}" }
      ] }, status: 401
  end

  def render_unauthorized
    render json: {
      errors: [
        { code: 'UNAUTHORIZED',
          message: 'HTTP Basic: Access denied' }
      ] }, status: 401
Kamil Trzcinski's avatar
Kamil Trzcinski committed
51
52
  end

53
  def auth_params
54
    params.permit(:service, :scope, :account, :client_id)
Kamil Trzcinski's avatar
Kamil Trzcinski committed
55
56
  end
end