Class: FaradayMiddleware::OAuth2

Inherits:
Faraday::Middleware
  • Object
show all
Defined in:
lib/faraday/oauth2.rb

Instance Method Summary collapse

Constructor Details

#initialize(app, client_id, access_token = nil) ⇒ OAuth2

Returns a new instance of OAuth2.



36
37
38
39
40
# File 'lib/faraday/oauth2.rb', line 36

def initialize(app, client_id, access_token=nil)
  @app = app
  @client_id = client_id
  @access_token = access_token
end

Instance Method Details

#call(env) ⇒ Object



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/faraday/oauth2.rb', line 7

def call(env)

  if env[:method] == :get or env[:method] == :delete
    if env[:url].query.nil?
      query = {}
    else
      query = Faraday::Utils.parse_query(env[:url].query)
    end

    if @access_token and not query["client_secret"]
      env[:url].query = Faraday::Utils.build_query(query.merge(:access_token => @access_token))
      env[:request_headers] = env[:request_headers].merge('Authorization' => "Token token=\"#{@access_token}\"")
    elsif @client_id
      env[:url].query = Faraday::Utils.build_query(query.merge(:client_id => @client_id))
    end
  else
    if @access_token and not env[:body] && env[:body][:client_secret]
      env[:body] = {} if env[:body].nil?
      env[:body] = env[:body].merge(:access_token => @access_token)
      env[:request_headers] = env[:request_headers].merge('Authorization' => "Token token=\"#{@access_token}\"")
    elsif @client_id
      env[:body] = env[:body].merge(:client_id => @client_id)
    end
  end


  @app.call env
end