DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

zwx00
zwx00

Posted on

How to impersonate a user through Django management shell

In a hypothetical scenario where you have access to the underlying system, there has to be a way to impersonate any given user that signed up on for your Django application.

It is however not as trivial to achieve this. There are packages like django-hijack etc., which provide this functionality, but we'd like to achieve it without installing new packages or modifying existing code. Here's a simple, non-intrusive way to go about it on a live environment.

Approach

First, you need to login into your Django application with any other account that you have access to. Visit the cookies tab in your development tools and copy the sessionid cookie value. It should look something like this: wxc0ldhcis45md5hbr3l7r4pyhewo0mr.

Then, on the system where Django server is running, access the Django management shell:

python manage.py dbshell
Enter fullscreen mode Exit fullscreen mode

Then do the following:

# Import the required interfaces
from django.contrib.sessions.models import Session
from boltobserver.users.models import User # This will be different for you, depending on where your User model is
from django.contrib.sessions.backends.db import SessionStore

# Find the user you wish to impersonate
u = User.objects.filter(email="someone@something.com").first()

# Find the session you are currently using in your browser
s = Session.objects.filter(session_key = "wxc0ldhcis45md5hbr3l7r4pyhewo0mr").first()

# And finally, modify the session by binding it to your target user
# _auth_user_backend might be different for you, check settings.AUTHENTICATION_BACKENDS for the right value
s2.session_data = SessionStore().encode({"_auth_user_id": str(u.id), "_auth_user_backend": "allauth.account.auth_backends.AuthenticationBackend", "_auth_user_hash": u.get_session_auth_hash()})
s2.save()

Enter fullscreen mode Exit fullscreen mode

After refreshing the page, you should be logged in as your desired user.

Thanks for reading!

Top comments (0)

🌚 Browsing with dark mode makes you a better developer.

It's a scientific fact.