9

I have a user logged in. How can i extend/renew expiry date of session received from the request ? Thanks in advance!

Nullpoet
  • 10,949
  • 20
  • 48
  • 65

3 Answers3

9

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)
Anentropic
  • 32,188
  • 12
  • 99
  • 147
  • I think this might not scale due to db update required for every request for every user Maybe redis? – java-addict301 Jun 10 '22 at 20:12
  • 1
    @java-addict301 I agree, for that purpose I would happily recommend https://github.com/jazzband/django-redis#configure-as-session-backend – Anentropic Jun 11 '22 at 14:50
7

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',
    ...
]
cooncesean
  • 1,294
  • 2
  • 18
  • 26
  • 1
    Does this *definitely* work as advertised? The [docs](https://docs.djangoproject.com/en/1.10/topics/http/sessions/#django.contrib.sessions.backends.base.SessionBase.get_expiry_date) for `get_expiry_date` say "this will equal the date `SESSION_COOKIE_AGE` seconds from **now**" (emphasis mine), which is consistent with my local testing. – Dan Tao Mar 30 '17 at 21:54
  • `get_expiry_date()` to me always returns the current time plus the expirary age. – run_the_race Oct 21 '20 at 14:55
2

setting SESSION_COOKIE_AGE is designed for that purpose I believe. After login cookie is set automatically for this period.

You can also save session cookie on every request by using SESSION_SAVE_EVERY_REQUEST setting.

dzida
  • 8,854
  • 2
  • 36
  • 57
  • 1
    yeah.. but if user's session is about to expire and I want to extend his session's expiry date further, then is there a way ? – Nullpoet Jun 15 '10 at 12:23