Class: Rack::Csrf

Inherits:
Object
  • Object
show all
Defined in:
lib/rack/csrf.rb

Defined Under Namespace

Classes: InvalidCsrfToken, SessionUnavailable

Constant Summary collapse

@@field =
'_csrf'
@@key =
'csrf.token'

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(app, opts = {}) ⇒ Csrf

Returns a new instance of Csrf.



16
17
18
19
20
21
22
23
24
25
# File 'lib/rack/csrf.rb', line 16

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]
  @@key = opts[:key] if opts[:key]

  @http_verbs = %w(POST PUT DELETE)
end

Class Method Details

.csrf_fieldObject



48
49
50
# File 'lib/rack/csrf.rb', line 48

def self.csrf_field
  @@field
end

.csrf_keyObject



44
45
46
# File 'lib/rack/csrf.rb', line 44

def self.csrf_key
  @@key
end

.csrf_tag(env) ⇒ Object



56
57
58
# File 'lib/rack/csrf.rb', line 56

def self.csrf_tag(env)
  %Q(<input type="hidden" name="#{csrf_field}" value="#{csrf_token(env)}" />)
end

.csrf_token(env) ⇒ Object



52
53
54
# File 'lib/rack/csrf.rb', line 52

def self.csrf_token(env)
  env['rack.session'][csrf_key] ||= SecureRandom.base64(32)
end

Instance Method Details

#call(env) ⇒ Object



27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/rack/csrf.rb', line 27

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'][self.class.csrf_key] ||
    skip_checking(req)
  if untouchable
    @app.call(env)
  else
    raise InvalidCsrfToken if @raisable
    [403, {'Content-Type' => 'text/html', 'Content-Length' => '0'}, []]
  end
end