I noticed that the SessionsMiddleware class was setting a cookie with an explicit expiration date. So I created this modified middleware for my application that allows SESSION_COOKIE_AGE to be set to None (which then creates a session cookie with no expiration date, meaning the cookie will be deleted when the browser session ends).
Currently the middleware sets the session expiration date in the database to 1 hour from when the session cookie is set, but this could be changed with a configuration variable (SESSION_EXPIRATION_AGE, perhaps?).
from django.middleware import sessions as sessionsMiddleware
from django.conf.settings import SESSION_COOKIE_NAME, SESSION_COOKIE_AGE, SESSION_COOKIE_DOMAIN
from django.models.core import sessions
import datetime
class SingleSessionMiddleware(sessionsMiddleware.SessionMiddleware):
def process_response(self, request, response):
try:
modified = request.session.modified
except AttributeError:
modified = False
if modified:
session_key = request.session.session_key or sessions.get_new_session_key()
if SESSION_COOKIE_AGE != None:
new_session = sessions.save(session_key, request.session._session,
datetime.datetime.now() + datetime.timedelta(seconds=SESSION_COOKIE_AGE))
else:
# right now I'm just making sessions last for an hour ... should
# probably make a configuration directive to specify the seconds
# till the session expires
new_session = sessions.save(session_key, request.session._session,
datetime.datetime.now() + datetime.timedelta(hours=1))
# TODO: Accept variable session length and domain.
response.set_cookie(SESSION_COOKIE_NAME, session_key,
max_age=SESSION_COOKIE_AGE, domain=SESSION_COOKIE_DOMAIN)
return response