How to manage user in flask using session? - flask

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.

Related

Session with Django

In a Home page, i have a form login. in the view.index of the app "Home", after authenticate, i create the ssesion. And after, i call the app "Places" if the authenticate is okey,
request.session['user'] = username
request.session.set_expiry(900)
return HttpResponseRedirect('/places/')
in the settings of the project i configure the SESSION_SAVE_EVERY_REQUEST = True.
How can i send the session to all others pages of the project, and log out the user when the session is expired ?
HTTP is a request response protocol.
This means that the server has no way to to communicate to the client without the client initiating the conversation. So the only way to do something like this is native Django, is to have the client periodically check to see if the session is still ok.
One way to achieve this is with a background ajax call (perhaps using setInterval in javascript) which checks the session, and if it's not any good anymore (either by expiration or the user has been disabled etc) then redirect them back to the login page.
Another approaches could involve sending the expiry time to the client so that it only checks the session when it would have expired (though this wouldn't pick up on users being disabled) or having a websocket server which pushes this information to the client.

Can Hubot Slack bot store sessions

I am trying to implement simple slack bot. So I have configured hubot which will take inputs from slack and passing it to my webapp (django app) and it will take whatever the response from django-app and will reply to slack.
In this process I am trying to store session in django using request.session but that is not reflected in slack. If I am accessing the django-url in browser it is able to store sessions and getting proper response with session.
So does the problem lie with slack or my approach and is there a way to store sessions in hubot when requesting to django-app ??
I can not speak to the specific technologies you use (hubot, django), but I am using server sessions with my Slack apps all the time and can give you a general answer on how it works. Note that my Slack apps are build with PHP, but I think its safe to assume that the principles are the same.
Slack does not support sessions
In general Slack does not support sessions or context. Instead everything is request based. So if you want to have sessions to keep a functional context between requests you need to organize that by yourself in your Slack app.
Challenge for using server sessions with server requests
One challenge is that most server sessions are designed to work with a client that uses a browser. e.g. a PHP server session will store a cookie in the browser, so the server knows, which requests belong to the same session. This does obviously not work with Slack, since all Slack requests are coming from a server and and there is no browser involved.
Approach for using server sessions with Slack
But you can use severs session with Slack with these two tricks:
Manually set the session ID
Usually the ID of a session is chosen automatically by the server, but you can also set it manually. This allows you to tell the server to continue an existing session that was started with a previous request.
Include session ID in Slack control
The functional session of a user is tied together by the Slack controls he uses. (e.g. an interactive button). Its possible to include custom data in those controls (see this answer for details) and that allows you to include the current session ID in it.
Full approach
You include the ID of your current session in the Slack controls, that you create with your app (e.g. an interactive button). Once the user clicks a button Slack will send a request to your app, which will include the session ID. That allows your app to continue an already started server session.

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.

Run method on session expire 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.

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.