Class: Otto::Security::Middleware::CSRFMiddleware

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

Overview

Global middleware that injects CSRF tokens into HTML responses.

Token enforcement deliberately does NOT live here. This middleware runs ahead of route matching, so it cannot see per-route options like +csrf=exempt+ (issue #186); enforcing globally would block routes an operator explicitly exempted. Enforcement is applied after matching by +Otto::Security::CSRFEnforcementWrapper+ at the handler layer, where the route definition is available. This middleware keeps only the response-shaping half — injecting a fresh token into HTML responses so forms and meta tags can carry it — which is method/content-type based and correctly stays global.

Instance Method Summary collapse

Constructor Details

#initialize(app, config = nil) ⇒ CSRFMiddleware

Returns a new instance of CSRFMiddleware.



22
23
24
25
# File 'lib/otto/security/middleware/csrf_middleware.rb', line 22

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

Instance Method Details

#call(env) ⇒ Object



27
28
29
30
31
32
33
34
# File 'lib/otto/security/middleware/csrf_middleware.rb', line 27

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

  request  = Otto::Request.new(env)
  response = @app.call(env)
  response = inject_csrf_token(request, response) if html_response?(response)
  response
end