Class: SimpleClient::Signature

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

Constant Summary collapse

ATTR =
[
  :api_key,
  :api_secret,
  :digest
]

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(params) ⇒ Signature

Returns a new instance of Signature.



18
19
20
21
22
23
# File 'lib/simple/signature.rb', line 18

def initialize(params)
  ATTR.each { |attr| instance_variable_set("@#{attr}", params[attr]) if params[attr] }
  @digest = "sha256" if !@digest
  @client_request_id = SecureRandom.uuid
  @timestamp = DateTime.now.strftime("%Q")
end

Instance Attribute Details

#client_request_idObject (readonly)

Returns the value of attribute client_request_id.



16
17
18
# File 'lib/simple/signature.rb', line 16

def client_request_id
  @client_request_id
end

#timestampObject (readonly)

Returns the value of attribute timestamp.



16
17
18
# File 'lib/simple/signature.rb', line 16

def timestamp
  @timestamp
end

Instance Method Details

#jsonify(model) ⇒ Object



32
33
34
35
36
37
38
39
40
41
# File 'lib/simple/signature.rb', line 32

def jsonify(model)
  return model if model.nil? || model.is_a?(String)
  local_body = nil
  if model.is_a?(Array)
    local_body = model.map{|m| object_to_hash(m) }
  else
    local_body = object_to_hash(model)
  end
  local_body.to_json
end

#object_to_hash(obj) ⇒ Object



43
44
45
46
47
48
49
# File 'lib/simple/signature.rb', line 43

def object_to_hash(obj)
  if obj.respond_to?(:to_hash)
    obj.to_hash
  else
    obj
  end
end

#sign(payload = nil) ⇒ Object



25
26
27
28
29
30
# File 'lib/simple/signature.rb', line 25

def sign(payload=nil)
  data = @api_key + @client_request_id + @timestamp
  data += jsonify(payload) if payload
  hmac = OpenSSL::HMAC.hexdigest(@digest, @api_secret, data)
  Base64.urlsafe_encode64(hmac)
end