base.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329
  1. from __future__ import unicode_literals
  2. import base64
  3. from datetime import datetime, timedelta
  4. import logging
  5. import string
  6. from django.conf import settings
  7. from django.core.exceptions import SuspiciousOperation
  8. from django.utils.crypto import constant_time_compare
  9. from django.utils.crypto import get_random_string
  10. from django.utils.crypto import salted_hmac
  11. from django.utils import timezone
  12. from django.utils.encoding import force_bytes, force_text
  13. from django.utils.module_loading import import_string
  14. from django.contrib.sessions.exceptions import SuspiciousSession
  15. # session_key should not be case sensitive because some backends can store it
  16. # on case insensitive file systems.
  17. VALID_KEY_CHARS = string.ascii_lowercase + string.digits
  18. class CreateError(Exception):
  19. """
  20. Used internally as a consistent exception type to catch from save (see the
  21. docstring for SessionBase.save() for details).
  22. """
  23. pass
  24. class SessionBase(object):
  25. """
  26. Base class for all Session classes.
  27. """
  28. TEST_COOKIE_NAME = 'testcookie'
  29. TEST_COOKIE_VALUE = 'worked'
  30. def __init__(self, session_key=None):
  31. self._session_key = session_key
  32. self.accessed = False
  33. self.modified = False
  34. self.serializer = import_string(settings.SESSION_SERIALIZER)
  35. def __contains__(self, key):
  36. return key in self._session
  37. def __getitem__(self, key):
  38. return self._session[key]
  39. def __setitem__(self, key, value):
  40. self._session[key] = value
  41. self.modified = True
  42. def __delitem__(self, key):
  43. del self._session[key]
  44. self.modified = True
  45. def get(self, key, default=None):
  46. return self._session.get(key, default)
  47. def pop(self, key, *args):
  48. self.modified = self.modified or key in self._session
  49. return self._session.pop(key, *args)
  50. def setdefault(self, key, value):
  51. if key in self._session:
  52. return self._session[key]
  53. else:
  54. self.modified = True
  55. self._session[key] = value
  56. return value
  57. def set_test_cookie(self):
  58. self[self.TEST_COOKIE_NAME] = self.TEST_COOKIE_VALUE
  59. def test_cookie_worked(self):
  60. return self.get(self.TEST_COOKIE_NAME) == self.TEST_COOKIE_VALUE
  61. def delete_test_cookie(self):
  62. del self[self.TEST_COOKIE_NAME]
  63. def _hash(self, value):
  64. key_salt = "django.contrib.sessions" + self.__class__.__name__
  65. return salted_hmac(key_salt, value).hexdigest()
  66. def encode(self, session_dict):
  67. "Returns the given session dictionary serialized and encoded as a string."
  68. serialized = self.serializer().dumps(session_dict)
  69. hash = self._hash(serialized)
  70. return base64.b64encode(hash.encode() + b":" + serialized).decode('ascii')
  71. def decode(self, session_data):
  72. encoded_data = base64.b64decode(force_bytes(session_data))
  73. try:
  74. # could produce ValueError if there is no ':'
  75. hash, serialized = encoded_data.split(b':', 1)
  76. expected_hash = self._hash(serialized)
  77. if not constant_time_compare(hash.decode(), expected_hash):
  78. raise SuspiciousSession("Session data corrupted")
  79. else:
  80. return self.serializer().loads(serialized)
  81. except Exception as e:
  82. # ValueError, SuspiciousOperation, unpickling exceptions. If any of
  83. # these happen, just return an empty dictionary (an empty session).
  84. if isinstance(e, SuspiciousOperation):
  85. logger = logging.getLogger('django.security.%s' %
  86. e.__class__.__name__)
  87. logger.warning(force_text(e))
  88. return {}
  89. def update(self, dict_):
  90. self._session.update(dict_)
  91. self.modified = True
  92. def has_key(self, key):
  93. return key in self._session
  94. def keys(self):
  95. return self._session.keys()
  96. def values(self):
  97. return self._session.values()
  98. def items(self):
  99. return self._session.items()
  100. def iterkeys(self):
  101. return self._session.iterkeys()
  102. def itervalues(self):
  103. return self._session.itervalues()
  104. def iteritems(self):
  105. return self._session.iteritems()
  106. def clear(self):
  107. # To avoid unnecessary persistent storage accesses, we set up the
  108. # internals directly (loading data wastes time, since we are going to
  109. # set it to an empty dict anyway).
  110. self._session_cache = {}
  111. self.accessed = True
  112. self.modified = True
  113. def _get_new_session_key(self):
  114. "Returns session key that isn't being used."
  115. while True:
  116. session_key = get_random_string(32, VALID_KEY_CHARS)
  117. if not self.exists(session_key):
  118. break
  119. return session_key
  120. def _get_or_create_session_key(self):
  121. if self._session_key is None:
  122. self._session_key = self._get_new_session_key()
  123. return self._session_key
  124. def _get_session_key(self):
  125. return self._session_key
  126. session_key = property(_get_session_key)
  127. def _get_session(self, no_load=False):
  128. """
  129. Lazily loads session from storage (unless "no_load" is True, when only
  130. an empty dict is stored) and stores it in the current instance.
  131. """
  132. self.accessed = True
  133. try:
  134. return self._session_cache
  135. except AttributeError:
  136. if self.session_key is None or no_load:
  137. self._session_cache = {}
  138. else:
  139. self._session_cache = self.load()
  140. return self._session_cache
  141. _session = property(_get_session)
  142. def get_expiry_age(self, **kwargs):
  143. """Get the number of seconds until the session expires.
  144. Optionally, this function accepts `modification` and `expiry` keyword
  145. arguments specifying the modification and expiry of the session.
  146. """
  147. try:
  148. modification = kwargs['modification']
  149. except KeyError:
  150. modification = timezone.now()
  151. # Make the difference between "expiry=None passed in kwargs" and
  152. # "expiry not passed in kwargs", in order to guarantee not to trigger
  153. # self.load() when expiry is provided.
  154. try:
  155. expiry = kwargs['expiry']
  156. except KeyError:
  157. expiry = self.get('_session_expiry')
  158. if not expiry: # Checks both None and 0 cases
  159. return settings.SESSION_COOKIE_AGE
  160. if not isinstance(expiry, datetime):
  161. return expiry
  162. delta = expiry - modification
  163. return delta.days * 86400 + delta.seconds
  164. def get_expiry_date(self, **kwargs):
  165. """Get session the expiry date (as a datetime object).
  166. Optionally, this function accepts `modification` and `expiry` keyword
  167. arguments specifying the modification and expiry of the session.
  168. """
  169. try:
  170. modification = kwargs['modification']
  171. except KeyError:
  172. modification = timezone.now()
  173. # Same comment as in get_expiry_age
  174. try:
  175. expiry = kwargs['expiry']
  176. except KeyError:
  177. expiry = self.get('_session_expiry')
  178. if isinstance(expiry, datetime):
  179. return expiry
  180. if not expiry: # Checks both None and 0 cases
  181. expiry = settings.SESSION_COOKIE_AGE
  182. return modification + timedelta(seconds=expiry)
  183. def set_expiry(self, value):
  184. """
  185. Sets a custom expiration for the session. ``value`` can be an integer,
  186. a Python ``datetime`` or ``timedelta`` object or ``None``.
  187. If ``value`` is an integer, the session will expire after that many
  188. seconds of inactivity. If set to ``0`` then the session will expire on
  189. browser close.
  190. If ``value`` is a ``datetime`` or ``timedelta`` object, the session
  191. will expire at that specific future time.
  192. If ``value`` is ``None``, the session uses the global session expiry
  193. policy.
  194. """
  195. if value is None:
  196. # Remove any custom expiration for this session.
  197. try:
  198. del self['_session_expiry']
  199. except KeyError:
  200. pass
  201. return
  202. if isinstance(value, timedelta):
  203. value = timezone.now() + value
  204. self['_session_expiry'] = value
  205. def get_expire_at_browser_close(self):
  206. """
  207. Returns ``True`` if the session is set to expire when the browser
  208. closes, and ``False`` if there's an expiry date. Use
  209. ``get_expiry_date()`` or ``get_expiry_age()`` to find the actual expiry
  210. date/age, if there is one.
  211. """
  212. if self.get('_session_expiry') is None:
  213. return settings.SESSION_EXPIRE_AT_BROWSER_CLOSE
  214. return self.get('_session_expiry') == 0
  215. def flush(self):
  216. """
  217. Removes the current session data from the database and regenerates the
  218. key.
  219. """
  220. self.clear()
  221. self.delete()
  222. self.create()
  223. def cycle_key(self):
  224. """
  225. Creates a new session key, whilst retaining the current session data.
  226. """
  227. data = self._session_cache
  228. key = self.session_key
  229. self.create()
  230. self._session_cache = data
  231. self.delete(key)
  232. # Methods that child classes must implement.
  233. def exists(self, session_key):
  234. """
  235. Returns True if the given session_key already exists.
  236. """
  237. raise NotImplementedError('subclasses of SessionBase must provide an exists() method')
  238. def create(self):
  239. """
  240. Creates a new session instance. Guaranteed to create a new object with
  241. a unique key and will have saved the result once (with empty data)
  242. before the method returns.
  243. """
  244. raise NotImplementedError('subclasses of SessionBase must provide a create() method')
  245. def save(self, must_create=False):
  246. """
  247. Saves the session data. If 'must_create' is True, a new session object
  248. is created (otherwise a CreateError exception is raised). Otherwise,
  249. save() can update an existing object with the same key.
  250. """
  251. raise NotImplementedError('subclasses of SessionBase must provide a save() method')
  252. def delete(self, session_key=None):
  253. """
  254. Deletes the session data under this key. If the key is None, the
  255. current session key value is used.
  256. """
  257. raise NotImplementedError('subclasses of SessionBase must provide a delete() method')
  258. def load(self):
  259. """
  260. Loads the session data and returns a dictionary.
  261. """
  262. raise NotImplementedError('subclasses of SessionBase must provide a load() method')
  263. @classmethod
  264. def clear_expired(cls):
  265. """
  266. Remove expired sessions from the session store.
  267. If this operation isn't possible on a given backend, it should raise
  268. NotImplementedError. If it isn't necessary, because the backend has
  269. a built-in expiration mechanism, it should be a no-op.
  270. """
  271. raise NotImplementedError('This backend does not support clear_expired().')