Detecting user logout on browser close in Django

2019-02-24 10:58发布

问题:

we have a web service for some numerical computing. It has a registered mode, in which a user has to register to have its results sent by mail.

We would like to keep track of how long the user stays logged. The login time is written in the database upon successful registration. Registration in not permanent, it's just for the purpose of single session and is used for acquiring the user email.

There are a few situations possible:

User logs out normally via the logout button. Simplest solution. Write the time and logout in the database, and delete session.

User logs out by session expiry. I'm planning on having a script which would check all the database entries which don't have a set logout time and if current time - login time > expiry time write logout time in a database as login time + expiry time.

User logs out by browser close. The sessions have a get_expire_at_browser_close() set to True. But i don't know how can the server detect browser closure.

Ideas, critics, comments?

回答1:

In django session middleware these lines control session expiration if we want that SESSION_EXPIRE_AT_BROWSER_CLOSE:

if settings.SESSION_EXPIRE_AT_BROWSER_CLOSE:
    max_age = None
    expires = None

Server doesn't have to do detect anything as cookie that has no max_age or expires set should be deleted on the client side, according to this page:

By setting either of these, the cookie will persist until its time runs out, otherwise—if you set neither—the cookie will last until you close your browser (a “session cookie”).

Edit:

One way of tracking how long user was online is by using javascript that will ping server every now and then. It will happen only as long as the user has page opened in browser and on every ping server should update last seen online value for the user.

When user closes browser session is over. Next time user logs in server can calculate duration of his last visit as last seen online - last login time.

Simpler solution without using any javascript: last seen online could be updated on every user request using simple custom middleware.