Last active
August 12, 2024 04:27
-
-
Save dbrgn/bae5329e17d2801a041e to your computer and use it in GitHub Desktop.
Manually create a Django session
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from django.contrib import auth | |
from django.contrib.sessions.backends.db import SessionStore | |
session = SessionStore(None) | |
session.clear() | |
session.cycle_key() | |
session[auth.SESSION_KEY] = user._meta.pk.value_to_string(user) | |
session[auth.BACKEND_SESSION_KEY] = 'django.contrib.auth.backends.ModelBackend' | |
session[auth.HASH_SESSION_KEY] = user.get_session_auth_hash() | |
session.save() |
Really helped me :D Thanks
BTW, why not use this on production server?
Thank you for sharing this 👍
Worth noting this is totally fine for production, as it very closely matches how Django does it (https://github.com/django/django/blob/3f2821af6bc48fa8e7970c1ce27bc54c3172545e/django/contrib/auth/__init__.py#L126), just that Django has a few more checks around the incoming data. If you need a session to impersonate a user programmatically, this is a good way to go!
Worked for me, GJ!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Only use this for testing, not for production systems!