Skip to content

Instantly share code, notes, and snippets.

@ender672
Created January 31, 2012 01:09
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 ender672/1707974 to your computer and use it in GitHub Desktop.
Save ender672/1707974 to your computer and use it in GitHub Desktop.
Rack middleware for signed request URIs
require './signed_request_uri'
require 'rack/file'
use Rack::SignedRequestUri, 'top secret'
run Rack::File.new('images')
require 'openssl'
require 'rack/utils'
module Rack
class SignedRequestUri
def initialize(app, secret, options = nil)
@app = app
@secret = secret
options ||= {}
@key = options['key'] || '_secret'
end
def call(env)
qs = Utils.parse_query(env["QUERY_STRING"])
signature = qs.delete(@key)
qs = qs.sort
unsigned_request = "#{env["REQUEST_PATH"]}?#{Utils.build_query(qs)}"
if signature == self.class.generate_hmac(@secret, unsigned_request)
@app.call(env)
else
[403, {"Content-Type" => "text/plain"}, ["Request signature did not match."]]
end
end
def self.generate_hmac(data, secret)
OpenSSL::HMAC.hexdigest(OpenSSL::Digest::SHA1.new, secret, data)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment