Class: FaradayMiddleware::OAuth2

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

Overview

Public: A simple middleware that adds an access token to each request.

The token is added as both “access_token” query parameter and the “Authorization” HTTP request header. However, an explicit “access_token” parameter or “Authorization” header for the current request are not overriden.

Examples

# configure default token:
OAuth2.new(app, 'abc123')

# configure query parameter name:
OAuth2.new(app, 'abc123', :param_name => 'my_oauth_token')

# default token value is optional:
OAuth2.new(app, :param_name => 'my_oauth_token')

Constant Summary collapse

PARAM_NAME =
'access_token'.freeze
AUTH_HEADER =
'Authorization'.freeze

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

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

Returns a new instance of OAuth2.

Raises:

  • (ArgumentError)


43
44
45
46
47
48
49
# File 'lib/faraday_middleware/request/oauth2.rb', line 43

def initialize(app, token = nil, options = {})
  super(app)
  options, token = token, nil if token.is_a? Hash
  @token = token && token.to_s
  @param_name = options.fetch(:param_name, PARAM_NAME).to_s
  raise ArgumentError, ":param_name can't be blank" if @param_name.empty?
end

Instance Attribute Details

#param_nameObject (readonly)

Returns the value of attribute param_name.



27
28
29
# File 'lib/faraday_middleware/request/oauth2.rb', line 27

def param_name
  @param_name
end

Instance Method Details

#call(env) ⇒ Object



32
33
34
35
36
37
38
39
40
41
# File 'lib/faraday_middleware/request/oauth2.rb', line 32

def call(env)
  params = { param_name => @token }.update query_params(env[:url])

  if token = params[param_name] and !token.empty?
    env[:url].query = build_query params
    env[:request_headers][AUTH_HEADER] ||= %(Token token="#{token}")
  end

  @app.call env
end

#query_params(url) ⇒ Object



51
52
53
54
55
56
57
# File 'lib/faraday_middleware/request/oauth2.rb', line 51

def query_params(url)
  if url.query.nil? or url.query.empty?
    {}
  else
    parse_query url.query
  end
end