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.