Login

AdminPeepingMiddleware

Author:
buriy
Posted:
September 11, 2007
Language:
Python
Version:
.96
Score:
13 (after 13 ratings)

Peeping middleware, that replaces active user to another one for current http request. Admin permissions required to activate, so you can place this snippet even on the production server. Very useful for debugging purposes. Wish it to be part of Django.

How to use:

Put this middleware after all other middlewares in the list. Then just add ?as_user=username or &as_user=username to the url, where username is the name of user whose views you want to see.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
from django.contrib.auth.models import User
from django.shortcuts import get_object_or_404
from django.http import Http404

class AdminPeepingMiddleware(object):
    """
    Peeping middleware, that replaces active user to another one
    for current http request. Admin permissions required to activate,
    so you can place this snippet even on the production server.
    Very useful for debugging purposes. Wish it to be part of Django.
    How to use:
    Just add ?as_user=<username> or &as_user=<username> to the request,
    where username is the name of user whose views you want to see.
    """
    def process_request(self, request):
        if 'as_user' in request.GET:
            if not request.user.is_superuser: raise Http404
            as_user = request.GET.get('as_user')
            rpc = request.GET.copy()
            #XXX: removing because some views don't like additional arguments :(
            del rpc['as_user']
            request.GET = rpc
            user = get_object_or_404(User, username = as_user)
            request.user = user

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 10 months, 1 week ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 2 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
  5. Help text hyperlinks by sa2812 1 year, 6 months ago

Comments

PhiR (on October 3, 2007):

Had to add this to make it work. Otherwise, pretty nifty.

from django.contrib.auth.models import User
from django.shortcuts import get_object_or_404

#

buriy (on October 18, 2007):

yes, right, adding to the snippet

#

buriy (on November 24, 2007):

nobody mentioned wrong 'return Http404' instead of 'raise Http404'. fixed.

#

buriy (on November 24, 2007):

really due to django misbehaving with process_request errors it's not the matter to use raise or return.

#

Please login first before commenting.