Skip to content

Instantly share code, notes, and snippets.

@estromlund
Created September 22, 2013 21:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save estromlund/6664202 to your computer and use it in GitHub Desktop.
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
# 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