connection.rb 1.81 KB
Newer Older
1
2
# frozen_string_literal: true

3
4
module Bitbucket
  class Connection
5
6
    DEFAULT_API_VERSION = '2.0'
    DEFAULT_BASE_URI    = 'https://api.bitbucket.org/'
Douwe Maan's avatar
Douwe Maan committed
7
    DEFAULT_QUERY       = {}.freeze
8

9
10
    attr_reader :expires_at, :expires_in, :refresh_token, :token

11
    def initialize(options = {})
12
13
      @api_version   = options.fetch(:api_version, DEFAULT_API_VERSION)
      @base_uri      = options.fetch(:base_uri, DEFAULT_BASE_URI)
14
      @default_query = options.fetch(:query, DEFAULT_QUERY)
15

16
17
18
19
      @token         = options[:token]
      @expires_at    = options[:expires_at]
      @expires_in    = options[:expires_in]
      @refresh_token = options[:refresh_token]
Stan Hu's avatar
Stan Hu committed
20
    end
21

22
    def get(path, extra_query = {})
23
24
      refresh! if expired?

25
      response = connection.get(build_url(path), params: @default_query.merge(extra_query))
26
27
28
      response.parsed
    end

Douwe Maan's avatar
Douwe Maan committed
29
    delegate :expired?, to: :connection
30
31
32
33
34
35
36
37

    def refresh!
      response = connection.refresh!

      @token         = response.token
      @expires_at    = response.expires_at
      @expires_in    = response.expires_in
      @refresh_token = response.refresh_token
38
      @connection    = nil
39
40
41
42
    end

    private

43
44
45
46
47
48
49
50
    def client
      @client ||= OAuth2::Client.new(provider.app_id, provider.app_secret, options)
    end

    def connection
      @connection ||= OAuth2::AccessToken.new(client, @token, refresh_token: @refresh_token, expires_at: @expires_at, expires_in: @expires_in)
    end

51
52
53
54
55
56
57
58
59
60
61
    def build_url(path)
      return path if path.starts_with?(root_url)

      "#{root_url}#{path}"
    end

    def root_url
      @root_url ||= "#{@base_uri}#{@api_version}"
    end

    def provider
62
      Gitlab::Auth::OAuth::Provider.config_for('bitbucket')
63
64
65
66
67
68
69
    end

    def options
      OmniAuth::Strategies::Bitbucket.default_options[:client_options].deep_symbolize_keys
    end
  end
end