PageRenderTime 46ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 0ms

/lib/werkzeug/contrib/sessions.py

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