Class: Rack::Csrf

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

Defined Under Namespace

Classes: InvalidCsrfToken, SessionUnavailable

Constant Summary collapse

VERSION =
'2.6.0'
@@field =
'_csrf'
@@header =
'X_CSRF_TOKEN'
@@key =
'csrf.token'

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

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

Returns a new instance of Csrf.



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

def initialize(app, opts = {})
  @app = app

  @raise_if_invalid = opts.fetch(:raise, false)
  @skip_list        = opts.fetch(:skip, []).map {|r| /\A#{r}\Z/i}
  @skip_if          = opts[:skip_if]
  @check_only_list  = opts.fetch(:check_only, []).map {|r| /\A#{r}\Z/i}
  @@field           = opts[:field] if opts[:field]
  @@header          = opts[:header] if opts[:header]
  @@key             = opts[:key] if opts[:key]

  standard_http_methods = %w(POST PUT DELETE PATCH)
  check_also            = opts.fetch(:check_also, [])
  @http_methods = (standard_http_methods + check_also).flatten.uniq
end

Class Method Details

.fieldObject Also known as: csrf_field



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

def self.field
  @@field
end

.headerObject Also known as: csrf_header



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

def self.header
  @@header
end

.keyObject Also known as: csrf_key



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

def self.key
  @@key
end

.metatag(env, options = {}) ⇒ Object Also known as: csrf_metatag



65
66
67
68
# File 'lib/rack/csrf.rb', line 65

def self.metatag(env, options = {})
  name = options.fetch(:name, '_csrf')
  %Q(<meta name="#{name}" content="#{token(env)}" />)
end

.tag(env) ⇒ Object Also known as: csrf_tag



61
62
63
# File 'lib/rack/csrf.rb', line 61

def self.tag(env)
  %Q(<input type="hidden" name="#{field}" value="#{token(env)}" />)
end

.token(env) ⇒ Object Also known as: csrf_token



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

def self.token(env)
  env['rack.session'][key] ||= SecureRandom.urlsafe_base64(32)
end

Instance Method Details

#call(env) ⇒ Object



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

def call(env)
  unless env['rack.session']
    fail SessionUnavailable, 'Rack::Csrf depends on session middleware'
  end
  req = Rack::Request.new(env)
  let_it_pass = skip_checking(req) ||
    !@http_methods.include?(req.request_method) ||
    found_a_valid_token?(req)
  if let_it_pass
    @app.call(env)
  else
    fail InvalidCsrfToken if @raise_if_invalid
    [403, {'Content-Type' => 'text/html', 'Content-Length' => '0'}, []]
  end
end