Sha256: 0b1fc2183abb72cee2fa99e2d07eae0e0c2f5a593fde4c7ac209902890b230af

Contents?: true

Size: 1.48 KB

Versions: 1

Compression:

Stored size: 1.48 KB

Contents

# frozen_string_literal: true
require 'base64'

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
      )
        @fullpath = fullpath
        @raw_post = raw_post
        @request_timestamp = request_timestamp
        @multipart = multipart
        @body = body

        unless present?(@request_timestamp)
          raise 'Request full_path is required'
        end
        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'),
          app_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 app_secret_key
        ENV['DVELP_API_AUTH_SECRET_KEY']
      end

      def multipart?
        @multipart
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

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