Hot-keys on this page
r m x p toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
1# Imports
3from django.contrib.auth import get_user_model
4from .constants import IMPERSONATION_FOR_ID, IMPERSONATION_SESSION_KEY
5from .utils import user_is_allowed_to_impersonate
7# Exports
9__all__ = (
10 "UserImpersonationMiddleware",
11)
13# Processors
16class UserImpersonationMiddleware:
17 """Facilitate user impersonation."""
19 def __init__(self, get_response):
20 self.get_response = get_response
22 def __call__(self, request):
23 # Do nothing if the current user isn't allowed to impersonate.
24 if not user_is_allowed_to_impersonate(request.user):
25 return self.get_response(request)
27 # Always assume the user is not impersonating by default.
28 request.user.is_impersonated = False
29 request.impersonator = None
31 # noinspection PyPep8Naming
32 UserModel = get_user_model()
34 if request.user.is_authenticated and IMPERSONATION_SESSION_KEY in request.session:
35 try:
36 for_id = request.session[IMPERSONATION_FOR_ID]
37 user = UserModel.objects.get(pk=for_id)
39 request.impersonator = request.user
40 request.user = user
41 request.user.is_impersonated = True
42 except UserModel.DoesNotExist:
43 pass
45 return self.get_response(request)