Working on Instahero these past few days, doing mostly customer development, I’ve frequently needed to log in as a user and see what they see, so I could walk them through using Instahero, troubleshoot issues they were having, or better respond to feedback.

To achieve that, I had written a custom authentication backend that allowed me to log in as any user I needed. This worked well, but it was a bit cumbersome because I had to log out and log back in through a custom interface.

I thought a bit, and came up with a much more elegant solution. A “Log in as user” button in the Django admin interface, on the user’s page:

"Log in as" button

I thought a bit about how to do that, and the admin interface was easy enough, since you can just extend it with a custom template. I added a corresponding view that serves a URL of the form /login/user/<id> and logs you in as that user, if you are already logged in as a superuser (it fails otherwise, which might not be what’s needed, since sometimes staff might need to log in as other users too).

The view was a bit trickier, as Django wants you to call authenticate() before login(), and authenticate() needs the user’s credentials to work. I could add a dummy backend, but that seemed superfluous, so I searched a bit and came upon this snippet, which lets you perform the appropriate magic manually and satisfy Django without calling authenticate().

The resulting app works very well so far, and I am very pleased with it. It has already made a big difference in how easily I can offer support to my users. I have called it django-loginas and put it up on Github here:

https://github.com/stochastic-technologies/django-loginas

I haven’t packaged it up yet, or uploaded it to PyPI, but if someone wants to package it and send me a pull request, I’ll accept and upload it right away. Let me know what you think!