Class: Tumblr::Request::TumblrOAuth

Inherits:
Faraday::Middleware
  • Object
show all
Defined in:
lib/tumblr/request/oauth.rb

Instance Method Summary collapse

Constructor Details

#initialize(app, options = {}) ⇒ TumblrOAuth

Returns a new instance of TumblrOAuth.



30
31
32
# File 'lib/tumblr/request/oauth.rb', line 30

def initialize(app, options={})
  @app, @options = app, options
end

Instance Method Details

#call(env) ⇒ Object



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/tumblr/request/oauth.rb', line 10

def call(env)
  if env[:method].to_s == "get"
      params = env[:url].query_values || {}
      url = "#{env[:url].scheme}://#{env[:url].host}#{env[:url].path}"
  else
      params = env[:body] || {}
      url = env[:url]
  end
  signature_params = params
  params.each do |key, value|
    signature_params = {} if value.respond_to?(:content_type)
  end
  env[:request_headers]["Authorization"] = self.oauth_gen(env[:method], url, signature_params) 
  env[:request_headers]["Content-type"] = "application/x-www-form-urlencoded"                                                                              
  env[:request_headers]["Host"] = "api.tumblr.com"
  

  @app.call(env)
end

#oauth_gen(method, url, params) ⇒ Object



34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/tumblr/request/oauth.rb', line 34

def oauth_gen(method, url, params)
   params[:oauth_consumer_key] = @options[:consumer_key]
   params[:oauth_nonce] = Time.now.to_i
   params[:oauth_signature_method] = 'HMAC-SHA1'
   params[:oauth_timestamp] = Time.now.to_i
   params[:oauth_token] = @options[:token]
   params[:oauth_version] = "1.0"
   params[:oauth_signature] = self.oauth_sig(method, url, params)
   
   header = []
   params.each do |key, value|
      if key.to_s.include?("oauth")
        header << "#{key.to_s}=#{value}"
      end
   end

   "OAuth #{header.join(", ")}"

end

#oauth_sig(method, url, params) ⇒ Object



54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
# File 'lib/tumblr/request/oauth.rb', line 54

def oauth_sig(method, url, params)
  parts = [method.upcase, URI.encode(url.to_s, /[^a-z0-9\-\.\_\~]/i)]
  
  #sort the parameters
  params = Hash[params.sort_by{ |key, value| key.to_s}]
  
  encoded = []
  params.each do |key, value|
      encoded << "#{key.to_s}=#{URI.encode(value.to_s, /[^a-z0-9\-\.\_\~]/i)}"
  end

  parts << URI.encode(encoded.join("&"), /[^a-z0-9\-\.\_\~]/i)
  signature_base = parts.join("&")
  secret = "#{@options[:consumer_secret]}&#{@options[:token_secret]}"
  Base64.encode64(OpenSSL::HMAC.digest(OpenSSL::Digest::SHA1.new, secret, signature_base)).chomp.gsub(/\n/, '')
end