Sha256: d940183b2db9f5edd25d4bd7e91f16a0856b716d18d7b56fea170839d44d9888

Contents?: true

Size: 1.59 KB

Versions: 2

Compression:

Stored size: 1.59 KB

Contents

require 'base64'
require 'curb'
require 'json'
require 'openssl'

module Lenddo
  module Authentication
    def signed_request(args)
      host = args[:host]
      method = args[:method].downcase
      path = args[:path]
      params = args[:params]

      if (method == 'post' || method == 'put')
        body = params
      else
        body = {}
      end

      uri = URI.parse(host + path)
      Curl.send(method.to_s, uri.to_s, params) do |http|
        headers = sign(method.upcase, path, body)
        headers.each do |key, value|
          http.headers[key] = value.chomp
        end

        http.use_ssl = 3
        http.ssl_verify_host = OpenSSL::SSL::VERIFY_PEER
        http.cacert = File.absolute_path("./cacert.pem") if RbConfig::CONFIG['host_os'] == 'mingw32'
      end
    end

    private
    def sign(verb, path, body, ts = nil)
      date_format = "%a %b %d %H:%M:%S %Z %Y"
      digest = body.empty? ? "" : Digest::MD5.hexdigest(URI.encode_www_form(body))
      timestamp = ts.nil? ? Time.now : Time.parse(ts, date_format)
      date = timestamp.strftime(date_format)
      text = [verb, digest, date, path].join("\n")
      {
          'Authorization' => auth_string(text),
          'Content-Type' => 'application/json',
          'Date' => date
      }
    end

    def auth_string(text)
      hash = Base64.encode64(sha1_hmac(Lenddo.configuration.secret_key, text))
      "LENDDO #{Lenddo.configuration.access_key}:#{hash}"
    end

    def sha1_hmac(key, value)
      OpenSSL::HMAC.digest(OpenSSL::Digest.new('sha1'), key, value)
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
lenddo-1.1.1 lib/lenddo/authentication.rb
lenddo-1.1.0 lib/lenddo/authentication.rb