lib/global_session/rack.rb in global_session-3.1.1 vs lib/global_session/rack.rb in global_session-3.2.0

- old
+ new

@@ -25,10 +25,12 @@ module GlobalSession module Rack # Global session middleware. Note: this class relies on # Rack::Cookies being used higher up in the chain. class Middleware + NUMERIC_HOST = /^[0-9.]+$/.freeze + LOCAL_SESSION_KEY = "rack.session".freeze # @return [GlobalSession::Configuration] attr_accessor :configuration @@ -230,17 +232,19 @@ end value = session.to_s expires = @configuration['ephemeral'] ? nil : session.expired_at unless env['rack.cookies'][@cookie_name] == value + secure = (env['HTTP_X_FORWARDED_PROTO'] == 'https') || + (env['rack.url_scheme'] == 'https') env['rack.cookies'][@cookie_name] = { :value => value, :domain => cookie_domain(env), :expires => expires, :httponly => true, - :secure => (env['rack.url_scheme'] == 'https'), + :secure => secure, } end else # write an empty cookie wipe_cookie(env) @@ -314,17 +318,30 @@ # in the configuration if one is found; otherwise, uses the SERVER_NAME from the request # but strips off the first component if the domain name contains more than two components. # # @param [Hash] env Rack request environment def cookie_domain(env) + name = env['HTTP_X_FORWARDED_HOST'] || env['SERVER_NAME'] + if @configuration['cookie'].has_key?('domain') # Use the explicitly provided domain name domain = @configuration['cookie']['domain'] + elsif name =~ NUMERIC_HOST + # Don't set a domain if the browser requested an IP-based host + domain = nil else - # Use the server name, but strip off the most specific component - parts = env['SERVER_NAME'].split('.') - parts = parts[1..-1] if parts.length > 2 - domain = parts.join('.') + # Guess an appropriate domain for the cookie. Strip one level of + # subdomain; leave SLDs unmolested; omit domain entirely for + # one-component domains (e.g. localhost). + parts = name.split('.') + case parts.length + when 0..1 + domain = nil + when 2 + domain = parts.join('.') + else + domain = parts[1..-1].join('.') + end end domain end end