Class: FaradayMiddleware::BingbongOAuth

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

Constant Summary collapse

AUTH_HEADER =
'Authorization'
CONTENT_TYPE =
'Content-Type'
TYPE_URLENCODED =
'application/x-www-form-urlencoded'

Instance Method Summary collapse

Constructor Details

#initialize(app, options) ⇒ BingbongOAuth

Returns a new instance of BingbongOAuth.



12
13
14
15
# File 'lib/fellowshipone/bingbong_oauth.rb', line 12

def initialize(app, options)
  super(app)
  @options = options
end

Instance Method Details

#body_params(env) ⇒ Object



43
44
45
46
47
48
49
50
51
# File 'lib/fellowshipone/bingbong_oauth.rb', line 43

def body_params(env)
  if include_body_params?(env)
    if env[:body].respond_to?(:to_str)
      parse_nested_query env[:body]
    else
      env[:body]
    end
  end || {}
end

#call(env) ⇒ Object



17
18
19
20
# File 'lib/fellowshipone/bingbong_oauth.rb', line 17

def call(env)
  env[:request_headers][AUTH_HEADER] ||= oauth_header(env).to_s if sign_request?(env)
  @app.call(env)
end

#include_body_params?(env) ⇒ Boolean

Returns:

  • (Boolean)


53
54
55
56
# File 'lib/fellowshipone/bingbong_oauth.rb', line 53

def include_body_params?(env)
  # see RFC 5849, section 3.4.1.3.1 for details
  !(type = env[:request_headers][CONTENT_TYPE]) || (type == TYPE_URLENCODED)
end

#oauth_header(env) ⇒ Object



22
23
24
25
26
27
28
29
# File 'lib/fellowshipone/bingbong_oauth.rb', line 22

def oauth_header(env)
  SimpleOAuth::Header.new(
    env[:method],
    env[:url].to_s,
    signature_params(body_params(env)),
    oauth_options(env)
  )
end

#oauth_options(env) ⇒ Object



35
36
37
38
39
40
41
# File 'lib/fellowshipone/bingbong_oauth.rb', line 35

def oauth_options(env)
  if (extra = env[:request][:oauth]) && extra.is_a?(Hash) && !extra.empty?
    @options.merge extra
  else
    @options
  end
end

#sign_request?(env) ⇒ Boolean

Returns:

  • (Boolean)


31
32
33
# File 'lib/fellowshipone/bingbong_oauth.rb', line 31

def sign_request?(env)
  !!env[:request].fetch(:oauth, true)
end

#signature_params(params) ⇒ Object



58
59
60
61
62
63
64
# File 'lib/fellowshipone/bingbong_oauth.rb', line 58

def signature_params(params)
  if params.empty?
    params
  else
    params.reject { |_k, v| v.respond_to?(:content_type) }
  end
end