Skip to content

Instantly share code, notes, and snippets.

@vierja
Created June 30, 2015 19:57
Show Gist options
  • Save vierja/c76dedc00aa618c7c477 to your computer and use it in GitHub Desktop.
Save vierja/c76dedc00aa618c7c477 to your computer and use it in GitHub Desktop.
Anonymous Tracking Middleware for Django
import uuid
import base64
from trubrain.settings import (
ANON_TRACKING_COOKIE,
ANON_TRACKING_COOKIE_MAX_AGE
)
class AnonTrackingMiddleware(object):
salt = 'anon_tracking'
def _get_cookie(self, request):
return request.get_signed_cookie(
ANON_TRACKING_COOKIE, None, salt=self.salt
)
def _set_cookie(self, response, anon_uuid):
response.set_signed_cookie(
ANON_TRACKING_COOKIE,
anon_uuid,
max_age=ANON_TRACKING_COOKIE_MAX_AGE,
salt=self.salt,
)
def _delete_cookie(self, response):
response.delete_cookie(ANON_TRACKING_COOKIE)
def process_request(self, request):
# If ANON_TRACKING_COOKIE cookie set, save value in request
if not request.user.is_authenticated():
anon_uuid = self._get_cookie(request)
if anon_uuid is not None:
request.anon_uuid = anon_uuid
else:
request.anon_uuid = str(uuid.uuid4())
def process_response(self, request, response):
# If not authenticated and cookie is None, set new anon_uuid
if hasattr(request, 'user') and not request.user.is_authenticated():
if self._get_cookie(request) is None and \
hasattr(request, 'anon_uuid'):
self._set_cookie(response, request.anon_uuid)
elif hasattr(request, 'user') and request.user.is_authenticated():
# Just in case if the user is authenticated we delete the cookie
# response.delete_cookie fails silently if no cookie exists.
self._delete_cookie(response)
return response
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment