Search code examples
ruby-on-railssessioncookiessubdomain

What does Rails 3 session_store domain :all really do?


Updated question to make it more clear

I understand that you can set the domain of your session_store to share sessions between subdomains like this: Rails.application.config.session_store :cookie_store, :key => '_my_key', :domain => "mydomain.example"

in Rails 3, what does the setting :domain => :all do? It can't let you share sessions across top-level domains, cookies can't do that. The documentation says it assumes one top level domain. So what happens if multiple domains access your app?

In my app, my users can create personal subdomains of one main domain, but then can also access that subdomain via their own custom domain.

What is the correct session_store domain setting so that I can: a) share sessions across all domains of my primary domain, eg mydomain.example b) users who access their personal subdomain eg "user1.mydomain.example" via a CNAME custom URL like some.otherdomain.example can still create separate sessions.


Solution

  • OK, the way to accomplish this is to set the domain on the session cookie dynamically. To do this early enough it should be done as rack middleware:

    # Custom Domain Cookie
    #
    # Set the cookie domain to the custom domain if it's present
    class CustomDomainCookie
      def initialize(app, default_domain)
        @app = app
        @default_domain = default_domain
      end
    
      def call(env)
        host = env["HTTP_HOST"].split(':').first
        env["rack.session.options"][:domain] = custom_domain?(host) ? ".#{host}" : "#{@default_domain}"
        @app.call(env)
      end
    
      def custom_domain?(host)
        host !~ /#{@default_domain.sub(/^\./, '')}/i
      end
    end