Class: Tinplate::RequestAuthenticator

Inherits:
Object
  • Object
show all
Defined in:
lib/tinplate/request_authenticator.rb

Instance Method Summary collapse

Constructor Details

#initialize(action, params = {}, image_name = "") ⇒ RequestAuthenticator

Returns a new instance of RequestAuthenticator.



10
11
12
13
14
15
16
# File 'lib/tinplate/request_authenticator.rb', line 10

def initialize(action, params = {}, image_name = "")
  @action = action
  @params = params
  @image_name = image_name || ""
  @nonce = SecureRandom.hex
  @date  = Time.now.to_i
end

Instance Method Details

#content_typeObject



31
32
33
# File 'lib/tinplate/request_authenticator.rb', line 31

def content_type
  verb == "GET" ? "" : "multipart/form-data; boundary=-----------RubyMultipartPost"
end

#hash_to_sorted_query_string(params) ⇒ Object



54
55
56
57
58
# File 'lib/tinplate/request_authenticator.rb', line 54

def hash_to_sorted_query_string(params)
  Hash[params.sort].map do |key, value|
    "#{key}=#{URI.encode_www_form_component(value)}"
  end.join("&")
end

#paramsObject



18
19
20
21
22
23
24
25
# File 'lib/tinplate/request_authenticator.rb', line 18

def params
  {
    api_key: Tinplate.configuration.public_key,
    api_sig: signature,
    nonce:   @nonce,
    date:    @date
  }
end

#signatureObject



48
49
50
51
52
# File 'lib/tinplate/request_authenticator.rb', line 48

def signature
  OpenSSL::HMAC.hexdigest(OpenSSL::Digest.new("sha256"),
                          Tinplate.configuration.private_key,
                          signature_components.join)
end

#signature_componentsObject



35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/tinplate/request_authenticator.rb', line 35

def signature_components
  [
    Tinplate.configuration.private_key,
    verb,
    content_type,
    URI.encode_www_form_component(@image_name).downcase,
    @date.to_i,
    @nonce,
    "https://api.tineye.com/rest/#{@action}/",
    hash_to_sorted_query_string(@params),
  ]
end

#verbObject



27
28
29
# File 'lib/tinplate/request_authenticator.rb', line 27

def verb
  @image_name.empty? ? "GET" : "POST"
end