Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

csrf protection

  • Loading branch information...
commit 8c69454d6bf028ba5d473361dcc5209e18670f85 1 parent a2ab2fd
NS authored
Showing with 23 additions and 1 deletion.
  1. +5 −1 config/boot.rb
  2. +18 −0 config/csrf_protection.rb
View
6 config/boot.rb
@@ -7,7 +7,7 @@
Bundler.require(:default, ENV["RACK_ENV"].to_sym)
# init database
-require_relative "database.rb"
+require_relative "database"
# init sinatra
set :sessions, true
@@ -21,6 +21,10 @@
also_reload "lib/**/*.rb", "app/{models,helpers}/**/*.rb"
end
+# csrf
+require_relative "csrf_protection"
+use Rack::CsrfProtection unless test?
+
# assets
require "sprockets/sass/functions" if development?
require settings.root + "/config/assets.rb"
View
18 config/csrf_protection.rb
@@ -0,0 +1,18 @@
+module Rack
+ CsrfProtection = Struct.new(:app)
+
+ class CsrfProtection
+ SAFE_VERBS = %w[GET HEAD OPTIONS TRACE]
+
+ def call env
+ unless SAFE_VERBS.include?(env['REQUEST_METHOD'])
+ if env['rack.session'][:csrf] != Request.new(env).params['authenticity_token']
+ env['rack.session'] = {}
+ end
+ end
+ env['rack.session'][:csrf] ||= ("%032x" % rand(2**128-1))
+
+ app.call env
+ end
+ end
+end
Please sign in to comment.
Something went wrong with that request. Please try again.