Class: FaradayMiddleware::OAuth2Refresh

Inherits:
Faraday::Middleware
  • Object
show all
Extended by:
Forwardable
Defined in:
lib/faraday_middleware/oauth2_refresh.rb

Constant Summary collapse

AUTH_HEADER =
'Authorization'.freeze

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(app = nil, token = nil, options = {}) ⇒ OAuth2Refresh

Returns a new instance of OAuth2Refresh.



30
31
32
33
# File 'lib/faraday_middleware/oauth2_refresh.rb', line 30

def initialize(app=nil, token=nil, options={})
  super(app)
  @oauth2_token = token
end

Instance Attribute Details

#oauth2_tokenObject (readonly)

Returns the value of attribute oauth2_token.



9
10
11
# File 'lib/faraday_middleware/oauth2_refresh.rb', line 9

def oauth2_token
  @oauth2_token
end

Instance Method Details

#call(env) ⇒ Object



13
14
15
16
17
18
19
20
21
22
23
# File 'lib/faraday_middleware/oauth2_refresh.rb', line 13

def call(env)
  if @oauth2_token.expired?
  	@oauth2_token = @oauth2_token.refresh!({:headers => {'Authorization' => 'Basic ' + get_api_key()}})
  end
  
  if @oauth2_token.token.to_s.length>0
    env[:request_headers][AUTH_HEADER] = %(Bearer #{@oauth2_token.token.to_s})
  end

  @app.call env
end

#get_api_keyObject



25
26
27
28
# File 'lib/faraday_middleware/oauth2_refresh.rb', line 25

def get_api_key()
  api_key = Base64::encode64("#{@oauth2_token.client.id.to_s}:#{@oauth2_token.client.secret.to_s}").gsub(/[\s\t\r\n]/,'')
  return api_key
end