Class: Rack::Csrf
- Inherits:
-
Object
show all
- Defined in:
- lib/rack/csrf.rb
Defined Under Namespace
Classes: InvalidCsrfToken, SessionUnavailable
Constant Summary
collapse
- @@field =
'_csrf'
Class Method Summary
collapse
Instance Method Summary
collapse
Constructor Details
#initialize(app, opts = {}) ⇒ Csrf
Returns a new instance of Csrf.
15
16
17
18
19
20
21
22
23
|
# File 'lib/rack/csrf.rb', line 15
def initialize(app, opts = {})
@app = app
@raisable = opts[:raise] || false
@skippable = (opts[:skip] || []).map {|r| /\A#{r}\Z/i}
@@field = opts[:field] if opts[:field]
@http_verbs = %w(POST PUT DELETE)
end
|
Class Method Details
.csrf_field ⇒ Object
42
43
44
|
# File 'lib/rack/csrf.rb', line 42
def self.csrf_field
@@field
end
|
.csrf_tag(env) ⇒ Object
50
51
52
|
# File 'lib/rack/csrf.rb', line 50
def self.csrf_tag(env)
%Q(<input type="hidden" name="#{csrf_field}" value="#{csrf_token(env)}" />)
end
|
.csrf_token(env) ⇒ Object
46
47
48
|
# File 'lib/rack/csrf.rb', line 46
def self.csrf_token(env)
env['rack.session']['csrf.token'] ||= SecureRandom.base64(32)
end
|
Instance Method Details
#call(env) ⇒ Object
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
|
# File 'lib/rack/csrf.rb', line 25
def call(env)
unless env['rack.session']
raise SessionUnavailable.new('Rack::Csrf depends on session middleware')
end
self.class.csrf_token(env)
req = Rack::Request.new(env)
untouchable = !@http_verbs.include?(req.request_method) ||
req.POST[self.class.csrf_field] == env['rack.session']['csrf.token'] ||
skip_checking(req)
if untouchable
@app.call(env)
else
raise InvalidCsrfToken if @raisable
[403, {'Content-Type' => 'text/html', 'Content-Length' => '0'}, []]
end
end
|