Created
February 12, 2010 18:14
-
-
Save mattetti/302811 to your computer and use it in GitHub Desktop.
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
require 'rubygems' | |
require 'rack' | |
class Rack | |
class PlayCo | |
class RequestValidator | |
# ==== Parameters | |
# app<Rack::Builder>:: The Rack builder which will use this middleware. | |
# path_opts<Hash>:: Path options used to identify path to validate. | |
# | |
# ==== Options (path_opts) | |
# :http_methods<Array, String>:: | |
# 'POST', 'GET', 'DELETE' or 'UPDATE' HTTP verb used against | |
# env['REQUEST_METHOD']. | |
# :path<Regexp, string>:: Regular expression or stirng filtering requests | |
# to validate based on the request path. Used against env["REQUEST_PATH"] | |
# | |
# ==== Examples | |
# | |
# (Rails 2.x) in RAILS_ROOT/config.ru: | |
# use Rack::PlayCo::RequestValidator :http_method => ['POST', 'GET'], | |
# :path => /API\/v\d+\// | |
def initialize(app, path_opts) | |
@app = app | |
# TODO validate the path_opts and/or set defaults | |
@path_opts = path_opts | |
end | |
def call(env) | |
if validated_request_method?(env) && validated_path?(env) | |
post_body = env['rack.input'] ? env['rack.input'].read : nil | |
if valid_post_body?(post_body) | |
@app.call(env) | |
else | |
[400, {"Content-Type" => "text/html"}, [post_body]] | |
end | |
end | |
end | |
def validated_request_method?(env) | |
@path_ops[:http_methods].include?(env['REQUEST_METHOD']) | |
end | |
def validated_path?(env) | |
if @path_ops[:path].is_a? Regexp | |
!(env["REQUEST_PATH"] =~ @path_ops[:path].is_a?).nil? | |
else | |
env["REQUEST_PATH"] == @path_ops[:path] | |
end | |
end | |
def valid_post_body?(body) | |
false | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment