Class: Rack::SslEnforcer

Inherits:
Object
  • Object
show all
Defined in:
lib/rack/ssl-enforcer.rb,
lib/rack/ssl-enforcer/version.rb

Constant Summary collapse

VERSION =
"0.2.2.1"

Instance Method Summary collapse

Constructor Details

#initialize(app, options = {}) ⇒ SslEnforcer

Warning: If you set the option force_secure_cookies to false, make sure that your cookies

are encoded and that you understand the consequences (see documentation)


6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# File 'lib/rack/ssl-enforcer.rb', line 6

def initialize(app, options={})
  default_options = {
    :redirect_to => nil,
    :only => nil,
    :only_hosts => nil,
    :except => nil,
    :except_hosts => nil,
    :strict => false,
    :mixed => false,
    :hsts => nil,
    :http_port => nil,
    :https_port => nil,
    :force_secure_cookies => true
  }
  @app, @options = app, default_options.merge(options)
end

Instance Method Details

#call(env) ⇒ Object



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/rack/ssl-enforcer.rb', line 23

def call(env)
  @req = Rack::Request.new(env)
  if enforce_ssl?(@req)
    scheme = 'https' unless ssl_request?(env)
  elsif ssl_request?(env) && enforcement_non_ssl?(env)
    scheme = 'http'
  end

  if scheme
    location = replace_scheme(@req, scheme).url
    body     = "<html><body>You are being <a href=\"#{location}\">redirected</a>.</body></html>"
    [301, { 'Content-Type' => 'text/html', 'Location' => location }, [body]]
  elsif ssl_request?(env)
    status, headers, body = @app.call(env)
    flag_cookies_as_secure!(headers) if @options[:force_secure_cookies]
    set_hsts_headers!(headers) if @options[:hsts] && !@options[:strict]
    [status, headers, body]
  else
    @app.call(env)
  end
end