Sha256: 8c15e5e7ff064934158d6338772d13794bb4597a51d820cb26bdf85719f2a0aa

Contents?: true

Size: 1.82 KB

Versions: 12

Compression:

Stored size: 1.82 KB

Contents

# frozen_string_literal: true

module IronBank
  module Authentications
    # Get a cookie to enable authenticated calls to Zuora through Session.
    #
    class Cookie
      TEN_MINUTES = 600
      ONE_HOUR    = 3600

      def initialize(client_id:, client_secret:, base_url:)
        @client_id     = client_id
        @client_secret = client_secret
        @base_url      = base_url
        fetch_cookie
      end

      def expired?
        # Ten minutes as a margin of error in order to renew token in time
        expires_at < Time.now + TEN_MINUTES
      end

      def header
        { "Cookie" => use }
      end

      private

      attr_reader :client_id, :client_secret, :base_url, :cookie, :zsession,
                  :expires_at

      def use
        refetch_cookie if expired?
        zsession
      end

      def fetch_cookie
        response    = authenticate
        @cookie     = response.headers["set-cookie"]
        @zsession   = fetch_zsession
        @expires_at = Time.now + ONE_HOUR
      end
      alias refetch_cookie fetch_cookie

      def fetch_zsession
        /ZSession=([^;]+)/.match(cookie)[0]
      end

      def authenticate
        connection.post("v1/connections", {})
      end

      def connection
        @connection ||= Faraday.new(**faraday_config) do |conn|
          IronBank.configuration.middlewares.each do |klass, options|
            conn.use klass, options
          end

          conn.request  :url_encoded
          conn.response :json
          conn.adapter  Faraday.default_adapter
        end
      end

      def faraday_config
        {
          url:     base_url,
          headers: authentication_headers
        }
      end

      def authentication_headers
        {
          apiaccesskeyid:     client_id,
          apisecretaccesskey: client_secret
        }
      end
    end
  end
end

Version data entries

12 entries across 12 versions & 1 rubygems

Version Path
iron_bank-5.4.1 lib/iron_bank/authentications/cookie.rb
iron_bank-5.4.0 lib/iron_bank/authentications/cookie.rb
iron_bank-5.3.2 lib/iron_bank/authentications/cookie.rb
iron_bank-5.3.0 lib/iron_bank/authentications/cookie.rb
iron_bank-5.2.6 lib/iron_bank/authentications/cookie.rb
iron_bank-5.2.4 lib/iron_bank/authentications/cookie.rb
iron_bank-5.2.3 lib/iron_bank/authentications/cookie.rb
iron_bank-5.2.0 lib/iron_bank/authentications/cookie.rb
iron_bank-5.1.1 lib/iron_bank/authentications/cookie.rb
iron_bank-5.1.0 lib/iron_bank/authentications/cookie.rb
iron_bank-5.0.1 lib/iron_bank/authentications/cookie.rb
iron_bank-5.0.0 lib/iron_bank/authentications/cookie.rb