2016-08-22 14:42:26 -04:00
|
|
|
module Bitbucket
|
|
|
|
class Connection
|
2017-02-21 18:32:18 -05:00
|
|
|
DEFAULT_API_VERSION = '2.0'.freeze
|
|
|
|
DEFAULT_BASE_URI = 'https://api.bitbucket.org/'.freeze
|
|
|
|
DEFAULT_QUERY = {}.freeze
|
2016-08-22 14:42:26 -04:00
|
|
|
|
2016-12-15 07:19:28 -05:00
|
|
|
attr_reader :expires_at, :expires_in, :refresh_token, :token
|
|
|
|
|
2016-08-22 14:42:26 -04:00
|
|
|
def initialize(options = {})
|
2016-12-07 04:33:32 -05:00
|
|
|
@api_version = options.fetch(:api_version, DEFAULT_API_VERSION)
|
|
|
|
@base_uri = options.fetch(:base_uri, DEFAULT_BASE_URI)
|
2016-11-20 00:44:19 -05:00
|
|
|
@default_query = options.fetch(:query, DEFAULT_QUERY)
|
2016-08-22 14:42:26 -04:00
|
|
|
|
2016-11-20 00:44:19 -05:00
|
|
|
@token = options[:token]
|
|
|
|
@expires_at = options[:expires_at]
|
|
|
|
@expires_in = options[:expires_in]
|
|
|
|
@refresh_token = options[:refresh_token]
|
2016-11-11 19:08:03 -05:00
|
|
|
end
|
2016-08-22 14:42:26 -04:00
|
|
|
|
2016-11-20 00:44:19 -05:00
|
|
|
def get(path, extra_query = {})
|
2016-08-22 14:42:26 -04:00
|
|
|
refresh! if expired?
|
|
|
|
|
2016-11-20 00:44:19 -05:00
|
|
|
response = connection.get(build_url(path), params: @default_query.merge(extra_query))
|
2016-08-22 14:42:26 -04:00
|
|
|
response.parsed
|
|
|
|
end
|
|
|
|
|
2017-02-22 12:51:46 -05:00
|
|
|
delegate :expired?, to: :connection
|
2016-08-22 14:42:26 -04:00
|
|
|
|
|
|
|
def refresh!
|
|
|
|
response = connection.refresh!
|
|
|
|
|
|
|
|
@token = response.token
|
|
|
|
@expires_at = response.expires_at
|
|
|
|
@expires_in = response.expires_in
|
|
|
|
@refresh_token = response.refresh_token
|
2016-12-06 10:12:11 -05:00
|
|
|
@connection = nil
|
2016-08-22 14:42:26 -04:00
|
|
|
end
|
|
|
|
|
|
|
|
private
|
|
|
|
|
2016-12-12 09:16:51 -05:00
|
|
|
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
|
|
|
|
|
2016-08-22 14:42:26 -04:00
|
|
|
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
|
2016-12-07 04:33:32 -05:00
|
|
|
Gitlab::OAuth::Provider.config_for('bitbucket')
|
2016-08-22 14:42:26 -04:00
|
|
|
end
|
|
|
|
|
|
|
|
def options
|
|
|
|
OmniAuth::Strategies::Bitbucket.default_options[:client_options].deep_symbolize_keys
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|