class Bitodeme::Auth

OAuth2 client credentials authenticator for Bitodeme

Constants

GRANT_TYPE
USER_AGENT

Attributes

access_token[R]
connection[R]
expires_at[R]

Public Class Methods

build() click to toggle source
# File lib/bitodeme/auth.rb, line 9
def self.build
  $bitodeme_auth ||= instance
end
new() click to toggle source
# File lib/bitodeme/auth.rb, line 35
def initialize
  @connection   = build_connection
  @expires_at   = 0
  @access_token = ''
end

Public Instance Methods

inspect() click to toggle source
# File lib/bitodeme/auth.rb, line 19
def inspect
  "#<#{self.class.name}:0x#{(object_id << 1).to_s(16)} " \
    "hostname=\"#{hostname}\" client_id=\"#{client_id}\" " \
    "client_secret=\"#{client_secret}\">"
end
token() click to toggle source

Valid access token for Bitodeme endpoints

# File lib/bitodeme/auth.rb, line 14
def token
  reset_token if expired?
  access_token
end

Private Instance Methods

auth_body() click to toggle source
# File lib/bitodeme/auth.rb, line 71
def auth_body
  @auth_body ||= { token: auth_params }
end
auth_params() click to toggle source
# File lib/bitodeme/auth.rb, line 75
def auth_params
  {
    client_id:     client_id,
    client_secret: client_secret,
    grant_type:    GRANT_TYPE
  }
end
authenticate() click to toggle source
# File lib/bitodeme/auth.rb, line 51
def authenticate
  connection.post('/api/v1/tokens', auth_body).body
end
build_connection() click to toggle source
# File lib/bitodeme/auth.rb, line 55
def build_connection
  Faraday.new(faraday_opts) do |conn|
    conn.request  :json
    conn.response :logger if logging
    conn.response :json, content_type: /\bjson$/
    conn.adapter  Faraday.default_adapter
  end
end
expired?() click to toggle source
# File lib/bitodeme/auth.rb, line 41
def expired?
  Time.now.to_i >= expires_at
end
faraday_opts() click to toggle source
# File lib/bitodeme/auth.rb, line 64
def faraday_opts
  {
    url:     "https://#{hostname}",
    headers: { 'User-Agent' => USER_AGENT }
  }
end
reset_token() click to toggle source
# File lib/bitodeme/auth.rb, line 45
def reset_token
  token         = authenticate.fetch('token', {})
  @access_token = token.fetch('value', '')
  @expires_at   = token.fetch('expires_at', 0)
end