lib/centro/client.rb in centro-client-0.0.2 vs lib/centro/client.rb in centro-client-0.0.3

- old
+ new

@@ -1,9 +1,12 @@ require 'omniauth' require 'omniauth-oauth2' require 'faraday_middleware' +require 'centro/errors' +require 'centro/api/base' + module Centro class Client class << self def api_version return @api_version if defined?(@api_version) @@ -11,10 +14,14 @@ end def auth_host return @auth_host if defined?(@auth_host) @auth_host = 'localhost:3001' end + def finance_host + return @finance_host if defined?(@finance_host) + @finance_host = 'localhost:4000' + end def mms_host return @mms_host if defined?(@mms_host) @mms_host = 'localhost:3000' end def ssl_enabled? @@ -22,27 +29,34 @@ @ssl_enaabled = false end def auth_url url_from_host(auth_host) end + def finance_url + url_from_host(finance_host) + end def mms_url url_from_host(mms_host) end def url_from_host(host) (ssl_enabled? ? 'https://' : 'http://') + host + "/api/#{self.api_version}" end end - attr_accessor :client_id, :client_secret, :access_token + attr_accessor :client_id, :client_secret, :access_token, :access_token_expires_at def initialize(opts={}) @client_id = opts.delete(:client_id) if opts[:client_id] @client_secret = opts.delete(:client_secret) if opts[:client_secret] @access_token = opts.delete(:access_token) if opts[:access_token] end + def access_token_expired? + access_token_expires_at.nil? || access_token_expires_at < Time.now + end + def retrieve_access_token(username, password) raise 'client_id and client_secret required' unless @client_id && @client_secret connection = Faraday.new self.class.auth_url do |conn| set_default_connection_options(conn) end @@ -50,10 +64,11 @@ :grant_type => 'password', :client_id => @client_id, :client_secret => @client_secret, :username => username, :password => password) + self.access_token_expires_at = Time.now + response.body.expires_in self.access_token = response.body.access_token end def get_credentials @@ -112,9 +127,18 @@ def auth_connection raise 'access_token required' unless @access_token @auth_connection ||= begin Faraday.new self.class.auth_url do |conn| + conn.request :oauth2, @access_token + set_default_connection_options(conn) + end + end + end + def finance_connection + raise 'access_token required' unless @access_token + @finance_connection ||= begin + Faraday.new self.class.finance_url do |conn| conn.request :oauth2, @access_token set_default_connection_options(conn) end end end