Commits

Anonymous committed b3932f5

Factor out helper functions impersonate_start/stop and allow impersonation via GET args.

Comments (0)

Files changed (3)

impersonate/helpers.py

             return False
 
     return True
+
+
+def impersonate_start(request, uid):
+    ''' Takes in the UID of the user to impersonate.
+        View will fetch the User instance and store it 
+        in the request.session under the '_impersonate' key.
+        
+        The middleware will then pick up on it and adjust the 
+        request object as needed.
+    '''
+    new_user = get_object_or_404(User, pk=uid)
+    if check_allow_for_user(request, new_user):
+        request.session['_impersonate'] = new_user
+        request.session.modified = True  # Let's make sure...
+
+
+def impersonate_stop(request):
+    if '_impersonate' in request.session:
+        del request.session['_impersonate']
+        request.session.modified = True
+

impersonate/middleware.py

 from django.conf import settings
-from helpers import check_allow_for_user, check_allow_for_uri
+from helpers import (check_allow_for_user, check_allow_for_uri,
+    impersonate_stop, impersonate_start)
 
 
 class ImpersonateMiddleware(object):
     def process_request(self, request):
         if request.user.is_authenticated() and \
            '_impersonate' in request.session:
+            if request.GET.get('impersonate-stop', None):
+                impersonate_stop(request)
+            
+            try:
+                uid = int(request.GET.get('impersonate-start', None))
+            except: pass
+            else:
+                impersonate_stop(request, uid)
+            
             new_user = request.session['_impersonate']
             if check_allow_for_user(request, new_user) and \
                check_allow_for_uri(request.path):

impersonate/views.py

 from django.shortcuts import get_object_or_404, redirect, render_to_response
 from decorators import allowed_user_required
 from helpers import get_redir_path, get_paginator, check_allow_for_user, \
-                    users_impersonable
+                    users_impersonable, impersonate_stop, impersonate_start
 
 
 @allowed_user_required
         The middleware will then pick up on it and adjust the 
         request object as needed.
     '''
-    new_user = get_object_or_404(User, pk=uid)
-    if check_allow_for_user(request, new_user):
-        request.session['_impersonate'] = new_user
-        request.session.modified = True  # Let's make sure...
+    impersonate_start(request, uid)
     return redirect(get_redir_path())
 
 
 def stop_impersonate(request):
     ''' Remove the impersonation object from the session
     '''
-    if '_impersonate' in request.session:
-        del request.session['_impersonate']
-        request.session.modified = True
+    impersonate_stop()
     return redirect(get_redir_path())