Switching the Logged-in User in Django Using the Django Shell

Django
2023-10-12 21:41 (1 years ago) ytyng

How to Force Login as Another User for Inquiry Handling

When performing actions such as handling inquiries, be extremely cautious as incorrect operations or leaving the session logged in as another user can be dangerous. Do not perform these actions in a production environment.

The author assumes no responsibility for any impacts, damages, or issues that arise from performing these actions.

  1. First, log in to the Django application using your browser.
  2. Record the session_id from the cookies.
  3. Execute ./manage.py shell on the server.
# Your own session_id
session_id = 'abcd1234xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
# ID of the user you want to impersonate
user_id = 1

from django.conf import settings
from user.models import User

engine = __import__(settings.SESSION_ENGINE, {}, {}, [''])

session = engine.SessionStore(session_id)

dict(session)  # Confirm your own user ID

user = User.objects.get(id=user_id)
user  # Verify the user details

session['_auth_user_id'] = user.id
session['_auth_user_hash'] = user.get_session_auth_hash()
session.save()

Reload the browser, and you should be logged in as the desired user.

After completing the verification tasks, make sure to delete the cookies and log back in with the regular user to avoid any accidents.

Current rating: 5

Comments

Archive

2024
2023
2022
2021
2020
2019
2018
2017
2016
2015
2014
2013
2012
2011