django-impersonate: Record the impersonator on the user object v1 APPLIED

Jordi Gutiérrez Hermoso
Jordi Gutiérrez Hermoso: 1
 Record the impersonator on the user object

 3 files changed, 5 insertions(+), 2 deletions(-)
Export patchset (mbox)
How do I use this?

Copy & paste the following snippet into your terminal to import this patchset into git:

curl -s https://lists.code.netlandish.com/~petersanchez/public-inbox/patches/8/mbox | git am -3
Learn more about email & git
View this thread in the archives

[PATCH django-impersonate] Record the impersonator on the user object Export this patch

Jordi Gutiérrez Hermoso
# 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

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 &lt;user-id&gt; with the user id

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)