Created
October 30, 2012 19:37
-
-
Save glarrain/3982485 to your computer and use it in GitHub Desktop.
Decode session data, no matter what hashes say. It helps in some cases where the Session.get_decoded method returns an empty dictionary because it is "suspicious" of user-data tampering. Based on source code from the Django project.
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
import base64 | |
import pickle | |
from django.contrib.sessions.models import Session | |
from django.utils.encoding import force_unicode | |
def decode_session_data(session_key): | |
"""Decode the data in a session object stored under ``session_key``. | |
:param session_key: e.g. ``'1180b5ed42c2a3a5f217e35b755865da'`` | |
:return: decoded session data | |
:rtype: :class:`dict` | |
""" | |
session_obj = Session.objects.get(pk=session_key) | |
session_data = force_unicode(session_obj.session_data) | |
encoded_data = base64.decodestring(session_data) | |
hash, pickled = encoded_data.split(':', 1) | |
return pickle.loads(pickled) |
Created 13 years ago
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@glarrain Please specify Django & python version as well ( on whcih this snippet runs )
on python3.12 and django 5 + following are the issues with this script :
from django.utils.encoding import force_unicode
from django.utils.encoding import force_str
orfrom django.utils.encoding import force_text
whichever works with your version , as In Django 3.0+, force_unicode was renamed to force_text, and then in later versions, it was further refined to force_str.base64.decodestring
won't workbase64.decodestring()
withbase64.decodebytes()
Any ways , if your use case is that of mine , i.e viewing the session data in decoded form , you can simply write a custom SessionAdmin and register it and view it in django admin panel . Here's the code you can include in you
admin.py
file :NOTE : i am using
python3.12
andDjango==5.2.5
.