import time from django.utils.deprecation import MiddlewareMixin from django.utils.http import http_date from django.conf import settings class TrackMiddleware(MiddlewareMixin): def process_response(self, request, response): if (settings.DEBUG or settings.STAGING): return response uid = request.COOKIES.get('uid') if request.user.is_authenticated: if request.user.openid != uid: max_age = 60 * 60 * 24 * 730 expires_time = time.time() + max_age expires = http_date(expires_time) host = request.get_host() domain = extract_top_domain(host) response.set_cookie( 'uid', request.user.openid, max_age=max_age, expires=expires, domain=domain, ) return response def extract_top_domain(host): if not host: return host if host in ['localhost', '127.0.0.1', '[::1]']: return host return '.'.join(host.split('.')[-2:])