Sha256: 9ed462c169bc6a5092d12feb83a26f908c997460e157d5d5c729191cc71fb5a5

Contents?: true

Size: 1.72 KB

Versions: 3

Compression:

Stored size: 1.72 KB

Contents

require 'faraday'

module FaradayMiddleware
  # Public: Uses the simple_oauth library to sign requests according the
  # OAuth protocol.
  #
  # The options for this middleware are forwarded to SimpleOAuth::Header:
  # :consumer_key, :consumer_secret, :token, :token_secret. All these
  # parameters are optional.
  #
  # The signature is added to the "Authorization" HTTP request header. If the
  # value for this header already exists, it is not overriden.
  #
  # For requests that have parameters in the body, such as POST, this
  # middleware expects them to be in Hash form, i.e. not encoded to string.
  # This means this middleware has to be positioned on the stack before any
  # encoding middleware such as UrlEncoded.
  class OAuth < Faraday::Middleware
    dependency 'simple_oauth'

    AUTH_HEADER = 'Authorization'.freeze

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

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

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

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

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

    def body_params(env)
      env[:body] || {}
    end

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

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
faraday_middleware-0.8.2 lib/faraday_middleware/request/oauth.rb
faraday_middleware-0.8.1 lib/faraday_middleware/request/oauth.rb
faraday_middleware-0.8.0 lib/faraday_middleware/request/oauth.rb