Created
January 31, 2012 01:09
-
-
Save ender672/1707974 to your computer and use it in GitHub Desktop.
Rack middleware for signed request URIs
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 './signed_request_uri' | |
require 'rack/file' | |
use Rack::SignedRequestUri, 'top secret' | |
run Rack::File.new('images') |
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 '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