Sha256: c8326ed7c263076331e18194facba3b405fa784df5f401c136ff67d31340de93

Contents?: true

Size: 1.54 KB

Versions: 1

Compression:

Stored size: 1.54 KB

Contents

# frozen_string_literal: true

require 'base64'
require 'openssl'

module DvelpApiAuth
  module Authentication
    class Signature
      include ::DvelpApiAuth::HelperMethods

      attr_accessor :raw_post, :request_timestamp, :body, :multipart

      def initialize(
        fullpath,
        raw_post,
        request_timestamp,
        multipart = false,
        body = nil,
        api_secret_key = DvelpApiAuth.configuration.api_auth_secret_key
      )
        @fullpath = fullpath
        @raw_post = raw_post
        @request_timestamp = request_timestamp
        @multipart = multipart
        @body = body
        @api_secret_key = api_secret_key

        raise 'Request full_path is required' unless present?(@fullpath)
        raise 'Timestamp is required' unless present?(@request_timestamp)
      end

      def generate
        string = multipart? ? multipart_key : timesensitive_string_to_sign

        OpenSSL::HMAC.hexdigest(
          OpenSSL::Digest.new('SHA256'),
          @api_secret_key,
          string
        )
      end

      def fullpath
        @fullpath.split('?')[0]
      end

      private

      def timesensitive_string_to_sign
        request_timestamp.to_s + string_to_sign
      end

      def multipart_key
        request_timestamp.to_s +
          Base64.strict_encode64(fullpath).chomp +
          body.length.to_s
      end

      def string_to_sign
        string = blank?(raw_post) ? fullpath : raw_post
        Base64.strict_encode64(string).chomp
      end

      def multipart?
        @multipart
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
dvelp_api_auth-0.5.0 lib/dvelp_api_auth/authentication/signature.rb