Sha256: b4c697fb6a9805c6d2e0ec7762e012cc7d905fc074cd291709bbd7de75b9d8db

Contents?: true

Size: 1.16 KB

Versions: 13

Compression:

Stored size: 1.16 KB

Contents

module ResoTransport
  module Authentication
    # Authentication middleware
    # Ensures that each request is made with proper `Authorization` header set
    # and raises an exception if a request yields a `401 Access Denied` response.
    class Middleware < Faraday::Middleware
      AUTH_HEADER = 'Authorization'.freeze

      def initialize(app, auth)
        super(app)
        @auth = auth
      end

      def call(request_env)
        retries = 1

        begin
          authorize_request(request_env)

          @app.call(request_env).on_complete do |response_env|
            raise_if_unauthorized(response_env)
          end
        rescue ResoTransport::AccessDenied
          raise if retries == 0
          @auth.reset
          retries -= 1
          retry
        end
      end

      private

      def authorize_request(request_env)
        @auth.ensure_valid_access!

        request_env[:request_headers].merge!(
          AUTH_HEADER => "#{@auth.access.token_type} #{@auth.access.access_token}"
        )
      end

      def raise_if_unauthorized(response_env)
        raise ResoTransport::AccessDenied if response_env[:status] == 401
      end
    end
  end
end

Version data entries

13 entries across 13 versions & 1 rubygems

Version Path
reso_transport-1.5.7 lib/reso_transport/authentication/middleware.rb
reso_transport-1.5.5 lib/reso_transport/authentication/middleware.rb
reso_transport-1.5.4 lib/reso_transport/authentication/middleware.rb
reso_transport-1.5.3 lib/reso_transport/authentication/middleware.rb
reso_transport-1.5.2 lib/reso_transport/authentication/middleware.rb
reso_transport-1.5.1 lib/reso_transport/authentication/middleware.rb
reso_transport-1.4.0 lib/reso_transport/authentication/middleware.rb
reso_transport-1.3.2 lib/reso_transport/authentication/middleware.rb
reso_transport-1.3.1 lib/reso_transport/authentication/middleware.rb
reso_transport-1.3.0 lib/reso_transport/authentication/middleware.rb
reso_transport-1.2.0 lib/reso_transport/authentication/middleware.rb
reso_transport-1.1.0 lib/reso_transport/authentication/middleware.rb
reso_transport-1.0.0 lib/reso_transport/authentication/middleware.rb