Skip to content

Instantly share code, notes, and snippets.

@jtallieu
Created October 15, 2014 12:50
Show Gist options
  • Save jtallieu/5bd4cfb70c02822777e8 to your computer and use it in GitHub Desktop.
Save jtallieu/5bd4cfb70c02822777e8 to your computer and use it in GitHub Desktop.
Django Middleware that supports masquerading as another user without authentication. Requires views that will set the _masq_user session variable.
from django.contrib import auth
from django.core.exceptions import ImproperlyConfigured
from django.utils.functional import SimpleLazyObject
def get_user(request):
if request.session.has_key("_masq_user"):
return request.session["_masq_user"]
if not hasattr(request, '_cached_user'):
request._cached_user = auth.get_user(request)
return request._cached_user
class MaqueradeMiddleware(object):
def process_request(self, request):
assert hasattr(request, 'session'), "The Django authentication middleware requires session middleware to be installed. Edit your MIDDLEWARE_CLASSES setting to insert 'django.contrib.sessions.middleware.SessionMiddleware'."
request.user = SimpleLazyObject(lambda: get_user(request))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment