In django_session
table session_data
is stored which is first pickled using pickle module of python and then encoded in base64 by using base64 module of python.
I got the decoded pickled session_data.
session_data from django_session table:
gAJ9cQEoVQ9fc2Vzc2lvbl9leHBpcnlxAksAVRJfYXV0aF91c2VyX2JhY2tlbmRxA1UpZGphbmdvLmNvbnRyaWIuYXV0aC5iYWNrZW5kcy5Nb2RlbEJhY2tlbmRxBFUNX2F1dGhfdXNlcl9pZHEFigECdS5iZmUwOWExOWI0YTZkN2M0NDc2MWVjZjQ5ZDU0YjNhZA==
after decoding it by base64.decode(session_data):
\x80\x02}q\x01(U\x0f_session_expiryq\x02K\x00U\x12_auth_user_backendq\x03U)django.contrib.auth.backends.ModelBackendq\x04U\r_auth_user_idq\x05\x8a\x01\x02u.bfe09a19b4a6d7c44761ecf49d54b3ad
I want to find out the value of auth_user_id
from auth_user_idq\x05\x8a\x01\x02u
. Please help me to do so.
NOTE: format changed since original answer, for 1.4 and above see the update below
[update]
I really don't know why I used the base64 module, I guess because the question featured it.
You can just use the
str.decode
method:Loading pickled data from user sources (cookies) is a security risk, so the session_data format was changed since this question was answered (I should go after the specific issue in Django's bug tracker and link it here, but my pomodoro break is gone).
The format now (since Django 1.4) is "hash:json-object" where the first 40 byte hash is a crypto-signature and the rest is a JSON payload. For now you can ignore the hash (it allows checking if the data was not tampered by some cookie hacker).
I had trouble with Paulo's method (see my comment on his answer), so I ended up using this method from a scottbarnham.com blog post:
I wanted to do this in pure Python with the latest version of DJango (2.05). This is what I did:
If you want to learn more about it and know how does encode or decode work, there are some relevant code. By the way the version of Django that i use is 1.9.4.
django/contrib/sessions/backends/base.py
django/contrib/sessions/serializer.py
Let's focus on SessionBase's encode function.
So, decode is inverse. We can simplify the decode function in the following code.
And that what session.get_decoded() did.