Class: RailsSameSiteCookie::Middleware

Inherits:
Object
  • Object
show all
Defined in:
lib/rails_same_site_cookie/middleware.rb

Constant Summary collapse

"\n".freeze

Instance Method Summary collapse

Constructor Details

#initialize(app) ⇒ Middleware

Returns a new instance of Middleware.



8
9
10
# File 'lib/rails_same_site_cookie/middleware.rb', line 8

def initialize(app)
  @app = app
end

Instance Method Details

#call(env) ⇒ Object



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/rails_same_site_cookie/middleware.rb', line 12

def call(env)
  status, headers, body = @app.call(env)

  regex = RailsSameSiteCookie.configuration.user_agent_regex
  set_cookie = headers['Set-Cookie']
  if (regex.nil? or regex.match(env['HTTP_USER_AGENT'])) and not (set_cookie.nil? or set_cookie.strip == '')
    parser = UserAgentChecker.new(env['HTTP_USER_AGENT'])
    if parser.send_same_site_none?
      cookies = set_cookie.split(COOKIE_SEPARATOR)
      ssl = Rack::Request.new(env).ssl?

      cookies.each do |cookie|
        next if cookie == '' or cookie.nil?
        next if !ssl && parser.chrome? # https://www.chromestatus.com/feature/5633521622188032

        if ssl and not cookie =~ /;\s*secure/i
          cookie << '; Secure'
        end

        unless cookie =~ /;\s*samesite=/i
          cookie << '; SameSite=None'
        end

      end

      headers['Set-Cookie'] = cookies.join(COOKIE_SEPARATOR)
    end
  end

  [status, headers, body]
end