# HG changeset patch
# User Jordi Gutiérrez Hermoso <jordigh@gnu.org>
# Date 1612473215 18000
# Thu Feb 04 16:13:35 2021 -0500
# Node ID 02c4ab3442b2f9c2df491b0663fae5caa8129418
# Parent ccefd024a3fbf62b698bf38d750b7d03d1d74a65
Record the impersonator on the user object.
Sometimes you need to inspect the user well below the level of the
Django view. In our particular case, we wanted to overwrite Django's
email backend to always send all email to the current user in the
request. The email backend is far removed from the context of the
Django view, and the original request is now lost further up the call
stack.
While it is currently possible to guess who the impersonating user
might be by inspecting `impersonated_by` logs and taking the latest
log entry, this is a little brittle. It is easier to have the
impersonator on the impersonated user object.
diff --git a/README.md b/README.md
--- a/README.md
+++ b/README.md
@@ -102,8 +102,9 @@ Replace <user-id> with the user id
impersonate.
While in impersonation "mode" the `request.user` object will have an
-`is_impersonate` attribute set to `True`. So if you wanted to check in
-your templates or view, you just do something like...:
+`is_impersonate` attribute set to `True` as well as
+`request.impersonator` set to the original user. So if you wanted to
+check in your templates or view, you just do something like...:
{% if user.is_impersonate %} .... {% endif %}
diff --git a/impersonate/middleware.py b/impersonate/middleware.py
--- a/impersonate/middleware.py
+++ b/impersonate/middleware.py
@@ -56,5 +56,6 @@ class ImpersonateMiddleware(MiddlewareMi
request.impersonator = request.user
request.user = new_user
request.user.is_impersonate = True
+ request.user.impersonator = request.impersonator
request.real_user = request.impersonator or request.user
diff --git a/impersonate/tests.py b/impersonate/tests.py
--- a/impersonate/tests.py
+++ b/impersonate/tests.py
@@ -124,6 +124,7 @@ class TestMiddleware(TestCase):
# Check request.user and request.user.real_user
self.assertEqual(request.user, self.user)
self.assertEqual(request.impersonator, self.superuser)
+ self.assertEqual(request.user.impersonator, self.superuser)
self.assertEqual(request.real_user, self.superuser)
self.assertTrue(request.user.is_impersonate)