PageRenderTime 45ms CodeModel.GetById 13ms RepoModel.GetById 0ms app.codeStats 0ms

/venv/lib/python2.7/site-packages/werkzeug/contrib/sessions.py

https://gitlab.com/ismailam/openexport
Python | 352 lines | 320 code | 3 blank | 29 comment | 12 complexity | 89cfa438fc2516bdff93ddf4229686eb MD5 | raw file
  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. It 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: (c) 2014 by the Werkzeug Team, see AUTHORS for more details.
  40. :license: BSD, see LICENSE for more details.
  41. """
  42. import re
  43. import os
  44. import tempfile
  45. from os import path
  46. from time import time
  47. from random import random
  48. from hashlib import sha1
  49. from pickle import dump, load, HIGHEST_PROTOCOL
  50. from werkzeug.datastructures import CallbackDict
  51. from werkzeug.utils import dump_cookie, parse_cookie
  52. from werkzeug.wsgi import ClosingIterator
  53. from werkzeug.posixemulation import rename
  54. from werkzeug._compat import PY2, text_type
  55. from werkzeug.filesystem import get_filesystem_encoding
  56. _sha1_re = re.compile(r'^[a-f0-9]{40}$')
  57. def _urandom():
  58. if hasattr(os, 'urandom'):
  59. return os.urandom(30)
  60. return text_type(random()).encode('ascii')
  61. def generate_key(salt=None):
  62. if salt is None:
  63. salt = repr(salt).encode('ascii')
  64. return sha1(b''.join([
  65. salt,
  66. str(time()).encode('ascii'),
  67. _urandom()
  68. ])).hexdigest()
  69. class ModificationTrackingDict(CallbackDict):
  70. __slots__ = ('modified',)
  71. def __init__(self, *args, **kwargs):
  72. def on_update(self):
  73. self.modified = True
  74. self.modified = False
  75. CallbackDict.__init__(self, on_update=on_update)
  76. dict.update(self, *args, **kwargs)
  77. def copy(self):
  78. """Create a flat copy of the dict."""
  79. missing = object()
  80. result = object.__new__(self.__class__)
  81. for name in self.__slots__:
  82. val = getattr(self, name, missing)
  83. if val is not missing:
  84. setattr(result, name, val)
  85. return result
  86. def __copy__(self):
  87. return self.copy()
  88. class Session(ModificationTrackingDict):
  89. """Subclass of a dict that keeps track of direct object changes. Changes
  90. in mutable structures are not tracked, for those you have to set
  91. `modified` to `True` by hand.
  92. """
  93. __slots__ = ModificationTrackingDict.__slots__ + ('sid', 'new')
  94. def __init__(self, data, sid, new=False):
  95. ModificationTrackingDict.__init__(self, data)
  96. self.sid = sid
  97. self.new = new
  98. def __repr__(self):
  99. return '<%s %s%s>' % (
  100. self.__class__.__name__,
  101. dict.__repr__(self),
  102. self.should_save and '*' or ''
  103. )
  104. @property
  105. def should_save(self):
  106. """True if the session should be saved.
  107. .. versionchanged:: 0.6
  108. By default the session is now only saved if the session is
  109. modified, not if it is new like it was before.
  110. """
  111. return self.modified
  112. class SessionStore(object):
  113. """Baseclass for all session stores. The Werkzeug contrib module does not
  114. implement any useful stores besides the filesystem store, application
  115. developers are encouraged to create their own stores.
  116. :param session_class: The session class to use. Defaults to
  117. :class:`Session`.
  118. """
  119. def __init__(self, session_class=None):
  120. if session_class is None:
  121. session_class = Session
  122. self.session_class = session_class
  123. def is_valid_key(self, key):
  124. """Check if a key has the correct format."""
  125. return _sha1_re.match(key) is not None
  126. def generate_key(self, salt=None):
  127. """Simple function that generates a new session key."""
  128. return generate_key(salt)
  129. def new(self):
  130. """Generate a new session."""
  131. return self.session_class({}, self.generate_key(), True)
  132. def save(self, session):
  133. """Save a session."""
  134. def save_if_modified(self, session):
  135. """Save if a session class wants an update."""
  136. if session.should_save:
  137. self.save(session)
  138. def delete(self, session):
  139. """Delete a session."""
  140. def get(self, sid):
  141. """Get a session for this sid or a new session object. This method
  142. has to check if the session key is valid and create a new session if
  143. that wasn't the case.
  144. """
  145. return self.session_class({}, sid, True)
  146. #: used for temporary files by the filesystem session store
  147. _fs_transaction_suffix = '.__wz_sess'
  148. class FilesystemSessionStore(SessionStore):
  149. """Simple example session store that saves sessions on the filesystem.
  150. This store works best on POSIX systems and Windows Vista / Windows
  151. Server 2008 and newer.
  152. .. versionchanged:: 0.6
  153. `renew_missing` was added. Previously this was considered `True`,
  154. now the default changed to `False` and it can be explicitly
  155. deactivated.
  156. :param path: the path to the folder used for storing the sessions.
  157. If not provided the default temporary directory is used.
  158. :param filename_template: a string template used to give the session
  159. a filename. ``%s`` is replaced with the
  160. session id.
  161. :param session_class: The session class to use. Defaults to
  162. :class:`Session`.
  163. :param renew_missing: set to `True` if you want the store to
  164. give the user a new sid if the session was
  165. not yet saved.
  166. """
  167. def __init__(self, path=None, filename_template='werkzeug_%s.sess',
  168. session_class=None, renew_missing=False, mode=0o644):
  169. SessionStore.__init__(self, session_class)
  170. if path is None:
  171. path = tempfile.gettempdir()
  172. self.path = path
  173. if isinstance(filename_template, text_type) and PY2:
  174. filename_template = filename_template.encode(
  175. get_filesystem_encoding())
  176. assert not filename_template.endswith(_fs_transaction_suffix), \
  177. 'filename templates may not end with %s' % _fs_transaction_suffix
  178. self.filename_template = filename_template
  179. self.renew_missing = renew_missing
  180. self.mode = mode
  181. def get_session_filename(self, sid):
  182. # out of the box, this should be a strict ASCII subset but
  183. # you might reconfigure the session object to have a more
  184. # arbitrary string.
  185. if isinstance(sid, text_type) and PY2:
  186. sid = sid.encode(get_filesystem_encoding())
  187. return path.join(self.path, self.filename_template % sid)
  188. def save(self, session):
  189. fn = self.get_session_filename(session.sid)
  190. fd, tmp = tempfile.mkstemp(suffix=_fs_transaction_suffix,
  191. dir=self.path)
  192. f = os.fdopen(fd, 'wb')
  193. try:
  194. dump(dict(session), f, HIGHEST_PROTOCOL)
  195. finally:
  196. f.close()
  197. try:
  198. rename(tmp, fn)
  199. os.chmod(fn, self.mode)
  200. except (IOError, OSError):
  201. pass
  202. def delete(self, session):
  203. fn = self.get_session_filename(session.sid)
  204. try:
  205. os.unlink(fn)
  206. except OSError:
  207. pass
  208. def get(self, sid):
  209. if not self.is_valid_key(sid):
  210. return self.new()
  211. try:
  212. f = open(self.get_session_filename(sid), 'rb')
  213. except IOError:
  214. if self.renew_missing:
  215. return self.new()
  216. data = {}
  217. else:
  218. try:
  219. try:
  220. data = load(f)
  221. except Exception:
  222. data = {}
  223. finally:
  224. f.close()
  225. return self.session_class(data, sid, False)
  226. def list(self):
  227. """Lists all sessions in the store.
  228. .. versionadded:: 0.6
  229. """
  230. before, after = self.filename_template.split('%s', 1)
  231. filename_re = re.compile(r'%s(.{5,})%s$' % (re.escape(before),
  232. re.escape(after)))
  233. result = []
  234. for filename in os.listdir(self.path):
  235. #: this is a session that is still being saved.
  236. if filename.endswith(_fs_transaction_suffix):
  237. continue
  238. match = filename_re.match(filename)
  239. if match is not None:
  240. result.append(match.group(1))
  241. return result
  242. class SessionMiddleware(object):
  243. """A simple middleware that puts the session object of a store provided
  244. into the WSGI environ. It automatically sets cookies and restores
  245. sessions.
  246. However a middleware is not the preferred solution because it won't be as
  247. fast as sessions managed by the application itself and will put a key into
  248. the WSGI environment only relevant for the application which is against
  249. the concept of WSGI.
  250. The cookie parameters are the same as for the :func:`~dump_cookie`
  251. function just prefixed with ``cookie_``. Additionally `max_age` is
  252. called `cookie_age` and not `cookie_max_age` because of backwards
  253. compatibility.
  254. """
  255. def __init__(self, app, store, cookie_name='session_id',
  256. cookie_age=None, cookie_expires=None, cookie_path='/',
  257. cookie_domain=None, cookie_secure=None,
  258. cookie_httponly=False, environ_key='werkzeug.session'):
  259. self.app = app
  260. self.store = store
  261. self.cookie_name = cookie_name
  262. self.cookie_age = cookie_age
  263. self.cookie_expires = cookie_expires
  264. self.cookie_path = cookie_path
  265. self.cookie_domain = cookie_domain
  266. self.cookie_secure = cookie_secure
  267. self.cookie_httponly = cookie_httponly
  268. self.environ_key = environ_key
  269. def __call__(self, environ, start_response):
  270. cookie = parse_cookie(environ.get('HTTP_COOKIE', ''))
  271. sid = cookie.get(self.cookie_name, None)
  272. if sid is None:
  273. session = self.store.new()
  274. else:
  275. session = self.store.get(sid)
  276. environ[self.environ_key] = session
  277. def injecting_start_response(status, headers, exc_info=None):
  278. if session.should_save:
  279. self.store.save(session)
  280. headers.append(('Set-Cookie', dump_cookie(self.cookie_name,
  281. session.sid, self.cookie_age,
  282. self.cookie_expires, self.cookie_path,
  283. self.cookie_domain, self.cookie_secure,
  284. self.cookie_httponly)))
  285. return start_response(status, headers, exc_info)
  286. return ClosingIterator(self.app(environ, injecting_start_response),
  287. lambda: self.store.save_if_modified(session))