Class: ContentSecurityPolicy::Middleware

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

Instance Method Summary collapse

Constructor Details

#initialize(app) ⇒ Middleware

Returns a new instance of Middleware.



6
7
8
# File 'lib/content_security_policy/middleware.rb', line 6

def initialize(app)
  @app = app
end

Instance Method Details

#call(env) ⇒ Object



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/content_security_policy/middleware.rb', line 10

def call(env)
  request = Rack::Request.new(env)
  _, headers, _ = response = @app.call(env)

  return response unless html_response?(headers)

  # The EnforceHostname middleware ensures request.host_with_port can be trusted
  protocol = (SiteSetting.force_https || request.ssl?) ? "https://" : "http://"
  base_url = protocol + request.host_with_port + Discourse.base_path

  theme_id = env[:resolved_theme_id]

  headers["Content-Security-Policy"] = policy(
    theme_id,
    base_url: base_url,
    path_info: env["PATH_INFO"],
  ) if SiteSetting.content_security_policy
  headers["Content-Security-Policy-Report-Only"] = policy(
    theme_id,
    base_url: base_url,
    path_info: env["PATH_INFO"],
  ) if SiteSetting.content_security_policy_report_only

  response
end