Created
September 22, 2013 21:47
-
-
Save estromlund/6664202 to your computer and use it in GitHub Desktop.
Rack middleware to block requests from specific API keys before they hit your Rails app
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Rack middleware to block specific requests | |
# Add to your application.rb file: | |
# | |
# config.autoload_paths += %W( #{config.root}/lib/middleware ) | |
# config.middleware.use "AccessBlocker" | |
class AccessBlocker | |
def initialize(app) | |
@app = app | |
end | |
def call(env) | |
request = Rack::Request.new(env) | |
# Check if we should block the request | |
if api_key_blocked?(request.params["api_key"]) | |
# Return 401/unauthorized status code | |
[401, {'Content-Type' => 'text/plain'}, self] #Three parameters needed: status, headers, body | |
else | |
# Execute the request as if nothing happened | |
@app.call(env) | |
end | |
end | |
# Unused, but needed | |
def each(&block) | |
end | |
private | |
def api_key_blocked?(key) | |
# Add any API Keys that we want to block | |
keys_to_block = ["XXXXXX", | |
"YYYYYY", | |
"ZZZZZZ"] | |
return true if keys_to_block.include?(key) # Return true if the array contains the API Key that we're checking | |
return false # Otherwise return false | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment