Skip to content
Browse files

use Redis to restrict POSTs to valid API keys

  • Loading branch information...
1 parent 7ccc97f commit 03b2d2b2a03987f7352965f91ffd3fbbadd380ea @stevenwilkin committed Feb 9, 2012
Showing with 50 additions and 3 deletions.
  1. +8 −1 coffee_tracker.rb
  2. +41 −0 test/api/api_key_test.rb
  3. +1 −2 test/test_helpers.rb
View
9 coffee_tracker.rb
@@ -5,7 +5,14 @@
class CoffeeTracker < Sinatra::Base
- post '/' do
+ post '/api' do
+ api_key = env['HTTP_X_API_KEY']
+ unless api_key
+ halt 401, {'Content-Type' => 'text/plain'}, 'Missing API Key'
+ end
+ unless $redis.sismember 'api_keys', api_key
+ halt 403, {'Content-Type' => 'text/plain'}, 'Invalid API Key'
+ end
end
end
View
41 test/api/api_key_test.rb
@@ -0,0 +1,41 @@
+require_relative '../test_helpers'
+
+class ApiKeyTest < Test::Unit::TestCase
+ include TestHelpers
+
+ def setup
+ @valid_api_key = 'valid'
+ @invalid_api_key = 'invalid'
+
+ $redis.flushdb
+ $redis.sadd 'api_keys', @valid_api_key
+ end
+
+ def test_no_api_key
+ post '/api'
+ assert_equal 401, last_response.status, 'Should reject POST when no API key'
+ end
+
+ def test_no_api_key_response
+ post '/api'
+ assert_equal 'Missing API Key', last_response.body, 'Should give rejection message'
+ end
+
+ def test_invalid_api_key
+ header('X-Api-Key', @invalid_api_key)
+ post '/api'
+ assert_equal 403, last_response.status, 'Should reject POST when invalid API key'
+ end
+
+ def test_invalid_api_key_response
+ header('X-Api-Key', @invalid_api_key)
+ post '/api'
+ assert_equal 'Invalid API Key', last_response.body, 'Should give rejection message'
+ end
+
+ def test_valid_api_key
+ header('X-Api-Key', @valid_api_key)
+ post '/api'
+ assert_equal 200, last_response.status, 'Should accept POST when valid API key'
+ end
+end
View
3 test/test_helpers.rb
@@ -1,10 +1,9 @@
ENV['RACK_ENV'] ||= 'test'
-require 'simplecov'
require 'test/unit'
require 'rack/test'
-require_relative '../courier'
+require_relative '../coffee_tracker'
module TestHelpers
include Rack::Test::Methods

0 comments on commit 03b2d2b

Please sign in to comment.
Something went wrong with that request. Please try again.