Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django session expires at browser close OR after time

The Django documentation states:

You can control whether the session framework uses browser-length sessions vs. persistent sessions with the SESSION_EXPIRE_AT_BROWSER_CLOSE setting.

If SESSION_EXPIRE_AT_BROWSER_CLOSE is set to True, Django will use browser-length cookies -- cookies that expire as soon as the user closes his or her browser. Use this if you want people to have to log in every time they open a browser.

This setting is a global default and can be overwritten at a per-session level by explicitly calling the set_expiry() method of request.session as described above in using sessions in views.

So when I set SESSION_EXPIRE_AT_BROWSER_CLOSE to True in my settings file, this indeed is what it does. This is good because I want a user's session to expire upon browser close. However, I also want a user's session to expire after, say, 15 minutes of inactivity. If I use set_expiry() mentioned above, the SESSION_EXPIRE_AT_BROWSER_CLOSE is overridden so if a user closes the browser and then re-opens the browser before the expiration, the session is still valid. Not what I want.

In addition, the documentation for set_expiry() says the sessions expires after the set amount of time of inactivity. That's actually not true. It expires no matter what, whether my user is clicking around on the site or not.

So to summarize, what I want to do is:

  1. Have my sessions configured that if the user closes the browser, the session automatically expires.
  2. Set a session expiration length that is updated with activity, i.e. if a user does something else on the site, the expiration is reset.

Thoughts/suggestions?

like image 521
nucklehedd Avatar asked Jan 03 '13 20:01

nucklehedd


People also ask

Is session expire when browser close?

Session cookies expire once you log off or close the browser. They are only stored temporarily and are destroyed after leaving the page.

How does Django maintain session?

Django uses a cookie containing a special session id to identify each browser and its associated session with the site. The actual session data is stored in the site database by default (this is more secure than storing the data in a cookie, where they are more vulnerable to malicious users).

Why does session expire?

If your Internet connection is unstable, periodically disconnecting and reconnecting, it can cause a website session to expire. When the Internet connection is lost the website connection can be terminated, resulting in a session expired message if you try to access any page after the Internet reconnects.


1 Answers

As Jiaaro suggested in this answer you can use SESSION_EXPIRE_AT_BROWSER_CLOSE and set a timestamp on session at each request and add a custom Middleware to handle the inactivity.

like image 172
Amyth Avatar answered Sep 24 '22 22:09

Amyth