From ab177702bbb4fa80e2c7296c58d461d38a36ef9e Mon Sep 17 00:00:00 2001 From: Konstantin Haase Date: Sat, 28 May 2011 17:51:54 +0200 Subject: [PATCH] import authenticity token implementation --- .../lib/rack/protection/authenticity_token.rb | 7 +++++++ rack-protection/lib/rack/protection/base.rb | 10 ++++++++++ 2 files changed, 17 insertions(+) diff --git a/rack-protection/lib/rack/protection/authenticity_token.rb b/rack-protection/lib/rack/protection/authenticity_token.rb index 8016480f..c4a533d9 100644 --- a/rack-protection/lib/rack/protection/authenticity_token.rb +++ b/rack-protection/lib/rack/protection/authenticity_token.rb @@ -14,6 +14,13 @@ module Rack # # Not Yet Implemented! class AuthenticityToken < Base + def accepts?(env) + return true if safe? env + request = Request.new env + token = session[:csrf] ||= session['_csrf_token'] || random_string + env['HTTP_X_CSRF_TOKEN'] == token or + request.params['authenticity_token'] == token + end end end end diff --git a/rack-protection/lib/rack/protection/base.rb b/rack-protection/lib/rack/protection/base.rb index 0236d877..634502f4 100644 --- a/rack-protection/lib/rack/protection/base.rb +++ b/rack-protection/lib/rack/protection/base.rb @@ -54,6 +54,16 @@ module Rack [options[:status], {'Content-Type' => 'text/plain'}, [options[:message]]] end + def session(env) + env['rack.session'] ||= {} + end + + def random_string(secure = defined? SecureRandom) + secure ? SecureRandom.hex(32) : "%032x" % rand(2**128-1) + rescue NotImpelentedError + random_string false + end + def drop_session(env) env['rack.session'] = {} end