Skip to content

Instantly share code, notes, and snippets.

@robhudson
Created September 25, 2013 16:12
Show Gist options
  • Save robhudson/6702014 to your computer and use it in GitHub Desktop.
Save robhudson/6702014 to your computer and use it in GitHub Desktop.
CNAME handling in Django middleware example
import threading
from django.conf import settings
from django.http import HttpResponseRedirect
# We used our own model to associate users with sites, but could use django.contrib.sites here.
from .models import Network
# List of allowed URLs if user isn't in the network
ALLOWED = [
u'/accounts/register/',
u'/accounts/network_connect/',
]
# There are only a few cases where it's harder or less optimized to pass
# request, so a threading local is used.
_network = threading.local()
def set_network(network):
_network.network = network
class NetworkMiddleware(object):
def process_request(self, request):
network = self.get_network_from_request(request)
# Make sure network exists
if not network:
return HttpResponseRedirect(settings.SITE_ROOT_URL)
# Make sure user is in this network
if not request.user.is_anonymous():
if not network in request.user.network_set.all():
if request.path in ALLOWED:
pass # Allow the request to go through
else:
return HttpResponseRedirect(settings.SITE_ROOT_URL)
request.network = network
def get_network_from_request(self, request):
base_domain = settings.SESSION_COOKIE_DOMAIN
# Get network from subdomain (http://<network>.domain.com)
host = request.META.get('HTTP_HOST', '')
if not host.endswith(base_domain):
return HttpResponseRedirect(settings.SITE_ROOT_URL)
vhost = host[:-len(base_domain)].replace('.', '-')
try:
network = Network.objects.get(slug=vhost)
except Network.DoesNotExist:
network = None
set_network(network)
return network
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment