Class: StaticRails::SitePlusCsrfMiddleware

Inherits:
SiteMiddleware show all
Defined in:
lib/static-rails/site_plus_csrf_middleware.rb

Constant Summary

Constants inherited from SiteMiddleware

StaticRails::SiteMiddleware::PATH_INFO_OBFUSCATION

Instance Method Summary collapse

Constructor Details

#initialize(app) ⇒ SitePlusCsrfMiddleware

Returns a new instance of SitePlusCsrfMiddleware.



8
9
10
11
12
13
# File 'lib/static-rails/site_plus_csrf_middleware.rb', line 8

def initialize(app)
  @determines_whether_to_handle_request = DeterminesWhetherToHandleRequest.new
  @validates_csrf_token = ValidatesCsrfToken.new
  @gets_csrf_token = GetsCsrfToken.new
  super
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
34
35
36
# File 'lib/static-rails/site_plus_csrf_middleware.rb', line 15

def call(env)
  return @app.call(env) unless env["PATH_INFO"]&.start_with?(/\/?#{PATH_INFO_OBFUSCATION}/o) || @determines_whether_to_handle_request.call(env)

  env = env.merge(
    "PATH_INFO" => env["PATH_INFO"].gsub(/^\/?#{PATH_INFO_OBFUSCATION}/o, "")
  )
  status, headers, body = super(env)

  if StaticRails.config.set_csrf_token_cookie
    req = Rack::Request.new(env)
    res = Rack::Response.new(body, status, headers)
    if needs_new_csrf_token?(req)
      res.set_cookie("_csrf_token", {
        value: @gets_csrf_token.call(req),
        path: "/"
      })
    end
    res.finish
  else
    [status, headers, body]
  end
end