signed_cookies.py 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. from django.conf import settings
  2. from django.core import signing
  3. from django.contrib.sessions.backends.base import SessionBase
  4. class SessionStore(SessionBase):
  5. def load(self):
  6. """
  7. We load the data from the key itself instead of fetching from
  8. some external data store. Opposite of _get_session_key(),
  9. raises BadSignature if signature fails.
  10. """
  11. try:
  12. return signing.loads(self.session_key,
  13. serializer=self.serializer,
  14. # This doesn't handle non-default expiry dates, see #19201
  15. max_age=settings.SESSION_COOKIE_AGE,
  16. salt='django.contrib.sessions.backends.signed_cookies')
  17. except (signing.BadSignature, ValueError):
  18. self.create()
  19. return {}
  20. def create(self):
  21. """
  22. To create a new key, we simply make sure that the modified flag is set
  23. so that the cookie is set on the client for the current request.
  24. """
  25. self.modified = True
  26. def save(self, must_create=False):
  27. """
  28. To save, we get the session key as a securely signed string and then
  29. set the modified flag so that the cookie is set on the client for the
  30. current request.
  31. """
  32. self._session_key = self._get_session_key()
  33. self.modified = True
  34. def exists(self, session_key=None):
  35. """
  36. This method makes sense when you're talking to a shared resource, but
  37. it doesn't matter when you're storing the information in the client's
  38. cookie.
  39. """
  40. return False
  41. def delete(self, session_key=None):
  42. """
  43. To delete, we clear the session key and the underlying data structure
  44. and set the modified flag so that the cookie is set on the client for
  45. the current request.
  46. """
  47. self._session_key = ''
  48. self._session_cache = {}
  49. self.modified = True
  50. def cycle_key(self):
  51. """
  52. Keeps the same data but with a new key. To do this, we just have to
  53. call ``save()`` and it will automatically save a cookie with a new key
  54. at the end of the request.
  55. """
  56. self.save()
  57. def _get_session_key(self):
  58. """
  59. Most session backends don't need to override this method, but we do,
  60. because instead of generating a random string, we want to actually
  61. generate a secure url-safe Base64-encoded string of data as our
  62. session key.
  63. """
  64. session_cache = getattr(self, '_session_cache', {})
  65. return signing.dumps(session_cache, compress=True,
  66. salt='django.contrib.sessions.backends.signed_cookies',
  67. serializer=self.serializer)
  68. @classmethod
  69. def clear_expired(cls):
  70. pass