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}!").to_s) 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