session.py 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. from bottle import request, response
  2. from freepost import database, random, settings
  3. # Start a new session
  4. def start (user_id, remember = False):
  5. # Create a new token for this session.
  6. # The random token is stored as a user cookie, and its hash value is
  7. # stored in the database to match the current user for the future requests.
  8. session_token = random.ascii_string (64)
  9. # Create session cookie
  10. response.set_cookie (
  11. name = settings['session']['name'],
  12. value = session_token,
  13. secret = settings['cookies']['secret'],
  14. path = '/',
  15. # When to end the session
  16. max_age = settings['session']['remember_me'] if remember else None,
  17. # HTTPS only
  18. secure = False,
  19. # Do not allow JavaScript to read this cookie
  20. httponly = True)
  21. # Store session to database
  22. database.new_session (user_id, session_token)
  23. # Close the current open session
  24. def close ():
  25. session_user = user ()
  26. # Delete user cookie containing session token
  27. response.delete_cookie (settings['session']['name'])
  28. # Delete session token from database
  29. database.delete_session (session_user['id'])
  30. # Retrieve user from session token
  31. def user ():
  32. session_token = request.get_cookie (
  33. key = settings['session']['name'],
  34. secret = settings['cookies']['secret'])
  35. if session_token is None:
  36. return None
  37. return database.get_user_by_session_token (session_token)