lib/global_session/rack.rb in global_session-2.0.3 vs lib/global_session/rack.rb in global_session-3.0.0

- old
+ new

@@ -155,11 +155,10 @@ # env(Hash): Rack environment def update_cookie(env) return unless @directory.local_authority_name return if env['global_session.req.update'] == false - domain = @configuration['cookie']['domain'] || env['SERVER_NAME'] session = env['global_session'] if session unless session.valid? old_session = session @@ -170,15 +169,18 @@ value = session.to_s expires = @configuration['ephemeral'] ? nil : session.expired_at unless env['rack.cookies'][@cookie_name] == value env['rack.cookies'][@cookie_name] = - {:value => value, :domain => domain, :expires => expires, :httponly=>true} + {:value => value, + :domain => cookie_domain(env), + :expires => expires, + :httponly=>true} end else # write an empty cookie - env['rack.cookies'][@cookie_name] = {:value => nil, :domain => domain, :expires => Time.at(0)} + wipe_cookie(env) end rescue Exception => e wipe_cookie(env) raise e end @@ -189,12 +191,13 @@ # env(Hash): Rack environment def wipe_cookie(env) return unless @directory.local_authority_name return if env['global_session.req.update'] == false - domain = @configuration['cookie']['domain'] || env['SERVER_NAME'] - env['rack.cookies'][@cookie_name] = {:value => nil, :domain => domain, :expires => Time.at(0)} + env['rack.cookies'][@cookie_name] = {:value => nil, + :domain => cookie_domain(env), + :expires => Time.at(0)} end # Handle exceptions that occur during app invocation. This will either save the error # in the Rack environment or raise it, depending on the type of error. The error may # also be logged. @@ -231,9 +234,29 @@ if (local_session = env[LOCAL_SESSION_KEY]) && local_session.respond_to?(:rename!) local_session.rename!(old_session, new_session) end true + end + + # Determine the domain name for which we should set the cookie. Uses the domain specified + # 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. + # + # === Parameters + # env(Hash):: the Rack environment hash + def cookie_domain(env) + if @configuration['cookie'].key?('domain') + # Use the explicitly provided domain name + domain = @configuration['cookie']['domain'] + 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('.') + end + + domain end end end end