session.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618
  1. import cPickle
  2. import Cookie
  3. import hmac
  4. import os
  5. import random
  6. import time
  7. from datetime import datetime, timedelta
  8. try:
  9. from hashlib import md5
  10. except ImportError:
  11. from md5 import md5
  12. try:
  13. # Use PyCrypto (if available)
  14. from Crypto.Hash import HMAC, SHA as SHA1
  15. except ImportError:
  16. # PyCrypto not available. Use the Python standard library.
  17. import hmac as HMAC
  18. import sys
  19. # When using the stdlib, we have to make sure the hmac version and sha
  20. # version are compatible
  21. if sys.version_info[0:2] <= (2,4):
  22. # hmac in python2.4 or less require the sha module
  23. import sha as SHA1
  24. else:
  25. # NOTE: We have to use the callable with hashlib (hashlib.sha1),
  26. # otherwise hmac only accepts the sha module object itself
  27. from hashlib import sha1 as SHA1
  28. # Check for pycryptopp encryption for AES
  29. try:
  30. from beaker.crypto import generateCryptoKeys, aesEncrypt
  31. crypto_ok = True
  32. except:
  33. crypto_ok = False
  34. from beaker.cache import clsmap
  35. from beaker.exceptions import BeakerException
  36. from beaker.util import b64decode, b64encode, Set
  37. __all__ = ['SignedCookie', 'Session']
  38. getpid = hasattr(os, 'getpid') and os.getpid or (lambda : '')
  39. class SignedCookie(Cookie.BaseCookie):
  40. """Extends python cookie to give digital signature support"""
  41. def __init__(self, secret, input=None):
  42. self.secret = secret
  43. Cookie.BaseCookie.__init__(self, input)
  44. def value_decode(self, val):
  45. val = val.strip('"')
  46. sig = HMAC.new(self.secret, val[40:], SHA1).hexdigest()
  47. if sig != val[:40]:
  48. return None, val
  49. else:
  50. return val[40:], val
  51. def value_encode(self, val):
  52. sig = HMAC.new(self.secret, val, SHA1).hexdigest()
  53. return str(val), ("%s%s" % (sig, val))
  54. class Session(dict):
  55. """Session object that uses container package for storage"""
  56. def __init__(self, request, id=None, invalidate_corrupt=False,
  57. use_cookies=True, type=None, data_dir=None,
  58. key='beaker.session.id', timeout=None, cookie_expires=True,
  59. cookie_domain=None, secret=None, secure=False,
  60. namespace_class=None, **namespace_args):
  61. if not type:
  62. if data_dir:
  63. self.type = 'file'
  64. else:
  65. self.type = 'memory'
  66. else:
  67. self.type = type
  68. self.namespace_class = namespace_class or clsmap[self.type]
  69. self.namespace_args = namespace_args
  70. self.request = request
  71. self.data_dir = data_dir
  72. self.key = key
  73. self.timeout = timeout
  74. self.use_cookies = use_cookies
  75. self.cookie_expires = cookie_expires
  76. # Default cookie domain/path
  77. self._domain = cookie_domain
  78. self._path = '/'
  79. self.was_invalidated = False
  80. self.secret = secret
  81. self.secure = secure
  82. self.id = id
  83. self.accessed_dict = {}
  84. if self.use_cookies:
  85. cookieheader = request.get('cookie', '')
  86. if secret:
  87. try:
  88. self.cookie = SignedCookie(secret, input=cookieheader)
  89. except Cookie.CookieError:
  90. self.cookie = SignedCookie(secret, input=None)
  91. else:
  92. self.cookie = Cookie.SimpleCookie(input=cookieheader)
  93. if not self.id and self.key in self.cookie:
  94. self.id = self.cookie[self.key].value
  95. self.is_new = self.id is None
  96. if self.is_new:
  97. self._create_id()
  98. self['_accessed_time'] = self['_creation_time'] = time.time()
  99. else:
  100. try:
  101. self.load()
  102. except:
  103. if invalidate_corrupt:
  104. self.invalidate()
  105. else:
  106. raise
  107. def _create_id(self):
  108. self.id = md5(
  109. md5("%f%s%f%s" % (time.time(), id({}), random.random(),
  110. getpid())).hexdigest(),
  111. ).hexdigest()
  112. self.is_new = True
  113. self.last_accessed = None
  114. if self.use_cookies:
  115. self.cookie[self.key] = self.id
  116. if self._domain:
  117. self.cookie[self.key]['domain'] = self._domain
  118. if self.secure:
  119. self.cookie[self.key]['secure'] = True
  120. self.cookie[self.key]['path'] = self._path
  121. if self.cookie_expires is not True:
  122. if self.cookie_expires is False:
  123. expires = datetime.fromtimestamp( 0x7FFFFFFF )
  124. elif isinstance(self.cookie_expires, timedelta):
  125. expires = datetime.today() + self.cookie_expires
  126. elif isinstance(self.cookie_expires, datetime):
  127. expires = self.cookie_expires
  128. else:
  129. raise ValueError("Invalid argument for cookie_expires: %s"
  130. % repr(self.cookie_expires))
  131. self.cookie[self.key]['expires'] = \
  132. expires.strftime("%a, %d-%b-%Y %H:%M:%S GMT" )
  133. self.request['cookie_out'] = self.cookie[self.key].output(header='')
  134. self.request['set_cookie'] = False
  135. def created(self):
  136. return self['_creation_time']
  137. created = property(created)
  138. def _set_domain(self, domain):
  139. self['_domain'] = domain
  140. self.cookie[self.key]['domain'] = domain
  141. self.request['cookie_out'] = self.cookie[self.key].output(header='')
  142. self.request['set_cookie'] = True
  143. def _get_domain(self, domain):
  144. return self._domain
  145. domain = property(_get_domain, _set_domain)
  146. def _set_path(self, path):
  147. self['_path'] = path
  148. self.cookie[self.key]['path'] = path
  149. self.request['cookie_out'] = self.cookie[self.key].output(header='')
  150. self.request['set_cookie'] = True
  151. def _get_path(self, domain):
  152. return self._path
  153. path = property(_get_path, _set_path)
  154. def _delete_cookie(self):
  155. self.request['set_cookie'] = True
  156. self.cookie[self.key] = self.id
  157. if self._domain:
  158. self.cookie[self.key]['domain'] = self._domain
  159. if self.secure:
  160. self.cookie[self.key]['secure'] = True
  161. self.cookie[self.key]['path'] = '/'
  162. expires = datetime.today().replace(year=2003)
  163. self.cookie[self.key]['expires'] = \
  164. expires.strftime("%a, %d-%b-%Y %H:%M:%S GMT" )
  165. self.request['cookie_out'] = self.cookie[self.key].output(header='')
  166. self.request['set_cookie'] = True
  167. def delete(self):
  168. """Deletes the session from the persistent storage, and sends
  169. an expired cookie out"""
  170. if self.use_cookies:
  171. self._delete_cookie()
  172. self.clear()
  173. def invalidate(self):
  174. """Invalidates this session, creates a new session id, returns
  175. to the is_new state"""
  176. self.clear()
  177. self.was_invalidated = True
  178. self._create_id()
  179. self.load()
  180. def load(self):
  181. "Loads the data from this session from persistent storage"
  182. self.namespace = self.namespace_class(self.id,
  183. data_dir=self.data_dir, digest_filenames=False,
  184. **self.namespace_args)
  185. now = time.time()
  186. self.request['set_cookie'] = True
  187. self.namespace.acquire_read_lock()
  188. timed_out = False
  189. try:
  190. self.clear()
  191. try:
  192. session_data = self.namespace['session']
  193. # Memcached always returns a key, its None when its not
  194. # present
  195. if session_data is None:
  196. session_data = {
  197. '_creation_time':now,
  198. '_accessed_time':now
  199. }
  200. self.is_new = True
  201. except (KeyError, TypeError):
  202. session_data = {
  203. '_creation_time':now,
  204. '_accessed_time':now
  205. }
  206. self.is_new = True
  207. if self.timeout is not None and \
  208. now - session_data['_accessed_time'] > self.timeout:
  209. timed_out= True
  210. else:
  211. # Properly set the last_accessed time, which is different
  212. # than the *currently* _accessed_time
  213. if self.is_new or '_accessed_time' not in session_data:
  214. self.last_accessed = None
  215. else:
  216. self.last_accessed = session_data['_accessed_time']
  217. # Update the current _accessed_time
  218. session_data['_accessed_time'] = now
  219. self.update(session_data)
  220. self.accessed_dict = session_data.copy()
  221. finally:
  222. self.namespace.release_read_lock()
  223. if timed_out:
  224. self.invalidate()
  225. def save(self, accessed_only=False):
  226. """Saves the data for this session to persistent storage
  227. If accessed_only is True, then only the original data loaded
  228. at the beginning of the request will be saved, with the updated
  229. last accessed time.
  230. """
  231. # Look to see if its a new session that was only accessed
  232. # Don't save it under that case
  233. if accessed_only and self.is_new:
  234. return None
  235. if not hasattr(self, 'namespace'):
  236. self.namespace = self.namespace_class(
  237. self.id,
  238. data_dir=self.data_dir,
  239. digest_filenames=False,
  240. **self.namespace_args)
  241. self.namespace.acquire_write_lock()
  242. try:
  243. if accessed_only:
  244. data = dict(self.accessed_dict.items())
  245. else:
  246. data = dict(self.items())
  247. # Save the data
  248. if not data and 'session' in self.namespace:
  249. del self.namespace['session']
  250. else:
  251. self.namespace['session'] = data
  252. finally:
  253. self.namespace.release_write_lock()
  254. if self.is_new:
  255. self.request['set_cookie'] = True
  256. def revert(self):
  257. """Revert the session to its original state from its first
  258. access in the request"""
  259. self.clear()
  260. self.update(self.accessed_dict)
  261. # TODO: I think both these methods should be removed. They're from
  262. # the original mod_python code i was ripping off but they really
  263. # have no use here.
  264. def lock(self):
  265. """Locks this session against other processes/threads. This is
  266. automatic when load/save is called.
  267. ***use with caution*** and always with a corresponding 'unlock'
  268. inside a "finally:" block, as a stray lock typically cannot be
  269. unlocked without shutting down the whole application.
  270. """
  271. self.namespace.acquire_write_lock()
  272. def unlock(self):
  273. """Unlocks this session against other processes/threads. This
  274. is automatic when load/save is called.
  275. ***use with caution*** and always within a "finally:" block, as
  276. a stray lock typically cannot be unlocked without shutting down
  277. the whole application.
  278. """
  279. self.namespace.release_write_lock()
  280. class CookieSession(Session):
  281. """Pure cookie-based session
  282. Options recognized when using cookie-based sessions are slightly
  283. more restricted than general sessions.
  284. ``key``
  285. The name the cookie should be set to.
  286. ``timeout``
  287. How long session data is considered valid. This is used
  288. regardless of the cookie being present or not to determine
  289. whether session data is still valid.
  290. ``encrypt_key``
  291. The key to use for the session encryption, if not provided the
  292. session will not be encrypted.
  293. ``validate_key``
  294. The key used to sign the encrypted session
  295. ``cookie_domain``
  296. Domain to use for the cookie.
  297. ``secure``
  298. Whether or not the cookie should only be sent over SSL.
  299. """
  300. def __init__(self, request, key='beaker.session.id', timeout=None,
  301. cookie_expires=True, cookie_domain=None, encrypt_key=None,
  302. validate_key=None, secure=False, **kwargs):
  303. if not crypto_ok and encrypt_key:
  304. raise BeakerException("pycryptopp is not installed, can't use "
  305. "encrypted cookie-only Session.")
  306. self.request = request
  307. self.key = key
  308. self.timeout = timeout
  309. self.cookie_expires = cookie_expires
  310. self.encrypt_key = encrypt_key
  311. self.validate_key = validate_key
  312. self.request['set_cookie'] = False
  313. self.secure = secure
  314. self._domain = cookie_domain
  315. self._path = '/'
  316. try:
  317. cookieheader = request['cookie']
  318. except KeyError:
  319. cookieheader = ''
  320. if validate_key is None:
  321. raise BeakerException("No validate_key specified for Cookie only "
  322. "Session.")
  323. try:
  324. self.cookie = SignedCookie(validate_key, input=cookieheader)
  325. except Cookie.CookieError:
  326. self.cookie = SignedCookie(validate_key, input=None)
  327. self['_id'] = self._make_id()
  328. self.is_new = True
  329. # If we have a cookie, load it
  330. if self.key in self.cookie and self.cookie[self.key].value is not None:
  331. self.is_new = False
  332. try:
  333. self.update(self._decrypt_data())
  334. except:
  335. pass
  336. if self.timeout is not None and time.time() - \
  337. self['_accessed_time'] > self.timeout:
  338. self.clear()
  339. self.accessed_dict = self.copy()
  340. self._create_cookie()
  341. def created(self):
  342. return self['_creation_time']
  343. created = property(created)
  344. def id(self):
  345. return self['_id']
  346. id = property(id)
  347. def _set_domain(self, domain):
  348. self['_domain'] = domain
  349. self._domain = domain
  350. def _get_domain(self, domain):
  351. return self._domain
  352. domain = property(_get_domain, _set_domain)
  353. def _set_path(self, path):
  354. self['_path'] = path
  355. self._path = path
  356. def _get_path(self, domain):
  357. return self._path
  358. path = property(_get_path, _set_path)
  359. def _encrypt_data(self):
  360. """Serialize, encipher, and base64 the session dict"""
  361. if self.encrypt_key:
  362. nonce = b64encode(os.urandom(40))[:8]
  363. encrypt_key = generateCryptoKeys(self.encrypt_key,
  364. self.validate_key + nonce, 1)
  365. data = cPickle.dumps(self.copy(), 2)
  366. return nonce + b64encode(aesEncrypt(data, encrypt_key))
  367. else:
  368. data = cPickle.dumps(self.copy(), 2)
  369. return b64encode(data)
  370. def _decrypt_data(self):
  371. """Bas64, decipher, then un-serialize the data for the session
  372. dict"""
  373. if self.encrypt_key:
  374. nonce = self.cookie[self.key].value[:8]
  375. encrypt_key = generateCryptoKeys(self.encrypt_key,
  376. self.validate_key + nonce, 1)
  377. payload = b64decode(self.cookie[self.key].value[8:])
  378. data = aesEncrypt(payload, encrypt_key)
  379. return cPickle.loads(data)
  380. else:
  381. data = b64decode(self.cookie[self.key].value)
  382. return cPickle.loads(data)
  383. def _make_id(self):
  384. return md5(md5(
  385. "%f%s%f%d" % (time.time(), id({}), random.random(), getpid())
  386. ).hexdigest()
  387. ).hexdigest()
  388. def save(self, accessed_only=False):
  389. """Saves the data for this session to persistent storage"""
  390. if accessed_only and self.is_new:
  391. return
  392. if accessed_only:
  393. self.clear()
  394. self.update(self.accessed_dict)
  395. self._create_cookie()
  396. def expire(self):
  397. """Delete the 'expires' attribute on this Session, if any."""
  398. self.pop('_expires', None)
  399. def _create_cookie(self):
  400. if '_creation_time' not in self:
  401. self['_creation_time'] = time.time()
  402. if '_id' not in self:
  403. self['_id'] = self._make_id()
  404. self['_accessed_time'] = time.time()
  405. if self.cookie_expires is not True:
  406. if self.cookie_expires is False:
  407. expires = datetime.fromtimestamp( 0x7FFFFFFF )
  408. elif isinstance(self.cookie_expires, timedelta):
  409. expires = datetime.today() + self.cookie_expires
  410. elif isinstance(self.cookie_expires, datetime):
  411. expires = self.cookie_expires
  412. else:
  413. raise ValueError("Invalid argument for cookie_expires: %s"
  414. % repr(self.cookie_expires))
  415. self['_expires'] = expires
  416. elif '_expires' in self:
  417. expires = self['_expires']
  418. else:
  419. expires = None
  420. val = self._encrypt_data()
  421. if len(val) > 4064:
  422. raise BeakerException("Cookie value is too long to store")
  423. self.cookie[self.key] = val
  424. if '_domain' in self:
  425. self.cookie[self.key]['domain'] = self['_domain']
  426. elif self._domain:
  427. self.cookie[self.key]['domain'] = self._domain
  428. if self.secure:
  429. self.cookie[self.key]['secure'] = True
  430. self.cookie[self.key]['path'] = self.get('_path', '/')
  431. if expires:
  432. self.cookie[self.key]['expires'] = \
  433. expires.strftime("%a, %d-%b-%Y %H:%M:%S GMT" )
  434. self.request['cookie_out'] = self.cookie[self.key].output(header='')
  435. self.request['set_cookie'] = True
  436. def delete(self):
  437. """Delete the cookie, and clear the session"""
  438. # Send a delete cookie request
  439. self._delete_cookie()
  440. self.clear()
  441. def invalidate(self):
  442. """Clear the contents and start a new session"""
  443. self.delete()
  444. self['_id'] = self._make_id()
  445. class SessionObject(object):
  446. """Session proxy/lazy creator
  447. This object proxies access to the actual session object, so that in
  448. the case that the session hasn't been used before, it will be
  449. setup. This avoid creating and loading the session from persistent
  450. storage unless its actually used during the request.
  451. """
  452. def __init__(self, environ, **params):
  453. self.__dict__['_params'] = params
  454. self.__dict__['_environ'] = environ
  455. self.__dict__['_sess'] = None
  456. self.__dict__['_headers'] = []
  457. def _session(self):
  458. """Lazy initial creation of session object"""
  459. if self.__dict__['_sess'] is None:
  460. params = self.__dict__['_params']
  461. environ = self.__dict__['_environ']
  462. self.__dict__['_headers'] = req = {'cookie_out':None}
  463. req['cookie'] = environ.get('HTTP_COOKIE')
  464. if params.get('type') == 'cookie':
  465. self.__dict__['_sess'] = CookieSession(req, **params)
  466. else:
  467. self.__dict__['_sess'] = Session(req, use_cookies=True,
  468. **params)
  469. return self.__dict__['_sess']
  470. def __getattr__(self, attr):
  471. return getattr(self._session(), attr)
  472. def __setattr__(self, attr, value):
  473. setattr(self._session(), attr, value)
  474. def __delattr__(self, name):
  475. self._session().__delattr__(name)
  476. def __getitem__(self, key):
  477. return self._session()[key]
  478. def __setitem__(self, key, value):
  479. self._session()[key] = value
  480. def __delitem__(self, key):
  481. self._session().__delitem__(key)
  482. def __repr__(self):
  483. return self._session().__repr__()
  484. def __iter__(self):
  485. """Only works for proxying to a dict"""
  486. return iter(self._session().keys())
  487. def __contains__(self, key):
  488. return self._session().has_key(key)
  489. def get_by_id(self, id):
  490. params = self.__dict__['_params']
  491. session = Session({}, use_cookies=False, id=id, **params)
  492. if session.is_new:
  493. return None
  494. return session
  495. def save(self):
  496. self.__dict__['_dirty'] = True
  497. def delete(self):
  498. self.__dict__['_dirty'] = True
  499. self._session().delete()
  500. def persist(self):
  501. """Persist the session to the storage
  502. If its set to autosave, then the entire session will be saved
  503. regardless of if save() has been called. Otherwise, just the
  504. accessed time will be updated if save() was not called, or
  505. the session will be saved if save() was called.
  506. """
  507. if self.__dict__['_params'].get('auto'):
  508. self._session().save()
  509. else:
  510. if self.__dict__.get('_dirty'):
  511. self._session().save()
  512. else:
  513. self._session().save(accessed_only=True)
  514. def dirty(self):
  515. return self.__dict__.get('_dirty', False)
  516. def accessed(self):
  517. return self.__dict__['_sess'] is not None