I have a Django app. When logged in as an admin user, I want to be able to pass a secret parameter in the URL and have the whole site behave as if I were another user.
Let's say I have the URL
I solved this with a simple middleware. It also handles redirects (that is, the GET parameter is preserved during a redirect). Here it is:
class ImpersonateMiddleware(object): def process_request(self, request): if request.user.is_superuser and "__impersonate" in request.GET: request.user = models.User.objects.get(id=int(request.GET["__impersonate"])) def process_response(self, request, response): if request.user.is_superuser and "__impersonate" in request.GET: if isinstance(response, http.HttpResponseRedirect): location = response["Location"] if "?" in location: location += "&" else: location += "?" location += "__impersonate=%s" % request.GET["__impersonate"] response["Location"] = location return response