1

I use the same Django project for various domains. Some are subdomains, some are entirely different domains, so I have these domains operating the same Django site:

  • a.example1.com
  • b.example1.com
  • c.example1.com
  • example1.com
  • example2.com

I do not use the sites framework for reasons unrelated to this query, and I have a single settings.py for all sites, which I'd like to maintain.

When someone logs onto a subdomain, I'd like them to be logged onto any of the other subdomains as well. In fact, if it were possible I'd like them to be logged onto the other sites as well but I doubt this is possible. In order to achieve logging into all subdomains at the same time, I set the following variable in settings.py:

SESSION_COOKIE_DOMAIN=".example1.com"

This works as advertised and the logins are now working across different sites. However, I am not able to log onto any of the other domains anymore (I assume the cookie is set for the wrong domain and subsequently not properly recognized). What I assume I should do is somehow set SESSION_COOKIE_DOMAIN to either .example1.com when on the main site, or .example2.com when I'm on a different site. But how to achieve this?

Here is a similar question and this answer seems to do what I am looking for through a lightweight solution. However, this is written for older Django versions. I tried rewriting this for Django 3 as follows:

class CrossDomainSessionMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        try:
            if request.COOKIES:
                host = request.get_host()
                # check if it's a different domain
                if host not in settings.SESSION_COOKIE_DOMAIN:
                    domain = ".{domain}".format(domain=host)
                    for cookie in request.COOKIES:
                        if "domain" in request.COOKIES[cookie]:
                            request.cookies[cookie]['domain'] = domain
        except:
            pass
        return self.get_response(request)

But this doesn't seem to work. This condition:

if "domain" in request.COOKIES[cookie]:

Is simply never met. Not sure what I should change.

  • Why not just set a simple environment variable on your different... environments and base the setting on that? – Tom Carrick Jun 29 '20 at 08:52
  • I've never done that before - can you let me know how to do that? –  Jun 29 '20 at 09:10
  • How you set the environment variable will depend on your server. For the Django part, you can put `SECURE_COOKIE_DOMAIN = os.getenv("SECURE_COOKIE_DOMAIN")` in your settings file. – Tom Carrick Jun 29 '20 at 09:12
  • 1
    I see. But all sites live on the exact same server and as far as I know operate in the same environment, so how would I be able to set different environment variables? –  Jun 29 '20 at 10:32

0 Answers0