Source code for superdjango.contrib.accounts.impersonation.middleware

# Imports

from django.contrib.auth import get_user_model
from .constants import IMPERSONATION_FOR_ID, IMPERSONATION_SESSION_KEY
from .utils import user_is_allowed_to_impersonate

# Exports

__all__ = (
    "UserImpersonationMiddleware",
)

# Processors


[docs]class UserImpersonationMiddleware: """Facilitate user impersonation."""
[docs] def __init__(self, get_response): self.get_response = get_response
def __call__(self, request): # Do nothing if the current user isn't allowed to impersonate. if not user_is_allowed_to_impersonate(request.user): return self.get_response(request) # Always assume the user is not impersonating by default. request.user.is_impersonated = False request.impersonator = None # noinspection PyPep8Naming UserModel = get_user_model() if request.user.is_authenticated and IMPERSONATION_SESSION_KEY in request.session: try: for_id = request.session[IMPERSONATION_FOR_ID] user = UserModel.objects.get(pk=for_id) request.impersonator = request.user request.user = user request.user.is_impersonated = True except UserModel.DoesNotExist: pass return self.get_response(request)