Run method on session expire Django - django

I'm using session to store an object id and its description, this instance should be blocked to all other users while it is beign used in someone's session, and I would like to release the user object once he closes the browser, now I'm aware there is a configuration to expire sessions on browser close, I was just wandering if there is any entry point where I could add some custom code
What I'm trying to achieve is something like
def OnSessionExpire(???):
#release my objects
I've searched around but found no answer, can someone lay a help here? I'm using the backend session mode
Thank you !

Django doesn't do anything at all when the browser closes. Django doesn't even know - how can it: the only time Django knows anything about what you do in the browser is when you make a request to the server, but closing the browser is the opposite of making a request.
Session expiry on browser close is an attribute of the session cookie, not anything that Django does. It just means that the cookie is set with a flag that tells the browser not to persist it when it closes. The actual session data remains in Django's session store, and will do until you explicitly clear it, but is not accessible because the cookie has been removed.
So, the upshot of that is that there is no way to tell explicitly when a session ends. The only thing you can do is to send regular keepalive signals - eg via Ajax - while the session is open, and taken an action if you haven't seen any for a while.

Related

How to manage user in flask using session?

I'm creating chat website using flask socketio. I control people who join chatting using session ( When user login, I set people's session to usernake)like session ['name']=username And when the user is out of chat, I set his or her session none. But in this situation when the user closes the website by not click logout button, there is the user's session though the user logout.. so the user's name is on the list...
How to manage people who do not logout by closing the website?
You might want to try using Javascript to detect a browser close event. It's not a perfect solution, but it will give you a chance in many cases to detect that the user is leaving, and fire off some code to end their session.
You can check out various approaches, but I saw this question which seemed pretty helpful.
As per this doc http://flask.pocoo.org/docs/0.12/api/
you have this parameter for flask.session
permanent If set to True the session lives for
permanent_session_lifetime seconds. The default is 31 days. If set to
False (which is the default) the session will be deleted when the user
closes the browser.
Also from flask-socketio there is a mentioning of session behaviour
The session context global behaves in a different way than in regular
requests. A copy of the user session at the time the SocketIO
connection is established is made available to handlers invoked in the
context of that connection. If a SocketIO handler modifies the
session, the modified session will be preserved for future SocketIO
handlers, but regular HTTP route handlers will not see these changes.
Effectively, when a SocketIO handler modifies the session, a “fork” of
the session is created exclusively for these handlers. The technical
reason for this limitation is that to save the user session a cookie
needs to be sent to the client, and that requires HTTP request and
response, which do not exist in a SocketIO connection. When using
server-side sessions such as those provided by the Flask-Session or
Flask-KVSession extensions, changes made to the session in HTTP route
handlers can be seen by SocketIO handlers, as long as the session is
not modified in the SocketIO handlers.

How exactly does django validates its cookie?

