2007-10-30 07:55:08 +08:00
|
|
|
import time
|
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
from django.conf import settings
|
2005-10-09 08:55:08 +08:00
|
|
|
from django.utils.cache import patch_vary_headers
|
2007-10-31 11:59:40 +08:00
|
|
|
from django.utils.http import cookie_date
|
2009-03-19 00:55:59 +08:00
|
|
|
from django.utils.importlib import import_module
|
2005-08-17 06:54:05 +08:00
|
|
|
|
2006-06-08 13:00:13 +08:00
|
|
|
class SessionMiddleware(object):
|
2005-08-23 03:19:54 +08:00
|
|
|
def process_request(self, request):
|
2009-03-19 00:55:59 +08:00
|
|
|
engine = import_module(settings.SESSION_ENGINE)
|
2007-10-30 07:55:08 +08:00
|
|
|
session_key = request.COOKIES.get(settings.SESSION_COOKIE_NAME, None)
|
|
|
|
request.session = engine.SessionStore(session_key)
|
2005-08-17 06:54:05 +08:00
|
|
|
|
|
|
|
def process_response(self, request, response):
|
2008-09-17 16:10:55 +08:00
|
|
|
"""
|
|
|
|
If request.session was modified, or if the configuration is to save the
|
|
|
|
session every time, save the changes and set a session cookie.
|
|
|
|
"""
|
2005-08-17 06:54:05 +08:00
|
|
|
try:
|
2007-03-08 16:46:59 +08:00
|
|
|
accessed = request.session.accessed
|
2005-08-17 06:54:05 +08:00
|
|
|
modified = request.session.modified
|
|
|
|
except AttributeError:
|
2006-01-15 14:18:03 +08:00
|
|
|
pass
|
|
|
|
else:
|
2007-03-08 16:46:59 +08:00
|
|
|
if accessed:
|
|
|
|
patch_vary_headers(response, ('Cookie',))
|
2006-05-02 09:31:56 +08:00
|
|
|
if modified or settings.SESSION_SAVE_EVERY_REQUEST:
|
2008-06-08 04:28:06 +08:00
|
|
|
if request.session.get_expire_at_browser_close():
|
2006-06-02 06:25:06 +08:00
|
|
|
max_age = None
|
|
|
|
expires = None
|
|
|
|
else:
|
2008-06-08 04:28:06 +08:00
|
|
|
max_age = request.session.get_expiry_age()
|
|
|
|
expires_time = time.time() + max_age
|
2007-10-31 11:59:40 +08:00
|
|
|
expires = cookie_date(expires_time)
|
2008-06-08 04:28:06 +08:00
|
|
|
# Save the session data and refresh the client cookie.
|
2007-09-16 05:29:14 +08:00
|
|
|
request.session.save()
|
2007-10-20 13:13:56 +08:00
|
|
|
response.set_cookie(settings.SESSION_COOKIE_NAME,
|
|
|
|
request.session.session_key, max_age=max_age,
|
|
|
|
expires=expires, domain=settings.SESSION_COOKIE_DOMAIN,
|
|
|
|
path=settings.SESSION_COOKIE_PATH,
|
2010-11-26 21:30:50 +08:00
|
|
|
secure=settings.SESSION_COOKIE_SECURE or None,
|
|
|
|
httponly=settings.SESSION_COOKIE_HTTPONLY or None)
|
2005-08-17 06:54:05 +08:00
|
|
|
return response
|