Created
October 15, 2014 12:50
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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