説明なし
選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. # -*- coding: utf-8 -*-
  2. import os
  3. import datetime
  4. from werkzeug.contrib.sessions import FilesystemSessionStore
  5. from Modules.Interface.web.router import get_controller
  6. from Modules.Interface.web.LodelRequest import LodelRequest
  7. # TODO Déplacer ces trois paramètres dans les settings
  8. SESSION_FILES_TEMPLATE = 'lodel_%s.sess'
  9. SESSION_FILES_BASE_DIR = 'tmp/sessions'
  10. SESSION_EXPIRATION_LIMIT = 900 # 15 mn
  11. session_store = FilesystemSessionStore(path=SESSION_FILES_BASE_DIR, filename_template=SESSION_FILES_TEMPLATE)
  12. # TODO déplacer cette méthode dans un module Lodel/utils/datetime.py
  13. def get_utc_timestamp():
  14. d = datetime.datetime.utcnow()
  15. epoch = datetime.datetime(1970, 1, 1)
  16. t = (d - epoch).total_seconds()
  17. return t
  18. # TODO déplacer dans un module "sessions.py"
  19. def delete_old_session_files(timestamp_now):
  20. session_files_path = os.path.abspath(session_store.path)
  21. session_files = [f for f in os.listdir(session_files_path) if os.path.isfile(os.path.join(session_files_path, f))]
  22. for session_file in session_files:
  23. expiration_timestamp = os.stat(os.path.join(session_files_path, session_file)).st_mtime + \
  24. SESSION_EXPIRATION_LIMIT
  25. if timestamp_now > expiration_timestamp:
  26. os.unlink(os.path.join(session_files_path, session_file))
  27. # TODO déplacer dans un module "sessions.py"
  28. def is_session_file_expired(timestamp_now, sid):
  29. session_file = session_store.get_session_filename(sid)
  30. expiration_timestamp = os.stat(session_file).st_mtime + SESSION_EXPIRATION_LIMIT
  31. if timestamp_now < expiration_timestamp:
  32. return False
  33. return True
  34. # WSGI Application
  35. def application(env, start_response):
  36. current_timestamp = get_utc_timestamp()
  37. delete_old_session_files(current_timestamp)
  38. request = LodelRequest(env)
  39. sid = request.cookies.get('sid')
  40. if sid is None or sid not in session_store.list():
  41. request.session = session_store.new()
  42. request.session['last_accessed'] = current_timestamp
  43. else:
  44. request.session = session_store.get(sid)
  45. if is_session_file_expired(current_timestamp, sid):
  46. session_store.delete(request.session)
  47. request.session = session_store.new()
  48. request.session['user_context'] = None
  49. request.session['last_accessed'] = current_timestamp
  50. controller = get_controller(request)
  51. response = controller(request)
  52. if request.session.should_save:
  53. session_store.save(request.session)
  54. response.set_cookie('sid', request.session.sid)
  55. return response(env, start_response)