Sha256: ae6806cf05820fcc2eaa31a06202811478d76170c71a99326c729f5ffc16fea1

Contents?: true

Size: 1.64 KB

Versions: 2

Compression:

Stored size: 1.64 KB

Contents

# frozen_string_literal: true
module DvelpApiAuth
  module Authentication
    class Validator
      include ::DvelpApiAuth::HelperMethods

      attr_reader :client_authorization_code, :server_signature

      def initialize(
        client_authorization_code,
        request_timestamp,
        server_signature
      )
        @client_authorization_code = client_authorization_code
        @request_timestamp = request_timestamp
        @server_signature = server_signature

        unless present?(@client_authorization_code)
          raise 'Client authorization code is required'
        end
        unless present?(@server_signature)
          raise 'Server signature is required'
        end
        unless present?(@request_timestamp)
          raise 'Timestamp is required'
        end
      end

      def authentic?
        valid_signature? && valid_timestamp?
      end

      private

      def valid_timestamp?
        request_timestamp.between?(time_validity_start, time_validity_end)
      end

      def valid_signature?
        client_signature_digest == server_signature_digest
      end

      def client_signature_digest
        Digest::SHA1.hexdigest(client_authorization_code)
      end

      def server_signature_digest
        Digest::SHA1.hexdigest(server_signature)
      end

      def time_validity_start
        @time_validity_start ||= (time_benchmark - 15 * 60).to_i
      end

      def time_validity_end
        @time_validity_end ||= (time_benchmark + 5 * 60).to_i
      end

      def time_benchmark
        @time_benchmark ||= Time.now.utc
      end

      def request_timestamp
        @request_timestamp.to_i
      end
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
dvelp_api_auth-0.5.0 lib/dvelp_api_auth/authentication/validator.rb
dvelp_api_auth-0.1.0 lib/dvelp_api_auth/authentication/validator.rb