You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

signed_cookies.py 2.6KB

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