Class: Telesignature::Auth

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

Class Method Summary collapse

Class Method Details

.generate_auth_headers(opts = {}) ⇒ Object



23
24
25
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
# File 'lib/telesignature/auth.rb', line 23

def self.generate_auth_headers(opts = {})
  content_type = opts[:content_type] ? opts[:content_type] : ''
  auth_method = opts[:auth_method] ? opts[:auth_method] : :sha1
  fields = opts[:fields] ? opts[:fields] : nil

  customer_id = opts[:customer_id]
  secret_key = opts[:secret_key]
  resource = opts[:resource]
  method = opts[:method]

  current_date = Time.now.strftime("%a, %d %b %Y %H:%M:%S %z")
  nonce = SecureRandom.uuid

  if %w(POST PUT).include? method
    content_type = "application/x-www-form-urlencoded"
  end

  string_to_sign = "%s\n%s\n\nx-ts-auth-method:%s\nx-ts-date:%s\nx-ts-nonce:%s" % [
          method,
          content_type,
          AUTH_METHOD[auth_method][:name],
          current_date,
          nonce]

  if fields
    string_to_sign += "\n%s" % URI.encode_www_form(fields)
  end

  string_to_sign += "\n%s" % resource

  digest = AUTH_METHOD[auth_method][:hash].new
  signer = OpenSSL::HMAC.digest digest, Base64.decode64(secret_key), string_to_sign

  signature = Base64.encode64 signer

  {
    'Authorization' => "TSA %s:%s" % [customer_id, signature],
    'x-ts-date' => current_date,
    'x-ts-auth-method' => AUTH_METHOD[auth_method][:name],
    'x-ts-nonce' => nonce
  }
end