I was reading up on cookie validation and came across the question of how exactly does Django validates its cookie?
If I remember correctly, Django stores session id in the cookie for later use. Does that mean that anyone who fakes the cookie will be able to use arbitrary session data?
The validation itself is damn simple: against the data in in the session backend. As you can see here, the data you receive in a cookie comes from your session, session_key attribute. Where it is being stored depends on your session backend, by default it's the database.
It is impossible to "fake" a cookie. Unless someone stole your SECRET_KEY. More detailed info here.
If someone steals a cookie from a client, the thief can use the client's session till it expires. You cannot prevent it. If you are aware of such a case, the client's password needs to be changed ASAP, as it will lead to invalidation of ther user's existing sessions (starting from Django 1.10).
Upd: your question made me curious whether the session backend actually stores the value as is... Figures, it does. (I got also impressed there's pgAdmin for Windows)

Django close sessions if users moves another site or after browser close

How can I close sessions in Django if a user moves from my site to another or if he close the browser.
From both the question and comments, seems you would like to "close" session when user exits your site without any aid from JS. The answer is it depends how you define "close".
Root of the problem is that HTTP is stateless. Each request coming into the server is completely independent request without any relation to any other requests which means there cannot be any state. Since state is very useful we hack HTTP to add state by using sessions. The idea is that browser sends some identifier to some state stored on the server which allows the server to retrieve that state hence give some context to the request. The key there is that the browser is sending that data. In other words, if the browser at some point will stop sending requests, (e.g. user closes the tab), the server will never know that. Therefore if you define "close" session as removing session from the server, no that cannot be possible without some JS help.
If however all you are trying to achieve is log the user out when they exit your site, that can partially be done in Django with the use of SESSION_EXPIRE_AT_BROWSER_CLOSE setting. Here are additional docs about that. The idea here is that when Django sends the session cookie back to the browser, it will indicate to it that the session cookie should expire when the browser is closed. In that case when the browser is closed, the browser itself will invalidate the session hence the user will be forced to create new session on next visit. This is partial solution since the session will still be stored on the server and I believe only works when browser is completely closed (I dont think closing tabs works but not certain). To mitigate the issue of the server accumulating old sessions, Django provides a management command clearsessions which you should run on regular basis.

Working with Sessions and Cookies

I have this one question in mind that in login sessions does client have to maintain anything so that server uniquely identify client and in multiple client requests response to correct client. I don't understand this sessions and cookies. I asked many about this some say that its server job to maintain sessions and client just send normal request.
Yes, the client must keep track of something, called a session ID. Most commonly, it is a cookie. However, a less used approach is to rewrite all links to pass the session ID in the URL.
Example ID names are ASP.NET_SessionId and PHPSESSID.
Matthew's answer is correct.
It is the server's job to keep track of login sessions, and it's the client web browser's job to keep track of cookies. When you provide username & password on a site, a cookie is provided by the web server to your browser, which will automatically be provided along with subsequent requests to the web server. This cookie uniquely identifies a session which belongs to a particular user on the site (even the "guest" user). So, the server keeps track of all client sessions, and each client remembers its session cookie & provides it along with all its requests. It's a simple scheme. Using Firebug for example, you can see what the web requests look like when you log into a site. You might find that interesting to look at.
It is the server which will maintain the sessions. And it is the server responsibilty to allow session tracking happen. Clients need not bother about sending any information explicitly. As Cliens also sends Cookies saved on the client along with every request, server might use Cookies for sesssion tracking.
Note: Cookies are just one of the way to implement Session Tracking. It is also the best way
So server Cookies as one of the ways to handle session tracking.
It can also be done in other ways:
URL rewriting - the application/server should append the session id in all URL's/Links. When those are invoked from the client the session comes to the server along with the URL.
Hidden Form Fields - The forms may contain hidden input type with session id as field value. When the form is posted, the session id comes along with the form data.

Notify client about expired session - web programming

Is it posible to notify user that session has expired? Can browser act as server and receive such notifications?
One solution would be to generate JavaScript that does countdown on client side and notifies client in the end, but I am iterested if it is postible to do it the first way?
And what are the consequences of first approach? Are there any security concerns?
What would be posable implementation in django, for example?
You could have the JavaScript periodically poll the server for notifications (every 30 seconds, say), using XMLHTTPRequest to check a URL. If the session times out, the server could put something at that URL that indicates it, and then a notification could be popped up. This is how Stackoverflow implements the notifications that someone else has answered a question already if you're in the middle of composing an answer.
You may wish to look at comet, although I think a javascript timer would be a much better solution being less likely to break, and easier to implement.
I can't think of any security implications as you are only providing an expiration notice, not actually doing any authenticating in that step.
You're looking for some sort of comet-type thing. Probably the easiest "server-push" you can do is polling the server.
In fact in Django, there is not server-side expiration if you use filesystem or database engine => is it your client cookie session id wich expires. Otherwise, if you use cache-based session, you could set the cache expiration to a greater value than the session cookie expiration.
An then, simply declare a cookie without expiration to flag the client browser at login, and check in every page the session id :
if there is no session id cookie but your "cookie flag", the session is expired. There is no need to check the server.