Commits

Peter Sanchez committed e7f3640 Merge

Merged in mvantellingen/django-impersonate/with-real-user (pull request #6)

Always add the is_impersonate attribute and set the real user as attribute

Comments (0)

Files changed (3)

 
     {% if user.is_impersonate %} .... {% endif %}
 
+The original user is available as "request.impersonator".
+
+    {{ request.user }} ({{ request.impersonator }})
+
 You can reference this URL with reverse() or the {% url %} template tag 
 as 'impersonate-start'
 

impersonate/middleware.py

 
 class ImpersonateMiddleware(object):
     def process_request(self, request):
+        request.user.is_impersonate = False
+        request.impersonator = None
+
         if request.user.is_authenticated() and \
            '_impersonate' in request.session:
             new_user = request.session['_impersonate']
+
             if check_allow_for_user(request, new_user) and \
                check_allow_for_uri(request.path):
+                request.impersonator = request.user
                 request.user = new_user
                 request.user.is_impersonate = True
 from django.test import TestCase
 from django.utils import unittest
 from django.http import HttpResponse
-from django.test.client import Client
+from django.test.client import Client, RequestFactory
 from django.core.urlresolvers import reverse
 from django.test.utils import override_settings
 from django.conf.urls.defaults import patterns, url, include
             return user
 
 
+class TestMiddleware(TestCase):
+    def setUp(self):
+        from impersonate.middleware import ImpersonateMiddleware
+
+        self.superuser = UserFactory(username='superuser', is_superuser=True)
+        self.user = UserFactory(username='regular')
+        self.factory = RequestFactory()
+        self.middleware = ImpersonateMiddleware()
+
+    def test_impersonated_request(self):
+        request = self.factory.get('/')
+        request.user = self.superuser
+        request.session = {
+            '_impersonate': self.user
+        }
+        self.middleware.process_request(request)
+
+        # Check request.user and request.user.real_user
+        self.assertEqual(request.user, self.user)
+        self.assertEqual(request.impersonator, self.superuser)
+        self.assertTrue(request.user.is_impersonate)
+
+
 class TestImpersonation(TestCase):
     def setUp(self):
         self.client = Client()