Class: Rack::SslEnforcer

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

Constant Summary collapse

CONSTRAINTS_BY_TYPE =
{
  :hosts        => [:only_hosts, :except_hosts],
  :agents       => [:only_agents, :except_agents],
  :path         => [:only, :except],
  :methods      => [:only_methods, :except_methods],
  :environments => [:only_environments, :except_environments]
}
VERSION =
"1.0.0"

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)



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/rack/ssl-enforcer.rb', line 17

def initialize(app, options={})
  default_options = {
    :redirect_to          => nil,
    :redirect_code        => nil,
    :strict               => false,
    :mixed                => false,
    :hsts                 => nil,
    :http_port            => nil,
    :https_port           => nil,
    :force_secure_cookies => true,
    :redirect_html        => nil,
    :before_redirect      => nil
  }
  CONSTRAINTS_BY_TYPE.values.each do |constraints|
    constraints.each { |constraint| default_options[constraint] = nil }
  end

  @app, @options = app, default_options.merge(options)
end

Instance Method Details

#call(env) ⇒ Object



37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/rack/ssl-enforcer.rb', line 37

def call(env)
  req = Rack::Request.new(env)

  return @app.call(env) if ignore?(req)

  scheme = if enforce_ssl?(req)
    'https'
  elsif enforce_non_ssl?(req)
    'http'
  end

  if redirect_required?(req, scheme)
    call_before_redirect(req)
    modify_location_and_redirect(req, scheme)
  elsif ssl_request?(req)
    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