Class: BatchlyApi::CustomAuthUtility

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

Constant Summary collapse

HEADER_AUTHORIZATION =
"Authorization"
HMAC_TEMPLATE =
"Hmac %s"
HEADER_NONCE =
"Nonce"
HEADER_TIMESTAMP =
"Timestamp"
HEADER_API_KEY =
"Api-Key"

Class Method Summary collapse

Class Method Details

.append_custom_auth_params(url, method, headers) ⇒ Object

Appends the necessary OAuth credentials for making this authorized call

Parameters:

  • The (Hash)

    out going request to access the resource



26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# File 'lib/batchly_api/custom_auth_utility.rb', line 26

def self.append_custom_auth_params(url, method, headers)
  parsed_url = URI.parse(url)
  apiKey = Configuration.API_KEY.dup
  apiSecret = Configuration.API_SECRET.dup

  req_url = parsed_url.to_s

  if parsed_url.port == 80 || parsed_url.port == 443
    req_url = parsed_url.scheme + '://' + parsed_url.host + parsed_url.path
  else
    req_url = parsed_url.scheme + '://' + parsed_url.host + ":" + parsed_url.port.to_s + parsed_url.path
  end

  hmacHeaders = {
    HEADER_NONCE => Array.new( 5 ) { rand(256) }.pack('C*').unpack('H*').first,
    HEADER_TIMESTAMP => Time.now.to_i,
    HEADER_API_KEY =>apiKey
  }

  params = hmacHeaders
  method = method.upcase

  if parsed_url.query
    params.merge! CGI.parse( parsed_url.query )
  end

  base_str = [
    method.upcase,
    percent_encode( req_url ),
    percent_encode(query_string(params))
  ].join( "&" )

  key =  percent_encode( apiSecret )

  digest = OpenSSL::Digest::Digest.new( 'sha1' )
  hmac = OpenSSL::HMAC.digest( digest, key, base_str )

  headers["Authorization"] = HMAC_TEMPLATE % [ percent_encode( Base64.encode64( hmac ).chomp.gsub( /\n/, '' ) ) ]
  headers[HEADER_NONCE] = hmacHeaders[HEADER_NONCE]
  headers[HEADER_TIMESTAMP] = hmacHeaders[HEADER_TIMESTAMP]
  headers[HEADER_API_KEY] = hmacHeaders[HEADER_API_KEY]
end

.percent_encode(string) ⇒ Object



12
13
14
# File 'lib/batchly_api/custom_auth_utility.rb', line 12

def self.percent_encode( string )
  URI.escape( string, Regexp.new("[^#{URI::PATTERN::UNRESERVED}]") ).gsub('*', '%2A')
end

.query_string(params) ⇒ Object



16
17
18
19
20
21
22
# File 'lib/batchly_api/custom_auth_utility.rb', line 16

def self.query_string(params)
  pairs = []
  params.sort.each { | key, val |
    pairs.push( "#{ percent_encode( key ) }=#{ percent_encode( val.to_s ) }" )
  }
  pairs.join '&'
end