Class: EnstratusHelper

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

Constant Summary collapse

CONFIGURABLE_ATTRIBUTES =
[
  :details,
  :accept,
  :secret_key,
  :access_key
]

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ EnstratusHelper

Returns a new instance of EnstratusHelper.



17
18
19
20
21
22
23
# File 'lib/enstratus_helper.rb', line 17

def initialize(options = {})
  CONFIGURABLE_ATTRIBUTES.each do |attribute_name|
    self.send("#{attribute_name}=", options[attribute_name]) if options.has_key?(attribute_name)
  end
  @accept ||= 'application/xml'
  @details ||= 'extended'
end

Class Method Details

.sign(key, str_to_sign) ⇒ Object

Generates the signature for talking to enStratus



67
68
69
70
# File 'lib/enstratus_helper.rb', line 67

def self.sign(key, str_to_sign)
  digest = OpenSSL::Digest::Digest.new('sha256')
  Base64.encode64(OpenSSL::HMAC.digest(digest, key, str_to_sign)).gsub("\n","")
end

Instance Method Details

#generate_header(uri, http_method, options = {}) ⇒ Object

Generates the required headers for talking to enStratus API signature is of the following format:

BASE64(SHA256(ACCESS_KEY:METHOD:URI:TIMESTAMP:USER_AGENT))


28
29
30
31
32
33
34
35
36
37
# File 'lib/enstratus_helper.rb', line 28

def generate_header(uri, http_method, options={})
  http_method = http_method.to_s.upcase
  path = URI.parse(uri).path
  timestamp = Time.now.to_i * 1000
  signature = "#{@access_key}:#{http_method}:#{path}:#{timestamp}:#{self.class}"
  signature = EnstratusHelper::sign(@secret_key, signature)
  {'x-esauth-access' => @access_key, 'x-esauth-signature' => signature, 
   'x-esauth-timestamp' => timestamp, 'User-agent' => self.class, 
   'x-es-details' => details, 'Accept' => accept}
end

#request(method, uri, options = {}) ⇒ Object

Sends the request to the given URI using the specified method (GET by default) Returns the response object (of the rest-client library)



41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/enstratus_helper.rb', line 41

def request(method, uri, options={})
  response = nil
  data = options[:data]
  header = generate_header(uri, method)
  header = header.merge(options[:header]) if options[:header]
  begin
    case method
    when :get
      response = RestClient.send(method, uri, header)
    when :delete
      response = RestClient.send(method, uri, header)
    when :post
      header[:content_type] = 'application/xml'
      response = RestClient.send(method, uri, data, header)
    when :put
      response = RestClient.send(method, uri, data, header)
    else
      raise "HTTP method #{method} not supported"  
    end
  rescue => e
    puts e.inspect
  end
  response
end