I have a user logged in. How can i extend/renew expiry date of session received from the request ? Thanks in advance!
It's not necessary to make a custom middleware for this.
Setting SESSION_SAVE_EVERY_REQUEST = True
will cause Django's existing SessionMiddleware
to do exactly what you want.
It has this code:
if modified or settings.SESSION_SAVE_EVERY_REQUEST:
if request.session.get_expire_at_browser_close():
max_age = None
expires = None
else:
max_age = request.session.get_expiry_age()
expires_time = time.time() + max_age
expires = cookie_date(expires_time)
# Save the session data and refresh the client cookie.
# Skip session save for 500 responses, refs #3881.
if response.status_code != 500:
request.session.save()
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,
secure=settings.SESSION_COOKIE_SECURE or None,
httponly=settings.SESSION_COOKIE_HTTPONLY or None)
Here's some middleware that extends an authenticated user's session. It essentially keeps them permanently logged in by extending their session another 60 days if their session expiry_date
is less than 30 days away.
custom_middleware.py:
from datetime import timedelta
from django.utils import timezone
EXTENDED_SESSION_DAYS = 60
EXPIRE_THRESHOLD = 30
class ExtendUserSession(object):
"""
Extend authenticated user's sessions so they don't have to log back in
every 2 weeks (set by Django's default `SESSION_COOKIE_AGE` setting).
"""
def process_request(self, request):
# Only extend the session for auth'd users
if request.user.is_authenticated():
now = timezone.now()
# Only extend the session if the current expiry_date is less than 30 days from now
if request.session.get_expiry_date() < now + timedelta(days=EXPIRE_THRESHOLD):
request.session.set_expiry(now + timedelta(days=EXTENDED_SESSION_DAYS))
You will then need to add this custom middleware after Django's SessionMiddleware, so your settings file should look like:
project/settings.py:
MIDDLEWARE_CLASSES = [
...
'django.contrib.sessions.middleware.SessionMiddleware',
'project.custom_middleware.ExtendUserSession',
...
]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With