Class: Otto::Security::CSRFMiddleware

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

Constant Summary collapse

SAFE_METHODS =
%w[GET HEAD OPTIONS TRACE].freeze

Instance Method Summary collapse

Constructor Details

#initialize(app, config = nil) ⇒ CSRFMiddleware

Returns a new instance of CSRFMiddleware.



10
11
12
13
# File 'lib/otto/security/csrf.rb', line 10

def initialize(app, config = nil)
  @app = app
  @config = config || Otto::Security::Config.new
end

Instance Method Details

#call(env) ⇒ Object



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/otto/security/csrf.rb', line 15

def call(env)
  return @app.call(env) unless @config.csrf_enabled?

  request = Rack::Request.new(env)

  # Skip CSRF protection for safe methods
  if safe_method?(request.request_method)
    response = @app.call(env)
    response = inject_csrf_token(request, response) if html_response?(response)
    return response
  end

  # Validate CSRF token for unsafe methods
  unless valid_csrf_token?(request)
    return csrf_error_response
  end

  @app.call(env)
end