class EngagingNetworks::Request::MultiTokenAuthentication

Constants

PRIVATE
PUBLIC

Public Class Methods

new(app, *args) click to toggle source
# File lib/engaging_networks/request/multitoken.rb, line 55
def initialize(app, *args)
  @app = app

  options = args.extract_options!
  if options.has_key? :public_token
    @public_token = options[:public_token]
  else
    @public_token = nil
  end

  if options.has_key? :private_token
    @private_token = options[:private_token]
  else
    @private_token = nil
  end

end

Public Instance Methods

call(env) click to toggle source

Request middleware looks for token_type in http params, replaces with actual token value

# File lib/engaging_networks/request/multitoken.rb, line 9
def call(env)
  # decode url param string to hash
  if env[:url].query
    params = Hash[URI.decode_www_form(env[:url].query)]
  elsif env[:body]
    params = env[:body]
  else
    params = {}
  end

  if env[:method] == :get && params.has_key?("token_type")
    token_type = params['token_type'].to_i #because it got stringified in the form

    # insert necessary token
    if token_type == MultiTokenAuthentication::PRIVATE
      params["token"] = @private_token
    elsif token_type == MultiTokenAuthentication::PUBLIC
      params["token"] = @public_token
    else
      raise ArgumentError, "invalid token_type #{token_type}"
    end

    # remove token_type
    params.delete('token_type')

    # encode and return to env
    env[:url].query = URI.encode_www_form(params)
  elsif env[:method] == :post && params.has_key?(:token_type)
    token_type = params[:token_type].to_i

    if token_type == MultiTokenAuthentication::PRIVATE
      params[:token] = @private_token
    elsif token_type == MultiTokenAuthentication::PUBLIC
      params[:token] = @public_token
    else
      raise ArgumentError, "invalid token_type #{token_type}"
    end

    params.delete(:token_type)

    env[:body] = params
  end

  @app.call env
end