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.

sessions.py 13KB

5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389
  1. # -*- coding: utf-8 -*-
  2. r"""
  3. werkzeug.contrib.sessions
  4. ~~~~~~~~~~~~~~~~~~~~~~~~~
  5. This module contains some helper classes that help one to add session
  6. support to a python WSGI application. For full client-side session
  7. storage see :mod:`~werkzeug.contrib.securecookie` which implements a
  8. secure, client-side session storage.
  9. Application Integration
  10. =======================
  11. ::
  12. from werkzeug.contrib.sessions import SessionMiddleware, \
  13. FilesystemSessionStore
  14. app = SessionMiddleware(app, FilesystemSessionStore())
  15. The current session will then appear in the WSGI environment as
  16. `werkzeug.session`. However it's recommended to not use the middleware
  17. but the stores directly in the application. However for very simple
  18. scripts a middleware for sessions could be sufficient.
  19. This module does not implement methods or ways to check if a session is
  20. expired. That should be done by a cronjob and storage specific. For
  21. example to prune unused filesystem sessions one could check the modified
  22. time of the files. If sessions are stored in the database the new()
  23. method should add an expiration timestamp for the session.
  24. For better flexibility it's recommended to not use the middleware but the
  25. store and session object directly in the application dispatching::
  26. session_store = FilesystemSessionStore()
  27. def application(environ, start_response):
  28. request = Request(environ)
  29. sid = request.cookies.get('cookie_name')
  30. if sid is None:
  31. request.session = session_store.new()
  32. else:
  33. request.session = session_store.get(sid)
  34. response = get_the_response_object(request)
  35. if request.session.should_save:
  36. session_store.save(request.session)
  37. response.set_cookie('cookie_name', request.session.sid)
  38. return response(environ, start_response)
  39. :copyright: 2007 Pallets
  40. :license: BSD-3-Clause
  41. """
  42. import os
  43. import re
  44. import tempfile
  45. import warnings
  46. from hashlib import sha1
  47. from os import path
  48. from pickle import dump
  49. from pickle import HIGHEST_PROTOCOL
  50. from pickle import load
  51. from random import random
  52. from time import time
  53. from .._compat import PY2
  54. from .._compat import text_type
  55. from ..datastructures import CallbackDict
  56. from ..filesystem import get_filesystem_encoding
  57. from ..http import dump_cookie
  58. from ..http import parse_cookie
  59. from ..posixemulation import rename
  60. from ..wsgi import ClosingIterator
  61. warnings.warn(
  62. "'werkzeug.contrib.sessions' is deprecated as of version 0.15 and"
  63. " will be removed in version 1.0. It has moved to"
  64. " https://github.com/pallets/secure-cookie.",
  65. DeprecationWarning,
  66. stacklevel=2,
  67. )
  68. _sha1_re = re.compile(r"^[a-f0-9]{40}$")
  69. def _urandom():
  70. if hasattr(os, "urandom"):
  71. return os.urandom(30)
  72. return text_type(random()).encode("ascii")
  73. def generate_key(salt=None):
  74. if salt is None:
  75. salt = repr(salt).encode("ascii")
  76. return sha1(b"".join([salt, str(time()).encode("ascii"), _urandom()])).hexdigest()
  77. class ModificationTrackingDict(CallbackDict):
  78. __slots__ = ("modified",)
  79. def __init__(self, *args, **kwargs):
  80. def on_update(self):
  81. self.modified = True
  82. self.modified = False
  83. CallbackDict.__init__(self, on_update=on_update)
  84. dict.update(self, *args, **kwargs)
  85. def copy(self):
  86. """Create a flat copy of the dict."""
  87. missing = object()
  88. result = object.__new__(self.__class__)
  89. for name in self.__slots__:
  90. val = getattr(self, name, missing)
  91. if val is not missing:
  92. setattr(result, name, val)
  93. return result
  94. def __copy__(self):
  95. return self.copy()
  96. class Session(ModificationTrackingDict):
  97. """Subclass of a dict that keeps track of direct object changes. Changes
  98. in mutable structures are not tracked, for those you have to set
  99. `modified` to `True` by hand.
  100. """
  101. __slots__ = ModificationTrackingDict.__slots__ + ("sid", "new")
  102. def __init__(self, data, sid, new=False):
  103. ModificationTrackingDict.__init__(self, data)
  104. self.sid = sid
  105. self.new = new
  106. def __repr__(self):
  107. return "<%s %s%s>" % (
  108. self.__class__.__name__,
  109. dict.__repr__(self),
  110. "*" if self.should_save else "",
  111. )
  112. @property
  113. def should_save(self):
  114. """True if the session should be saved.
  115. .. versionchanged:: 0.6
  116. By default the session is now only saved if the session is
  117. modified, not if it is new like it was before.
  118. """
  119. return self.modified
  120. class SessionStore(object):
  121. """Baseclass for all session stores. The Werkzeug contrib module does not
  122. implement any useful stores besides the filesystem store, application
  123. developers are encouraged to create their own stores.
  124. :param session_class: The session class to use. Defaults to
  125. :class:`Session`.
  126. """
  127. def __init__(self, session_class=None):
  128. if session_class is None:
  129. session_class = Session
  130. self.session_class = session_class
  131. def is_valid_key(self, key):
  132. """Check if a key has the correct format."""
  133. return _sha1_re.match(key) is not None
  134. def generate_key(self, salt=None):
  135. """Simple function that generates a new session key."""
  136. return generate_key(salt)
  137. def new(self):
  138. """Generate a new session."""
  139. return self.session_class({}, self.generate_key(), True)
  140. def save(self, session):
  141. """Save a session."""
  142. def save_if_modified(self, session):
  143. """Save if a session class wants an update."""
  144. if session.should_save:
  145. self.save(session)
  146. def delete(self, session):
  147. """Delete a session."""
  148. def get(self, sid):
  149. """Get a session for this sid or a new session object. This method
  150. has to check if the session key is valid and create a new session if
  151. that wasn't the case.
  152. """
  153. return self.session_class({}, sid, True)
  154. #: used for temporary files by the filesystem session store
  155. _fs_transaction_suffix = ".__wz_sess"
  156. class FilesystemSessionStore(SessionStore):
  157. """Simple example session store that saves sessions on the filesystem.
  158. This store works best on POSIX systems and Windows Vista / Windows
  159. Server 2008 and newer.
  160. .. versionchanged:: 0.6
  161. `renew_missing` was added. Previously this was considered `True`,
  162. now the default changed to `False` and it can be explicitly
  163. deactivated.
  164. :param path: the path to the folder used for storing the sessions.
  165. If not provided the default temporary directory is used.
  166. :param filename_template: a string template used to give the session
  167. a filename. ``%s`` is replaced with the
  168. session id.
  169. :param session_class: The session class to use. Defaults to
  170. :class:`Session`.
  171. :param renew_missing: set to `True` if you want the store to
  172. give the user a new sid if the session was
  173. not yet saved.
  174. """
  175. def __init__(
  176. self,
  177. path=None,
  178. filename_template="werkzeug_%s.sess",
  179. session_class=None,
  180. renew_missing=False,
  181. mode=0o644,
  182. ):
  183. SessionStore.__init__(self, session_class)
  184. if path is None:
  185. path = tempfile.gettempdir()
  186. self.path = path
  187. if isinstance(filename_template, text_type) and PY2:
  188. filename_template = filename_template.encode(get_filesystem_encoding())
  189. assert not filename_template.endswith(_fs_transaction_suffix), (
  190. "filename templates may not end with %s" % _fs_transaction_suffix
  191. )
  192. self.filename_template = filename_template
  193. self.renew_missing = renew_missing
  194. self.mode = mode
  195. def get_session_filename(self, sid):
  196. # out of the box, this should be a strict ASCII subset but
  197. # you might reconfigure the session object to have a more
  198. # arbitrary string.
  199. if isinstance(sid, text_type) and PY2:
  200. sid = sid.encode(get_filesystem_encoding())
  201. return path.join(self.path, self.filename_template % sid)
  202. def save(self, session):
  203. fn = self.get_session_filename(session.sid)
  204. fd, tmp = tempfile.mkstemp(suffix=_fs_transaction_suffix, dir=self.path)
  205. f = os.fdopen(fd, "wb")
  206. try:
  207. dump(dict(session), f, HIGHEST_PROTOCOL)
  208. finally:
  209. f.close()
  210. try:
  211. rename(tmp, fn)
  212. os.chmod(fn, self.mode)
  213. except (IOError, OSError):
  214. pass
  215. def delete(self, session):
  216. fn = self.get_session_filename(session.sid)
  217. try:
  218. os.unlink(fn)
  219. except OSError:
  220. pass
  221. def get(self, sid):
  222. if not self.is_valid_key(sid):
  223. return self.new()
  224. try:
  225. f = open(self.get_session_filename(sid), "rb")
  226. except IOError:
  227. if self.renew_missing:
  228. return self.new()
  229. data = {}
  230. else:
  231. try:
  232. try:
  233. data = load(f)
  234. except Exception:
  235. data = {}
  236. finally:
  237. f.close()
  238. return self.session_class(data, sid, False)
  239. def list(self):
  240. """Lists all sessions in the store.
  241. .. versionadded:: 0.6
  242. """
  243. before, after = self.filename_template.split("%s", 1)
  244. filename_re = re.compile(
  245. r"%s(.{5,})%s$" % (re.escape(before), re.escape(after))
  246. )
  247. result = []
  248. for filename in os.listdir(self.path):
  249. #: this is a session that is still being saved.
  250. if filename.endswith(_fs_transaction_suffix):
  251. continue
  252. match = filename_re.match(filename)
  253. if match is not None:
  254. result.append(match.group(1))
  255. return result
  256. class SessionMiddleware(object):
  257. """A simple middleware that puts the session object of a store provided
  258. into the WSGI environ. It automatically sets cookies and restores
  259. sessions.
  260. However a middleware is not the preferred solution because it won't be as
  261. fast as sessions managed by the application itself and will put a key into
  262. the WSGI environment only relevant for the application which is against
  263. the concept of WSGI.
  264. The cookie parameters are the same as for the :func:`~dump_cookie`
  265. function just prefixed with ``cookie_``. Additionally `max_age` is
  266. called `cookie_age` and not `cookie_max_age` because of backwards
  267. compatibility.
  268. """
  269. def __init__(
  270. self,
  271. app,
  272. store,
  273. cookie_name="session_id",
  274. cookie_age=None,
  275. cookie_expires=None,
  276. cookie_path="/",
  277. cookie_domain=None,
  278. cookie_secure=None,
  279. cookie_httponly=False,
  280. cookie_samesite="Lax",
  281. environ_key="werkzeug.session",
  282. ):
  283. self.app = app
  284. self.store = store
  285. self.cookie_name = cookie_name
  286. self.cookie_age = cookie_age
  287. self.cookie_expires = cookie_expires
  288. self.cookie_path = cookie_path
  289. self.cookie_domain = cookie_domain
  290. self.cookie_secure = cookie_secure
  291. self.cookie_httponly = cookie_httponly
  292. self.cookie_samesite = cookie_samesite
  293. self.environ_key = environ_key
  294. def __call__(self, environ, start_response):
  295. cookie = parse_cookie(environ.get("HTTP_COOKIE", ""))
  296. sid = cookie.get(self.cookie_name, None)
  297. if sid is None:
  298. session = self.store.new()
  299. else:
  300. session = self.store.get(sid)
  301. environ[self.environ_key] = session
  302. def injecting_start_response(status, headers, exc_info=None):
  303. if session.should_save:
  304. self.store.save(session)
  305. headers.append(
  306. (
  307. "Set-Cookie",
  308. dump_cookie(
  309. self.cookie_name,
  310. session.sid,
  311. self.cookie_age,
  312. self.cookie_expires,
  313. self.cookie_path,
  314. self.cookie_domain,
  315. self.cookie_secure,
  316. self.cookie_httponly,
  317. samesite=self.cookie_samesite,
  318. ),
  319. )
  320. )
  321. return start_response(status, headers, exc_info)
  322. return ClosingIterator(
  323. self.app(environ, injecting_start_response),
  324. lambda: self.store.save_if_modified(session),
  325. )