From b05df568c732236b1ab68164c2a51c93cf0d8fb5 Mon Sep 17 00:00:00 2001
From: Robert Schaefer <robert.schaefer@student.hpi.de>
Date: Fri, 12 Jan 2018 00:26:57 +0100
Subject: [PATCH] Add api-key to http request headers if given

---
 lib/geocoder/lookups/ipdata_co.rb   |  1 +
 test/unit/lookups/ipdata_co_test.rb | 19 +++++++++++++++++++
 2 files changed, 20 insertions(+)

diff --git a/lib/geocoder/lookups/ipdata_co.rb b/lib/geocoder/lookups/ipdata_co.rb
index 04e38fa4..a8e0bf00 100644
--- a/lib/geocoder/lookups/ipdata_co.rb
+++ b/lib/geocoder/lookups/ipdata_co.rb
@@ -19,6 +19,7 @@ module Geocoder::Lookup
     private # ---------------------------------------------------------------
 
     def results(query)
+      Geocoder.configure(:http_headers => { "api-key" => configuration.api_key }) if configuration.api_key
       # don't look up a loopback address, just return the stored result
       return [reserved_result(query.text)] if query.loopback_ip_address?
       # note: Ipdata.co returns plain text on bad request
diff --git a/test/unit/lookups/ipdata_co_test.rb b/test/unit/lookups/ipdata_co_test.rb
index 5acdcf72..88a4d16c 100644
--- a/test/unit/lookups/ipdata_co_test.rb
+++ b/test/unit/lookups/ipdata_co_test.rb
@@ -32,4 +32,23 @@ class IpdataCoTest < GeocoderTestCase
         lookup.send(:check_response_for_errors!, response)
     end
   end
+
+  def test_api_key
+    Geocoder.configure(:api_key => 'XXXX')
+
+    # HACK: run the code once to add the api key to the HTTP request headers
+    Geocoder.search('8.8.8.8')
+    # It's really hard to 'un-monkey-patch' the base lookup class here
+
+    require 'webmock/test_unit'
+    WebMock.enable!
+    stubbed_request = WebMock.stub_request(:get, "https://api.ipdata.co/8.8.8.8").with(headers: {'api-key' => 'XXXX'}).to_return(status: 200)
+
+    g = Geocoder::Lookup::IpdataCo.new
+    g.send(:actual_make_api_request, Geocoder::Query.new('8.8.8.8'))
+    assert_requested(stubbed_request)
+
+    WebMock.reset!
+    WebMock.disable!
+  end
 end
-- 
GitLab