require 'json' require 'net/http' require 'threat_agent' module ThreatAgent # The APClient object handles most of the interactions with the ThreatAgent # API # # @author Erran Carey class APIClient # Intializes the ThreatAgent::APIClient object # # @param [String] key the user's API key # @param [String] sup the user's supplemental key # @return [APIClient] the initialized ThreatAgent::APIClient object def initialize(key, sup) @key = key @sup = sup end # Authenticates against threatagent.com # # @param [Hash] credentials credentials to attempt authentication with # @option [String] key the user's API key # @return [Boolean] whether the specified credentials where able to # authenticate with the ThreatAgent API def authenticate(credentials = {}) raise NotImplementedError end # Whether or not authentication was successful # # @return [Boolean] true if the ThreatAgent::APIClient has been # authentication, false otherwise def authenticated? # @authenticated raise NotImplementedError end # Send a request to the ThreatAgent API # # @param [String] action the type of request to send # @param [Hash] params parameters to send along with the action to # api.threatagent.com def request(action, params = {}) action = action.to_s.gsub(/-|_/, '/') params.merge!({ key: @key, sup: @sup }) encoded_params = URI.encode_www_form(params.keys.zip(params.values)) config = ThreatAgent::Config if File.exists?("#{ENV['HOME']}/.threatagent") ThreatAgent::Config.from_file("#{ENV['HOME']}/.threatagent") end api_endpoint = "#{config[:endpoint]}/api/#{config[:api_version]}/" uri = URI("#{api_endpoint}#{action}?#{encoded_params}") resp = Net::HTTP.get_response(uri) json = resp.body JSON.parse(json) end end end