Class: Panda::ApiAuthentication

Inherits:
Object
  • Object
show all
Defined in:
lib/panda/api_authentication.rb

Class Method Summary collapse

Class Method Details

._recursion(h, base = nil) ⇒ Object



44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/panda/api_authentication.rb', line 44

def self._recursion(h, base = nil)
  pairs = []
  h.keys.sort.each do |key|
    value = h[key]
    if value.kind_of? Hash
      pairs += _recursion(value, key)
    else
      new_pair = nil
      if base
        new_pair = "#{base}[#{url_encode(key)}]=#{url_encode(value)}"
      else
        new_pair = "#{url_encode(key)}=#{url_encode(value)}"
      end
      pairs << new_pair
    end
  end
  pairs
end

.canonical_querystring(h) ⇒ Object

param keys should be strings, not symbols please. return a string joined by & in canonical order.



29
30
31
# File 'lib/panda/api_authentication.rb', line 29

def self.canonical_querystring(h)
  _recursion(h).join('&')
end

.generate_signature(verb, request_uri, host, secret_key, params_given = {}) ⇒ Object



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# File 'lib/panda/api_authentication.rb', line 10

def self.generate_signature(verb, request_uri, host, secret_key, params_given={})
  # Ensure all param keys are strings
  params = {}; params_given.each {|k,v| params[k.to_s] = v }

  query_string = canonical_querystring(params)

  string_to_sign = verb.to_s.upcase + "\n" + 
      host.downcase + "\n" +
      request_uri + "\n" +
      query_string

  hmac = HMAC::SHA256.new( secret_key )
  hmac.update( string_to_sign )
  # chomp is important!  the base64 encoded version will have a newline at the end
  Base64.encode64(hmac.digest).chomp
end

.hash_to_query(hash) ⇒ Object

Turns a hash into a query string, returns the query string. url-encodes everything to Amazon’s specifications.



34
35
36
# File 'lib/panda/api_authentication.rb', line 34

def self.hash_to_query(hash)
  hash.collect{|key, value| url_encode(key) + "=" + url_encode(value) }.join("&")
end

.url_encode(string) ⇒ Object

It’s kinda like CGI.escape, except CGI.escape is encoding a tilde when it ought not to be, so we turn it back. Also space NEEDS to be %20 not +.



40
41
42
# File 'lib/panda/api_authentication.rb', line 40

def self.url_encode(string)
  CGI.escape(string.to_s).gsub("%7E", "~").gsub("+", "%20")
end