Sha256: 4cdb7186b5e236fa0189f0c04df66ffbf9aaadd07815654d73d436b6d80f9d1a

Contents?: true

Size: 1.95 KB

Versions: 6

Compression:

Stored size: 1.95 KB

Contents

module Fizzy
  module Api
    module Sessions
      class BasicAuthSession
        attr_reader :fizzy_url
        attr_reader :username
        attr_reader :password

        def initialize(fizzy_url: ENV['FIZZY_URL'],
                       username: ENV['FIZZY_BASICAUTH_ID'],
                       password: ENV['FIZZY_BASICAUTH_SECRET'])
          @fizzy_url = fizzy_url
          @username = username
          @password = password
        end

        def get(path, params = {})
          perform_request_or_fail do
            HTTParty.get(full_url_for(path),
                         query: params,
                         basic_auth: basic_auth)
          end
        end

        def post(path, params = {})
          perform_request_or_fail do
            HTTParty.post(full_url_for(path),
                          headers: { 'Content-Type' => 'application/json' },
                          body: params.to_json,
                          basic_auth: basic_auth)
          end
        end

        def delete(path, params = {})
          perform_request_or_fail do
            HTTParty.delete(full_url_for(path),
                            query: params,
                            basic_auth: basic_auth)
          end
        end

        private

        def perform_request_or_fail(&_block)
          response = yield
          case response.code
          when 401
            access_denied(response)
          when 500
            raise response.parsed_response || "Received HTTP response code #{response.code}!"
          else
            response
          end
        end

        def access_denied(response)
          raise NoSession if response.headers['WWW-Authenticate']
          raise Unauthorized
        end

        def full_url_for(path)
          fizzy_url + api_base + path
        end

        def api_base
          '/api/v1'
        end

        def basic_auth
          { username: username, password: password }
        end
      end
    end
  end
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
fizzy-api-0.1.2 lib/fizzy/api/sessions/basic_auth_session.rb
fizzy-api-0.1.1 lib/fizzy/api/sessions/basic_auth_session.rb
fizzy-api-0.1.0 lib/fizzy/api/sessions/basic_auth_session.rb
fizzy-api-0.0.6 lib/fizzy/api/sessions/basic_auth_session.rb
fizzy-api-0.0.5 lib/fizzy/api/sessions/basic_auth_session.rb
fizzy-api-0.0.4 lib/fizzy/api/sessions/basic_auth_session.rb