I added an admin trapdoor login to a project the other day. This is the technique where a superuser can log in to a site as any other user. My preferred way to do this is to use the standard login form in a clever way: enter the desired user’s name as the username, and both your superuser name and superuser password into the password field.
But this project was modern enough that I could use a Django authentication backend to get the job done:
from django.contrib.auth import login, authenticate
from django.contrib.auth.models import User
# So I can invoked authenticate recursively below
django_authenticate = authenticate
""" Let superusers login as regular users. """
def authenticate(self, username=None, password=None):
user = User.objects.get(username=username)
# The password should be name/password
if "@" not in password:
supername, superpass = password.split("@", 1)
superuser = django_authenticate(username=supername, password=superpass)
if superuser and superuser.is_superuser:
def get_user(self, user_id):