signed_cookies.py 2.6 KB

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