Skip to content

Instantly share code, notes, and snippets.

Created May 5, 2012 14:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anonymous/9ef870e91dc034f60179 to your computer and use it in GitHub Desktop.
Save anonymous/9ef870e91dc034f60179 to your computer and use it in GitHub Desktop.
import base64
try:
import json
except ImportError:
import simplejson as json
from django.contrib.sessions.backends.db import SessionStore as DBSessionStore
class SessionStore(DBSessionStore):
def __init__(self, *args, **kwargs):
super(SessionStore, self).__init__(*args, **kwargs)
def encode(self, session_dict):
"Returns the given session dictionary as json and encoded as a string."
data = json.dumps(session_dict)
hash = self._hash(data)
return base64.encodestring(hash + "$" + data)
def decode(self, session_data):
encoded_data = base64.decodestring(session_data)
try:
# could produce ValueError if there is no ':'
hash, data = encoded_data.split('$', 1)
print(hash, data)
expected_hash = self._hash(data)
if not constant_time_compare(hash, expected_hash):
raise SuspiciousOperation("Session data corrupted")
else:
return json.loads(data)
except Exception:
# ValueError, SuspiciousOperation, unpickling exceptions. If any of
# these happen, just return an empty dictionary (an empty session).
return {}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment