PageRenderTime 44ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 0ms

/lib/bitbucket/connection.rb

https://bitbucket.org/terrchen/gitlab-ce
Ruby | 67 lines | 51 code | 16 blank | 0 comment | 2 complexity | edaeb4a100778cd85963f01f918776b9 MD5 | raw file
Possible License(s): Apache-2.0, CC0-1.0
  1. module Bitbucket
  2. class Connection
  3. DEFAULT_API_VERSION = '2.0'.freeze
  4. DEFAULT_BASE_URI = 'https://api.bitbucket.org/'.freeze
  5. DEFAULT_QUERY = {}.freeze
  6. attr_reader :expires_at, :expires_in, :refresh_token, :token
  7. def initialize(options = {})
  8. @api_version = options.fetch(:api_version, DEFAULT_API_VERSION)
  9. @base_uri = options.fetch(:base_uri, DEFAULT_BASE_URI)
  10. @default_query = options.fetch(:query, DEFAULT_QUERY)
  11. @token = options[:token]
  12. @expires_at = options[:expires_at]
  13. @expires_in = options[:expires_in]
  14. @refresh_token = options[:refresh_token]
  15. end
  16. def get(path, extra_query = {})
  17. refresh! if expired?
  18. response = connection.get(build_url(path), params: @default_query.merge(extra_query))
  19. response.parsed
  20. end
  21. delegate :expired?, to: :connection
  22. def refresh!
  23. response = connection.refresh!
  24. @token = response.token
  25. @expires_at = response.expires_at
  26. @expires_in = response.expires_in
  27. @refresh_token = response.refresh_token
  28. @connection = nil
  29. end
  30. private
  31. def client
  32. @client ||= OAuth2::Client.new(provider.app_id, provider.app_secret, options)
  33. end
  34. def connection
  35. @connection ||= OAuth2::AccessToken.new(client, @token, refresh_token: @refresh_token, expires_at: @expires_at, expires_in: @expires_in)
  36. end
  37. def build_url(path)
  38. return path if path.starts_with?(root_url)
  39. "#{root_url}#{path}"
  40. end
  41. def root_url
  42. @root_url ||= "#{@base_uri}#{@api_version}"
  43. end
  44. def provider
  45. Gitlab::Auth::OAuth::Provider.config_for('bitbucket')
  46. end
  47. def options
  48. OmniAuth::Strategies::Bitbucket.default_options[:client_options].deep_symbolize_keys
  49. end
  50. end
  51. end