How i save and show existing progress status using flask socketio if browser is closed(session) - flask

Requirement :-
working on a project with flask.
flask socketIo ...and i have almost completed the project.
Now i want to implement something which is very common on web development.
Right now i can show the status of background tasks in the UI, and events are getting send to specfic (request.sid ). Now if the user accidentally close his browser and and returns to the same page, for obvious reason he won't see anything ( which was happening in the existing session) but the initial page
I want to a way if the user again comes to the page, it should be redirected to the current status page.
Am trying to achieve something exactly like any cloud based solutions For example if i create an Ec2 instance from console and close it. Upon reopening it will still show the existing operations with current status ( running,pending ) etc..
How can achieve that ?

if the user accidentally close his browser and and returns to the same page, for obvious reason he won't see anything
This isn't really obvious. If your user is logged in to your application then you know them, and presumably you also know what background task each user has pending. When the user returns to the page and logs in again, you should be able to find the state of any background tasks associated with the user.
The only situation in which you would not be able to do this is if you don't require your users to authenticate, in which case when the user comes to your page the second time you have no way to know it is the same user that closed the page before. The fix for this problem is to use authentication, so that your users are always known to the server.

Related

How to use django signals to refresh a specific page

I am creating an ecommerce webapp and I want to update my admin page when user place order. After research i found out about Django signals, but it seems pretty confusing. The idea behind this is that, when a user places an order I want the admin page to be refreshed and show the latest updates. I tried ajax but javascript can only work with the current open page. Can anyone help me with usibg django signals this way?
I think you misunderstand a little, if your idea is that the admin page viewed by the user in a browser is to be refreshed. The page viewed by a site visitor is retrieved on demand of the browser. The user could refresh a page, or a page script may auto-refresh on a timer (this is not a very good solution, but it is easy).
Django can't make the browser update the page.
Signals can cause django to do something in the backend, but they can't solve the problem that the browser is in charge.
There is one technology designed to allow the server to push content to the browser: websockets.
If you use websockets (Django's fairly recent built-in support is called Channels (https://channels.readthedocs.io/en/stable/)), then you can push content to the browser, where a receiving script on the page will do something with it. This is a very powerful technique, but there is a learning curve of some hours if you are starting from scratch.
Recently I came across this front-end library which tries to make this easy as
far as the browser goes: https://htmx.org/docs/
But you still have to deal with running a websocket server and learning how to send messages to a websocket. You will however feel like a superhero at the end of it, so there's that.

Send a post request to server

I am fairly new in web development and I decided to handle a user's availability to send a POST request to server. However, I do not know even whether it is possible or not but when a user close my Django site without using logout button (For example close the browser or tab), in order to understand the user is offline or online, I want to send a request to server. As a result, when the server does not get an answer from the user for a while, it automatically logout the user.
Can you tell me is it a good way to handle a user's availability and first of all is it a realistic solution? If it is, can you suggest me a document or example that helps me please.
I agree to to the answer of #Mounir. That's not related to django, if you want to know when a user is "disconnected"(close the tab or window) you need to use javascript, in concrete you need to use Sockets.
I recommend you this ones:
http://socket.io/
https://github.com/centrifugal/centrifugo
I'm using centrifugo for one project right now. In concrete, for chat and inbox messaging. It's very simple to make it run with Django.
Greetings
For logging out user you can use the Session expiration, but for all other staff you want to achieve I don't see any thin really related to Django itself, everything depend on your requirements and is more Browser/javascript related than Django.

How to create a facebook event on users behalf using javascript sdk

I'm trying to piece together information and different chunks of code scattered throughout the documentation on how to make this happen, since there aren't good examples.
I know I have to first get the create_event extended permission which I get with this code:
FB.login(function(response) {
// handle the response
}, {scope: 'create_event'})
;
I know that I also have to issue a HTTP POST request to 'PROFILE_ID/events' with the create_event permissions and the necessary parameters.
My problems are: 1. I don't know how to collect the create_event permission once it is given. If I run the code above, a dialog box will open asking for the permission but once I accept, only a blank page follows.
2. If everything works the way it supposed to with the permissions request and the post request, will my app see a create event page like I would if I were to create an event on my own from my profile? What interface gets seen from the app? Can I take a user from my app directly to the facebook create event page?
I don't know how to collect the create_event permission once it is given. If I run the code above, a dialog box will open asking for the permission but once I accept, only a blank page follows.
That’s how it works. Everything you want to show to the user after successful login, you have to implement yourself.
If everything works the way it supposed to with the permissions request and the post request, will my app see a create event page like I would if I were to create an event on my own from my profile? What interface gets seen from the app?
No “interface” at all – it’s up to you to build that.
Can I take a user from my app directly to the facebook create event page?
The user can go their by themselves. Why would the need your app for that?

How do I authenticate remotely in Django?

Basically what I'm doing is building a desktop application that needs to connect to a web server, perform some calculations, and then have the resulting values sent back to it. The calculations change over time, and also need to stay somewhat secure, which is why I'm not just coding them into the desktop application.
The issue is that only authenticated users should be allowed to access the server. So what I'm looking for is a way to log-in to Django from my desktop application (i.e. the desktop application will pop up a window asking for a username and password, which will then be sent to the Django site, used to authenticate the user, and if valid, will return the results of the computation. It also needs to work as a session (the user enters their password at the beginning and then doesn't need to log-in again until they close the desktop application, even if multiple computations are performed).
I think I need to use session keys for this, and perhaps the RemoteUserMiddleware described here but I really have no idea where to start as far as coding this. Any suggestions or pointers in the right direction would be hugely appreciated.
Thanks,
-Morag
P.S. If this is important, the desktop application is written in VB.NET.
Interesting. I've never done anything like this, but here is, what I assume, is the basic idea:
1) Get a good view of Django sessions; the basic idea is:
One logs in using the django auth framework login service
Django will create a session for you and handle all the difficult stuff
Django returns a HttpResponse with a sessionid cookie. You will need to send this back with any request following to identify yourself and 'operate within the session'.
One logs out using the django auth logout service and the session is destroyed by Django.
2) Now, the rest is relatively easy.
Setup django urls.py with the appropriate urls for login/logout + computation service
Execute a post request to the login service with the appropriate parameters set
Catch the response, extract the 'sessionid' cookie and save it somewhere
On each subsequent request, include the sessionid
This should get you started. Good luck!

IE8 losing session cookies in popup windows

We have an ASP.NET application that uses Forms Auth. When users log in, a session ID cookie and a Forms Auth ticket (stored as a cookie) are generated. These are session cookies, not permanent cookies. It is intentional and desirable that when the browser closes, the user is effectively logged out.
Once a user logs in, a new window is popped up using window.open('location here');. The page that is opened is effectively the workspace the user works in throughout the rest of their session. From this page, other pop-ups are also used.
Lately, we've had a number of customers (all using latest versions of IE8) complaining that the when they log in, the initial pop-up takes them back to the log in screen rather than their homepage. Alternately, users can sometimes log in, get to the homepage (which again, is in a new pop up window), and it all seems fine, until any additional pop-ups are created, where it starts redirecting them to the log in screen again.
In attempting to troubleshoot the issue, I've used good old Fiddler. When the problem starts manifesting, I've noticed that the browser is not sending up the ASP.NET session ID session cookie OR the Forms Auth ticket session cookie, even though the response to the log in POST clearly pushes down those cookies.
What's more strange is if I CTRL+N to open a new window from the popped-up window that is missing the session cookies, then manually type in the URL to the home page, those cookies magically appear again. However, subsequent window.open(); calls will continue to be broken, not sending the session cookies and taking the user to the log in screen.
It's important to note that sometimes, for seemingly no good reason, those same users can suddenly log in and work normally for a while, then it goes back to broken.
Now, I've ensured that there are no browser add-ons, plug-ins, toolbars, etc. are running. I've added our site as a trusted site and dropped the security settings to Low, I've modified the Cookie Privacy policy to "accept all" and even disabled automatic policy settings, manually forcing it to accept everything and include session cookies. Nothing appears to affect it.
Also note the web application resides on a single server. There is no load balancing, web gardens, server farms, clusters, etc. The server does reside behind an ISA server, but other than that it's pretty straight forward.
I've been searching around for days and haven't found anything actionable. Heck, sometimes I can't even reproduce it reliably. I have found a few references to people having this same problem, but they seem to be referencing an issue that was allegedly fixed in a beta or RC release (example: IE8 loses cookies when opening a new window after a redirect). These are release versions of IE, with up-to-date patches.
I'm aware that I can try to set permanent cookies instead of session cookies. However, this has drastic security implications for our application.
Update
It seems that the problem automagically goes away when the user is added as a Local Administrator on the machine. Only time will tell if this change permanently (and positively) affects this problem.
Time to bust out ProcMon and see if there is a resource access problem.
Update #2
It seems there are multiple angles to what appears to be a singular problem. I reported long ago that making the user a local administrator seemed to help. And it did, for a number of users. Of course, that's not really a solution, but it did let us hobble along.
Then more users started reporting the issue, and the admin fix was not helping. The users seemed to be mostly Win7, but Vista was also affected. They also seemed to mostly be 64-bit installations.
Setting the TabProcGrowth to 0 or 1 (either worked) as suggested by some members below seems to have largely addressed the issue. So, I'm going to move my accepted answer to the first person that suggested that, as it has had significantly more impact.
This has been an incredibly frustrating issue to attempt to solve, since it is difficult to reproduce and often occurs with users that I do not have direct communication with, or by the time I get to them it doesn't appear to be working. All I can say is something is not right with the session merging feature, but I don't have much data to feed to Microsoft to find a permanent fix.
This is 'new' functionality in IE8!
Checkj out the IE8 blog below to read about it.
http://blogs.msdn.com/askie/archive/2009/03/09/opening-a-new-tab-may-launch-a-new-process-with-internet-explorer-8-0.aspx
IE8 can use multiple processes for handling an x number of IE windows. When you cross a process space, you loose your cookies (Asp.Net session ID seems to be retained over this process boundry).
I personally think it's broken or a bug. As we know, when browing to the 'same domain target' cookies should be maintained and resent. That IE8 has different processing behavior for security.. Great! that it is behaving badly and 'drops cookies even if going to the same target domain in another window' is just a bug in my view.
You can modify the number of processes IE8 uses through the internet explorer options ehh.. modifying a registry setting!!!!!! (this is what makes it a bug in my view. IE providing a UI to modify these settings would make it 'enterprise level acceptable'.
Regard,
Marvin Smit
There are multiple possibilities behind this -
UAC & Vista (Had to crop up!!). Specifically, look for protected mode behavior.
This could be an actual problem with the Session Merging feature in IE8. More so because opening a new window via the Ctrl+N shortcut causes the cookies to be magically sent in your case.
An issue with an older build of IE (I know you have stated that your customers are using the latest build). You might want to check the details available at Microsoft Connect for bug IDs 408806 and 392032.
We solved this problem by changing the "Set tab process growth" to 0.
Although, we didn't have protected mode turned on and the zone was "Intranet". Evidently this is a problem/bug with Windows 7 64Bit as others have stated.
This page (#4) lead me to the solution: http://blog.httpwatch.com/2009/04/07/seven-things-you-should-known-about-ie-8/
Near as I can tell, another change to cookies across tabs just went live in this security update from November 12, 2013 that is breaking functionality in our app in all versions of IE. We're doing OpenID auth in a popup window so as to not have to redirect the user away from the page they were browsing when they first clicked the Login link. The session cookie for the login is correctly being sent down in the request in the popup window, but it never gets seen by the main browser window, so the next request to the server doesn't have that session cookie on it like it should, and thus logging in never actually works.
Does anyone have any possible solutions to this?
We had this problem on IE6,7 and 8 .The scenario is parent window(1) opens a modal window(2),modal window has a link to a non-modal window (3). I used to get a different session Id in the 3rd window.
Workaround mentioned here fixed the issue http://support.microsoft.com/kb/831678
Since IE8 we (and our customers) are also experiencing the same issue. We have an asp service for creating forms. This application uses new windows for adding elements or managing user accounts e.g. Randomly (when opening a new window), the application doesn't get the required session id for authentication allong with other 'permanent' cookies. Hence, the session id is a temporary cookie. Most of the time it goes well, but other times the session is broken every time a new window is opened. We have to advise our customers to close all IE windows and start over again.
As a web developer I use IE extensively. Personally, I am not experiencing the above issue. But I think a related one. A few times a day IE totally hangs (does not respond anymore) when opening a new window. When I kill a certain IE process using the task manager, IE starts responding again. But in most cases it's better to start all over with a clean new instance of IE. For this reason I just kill the process with the least ram usage which causes all IE processes to quit.
Microsoft saying these issues/bugs are squashed in the final version does not give me trust of their effort solving the issue still be experienced.
I also found a workable fix for this problem. There seems to be a problem with how IE8 handles opening servlets in another window with a relative path such as /test. It seems to be opening a new session as well as a new window. Our workable fix is that instead of opening a new window with a relative path, we just used a jsp page. So when we navigate to a URL, we do not navigate to /test anymore.We navigate to a specific file. In the jsp file, we forward the request to the relative path. This seems to work, which is kind of awkward, since the only difference is that we are placing a specific file in between.
I hope this helps.
I know this problem since IE 5, so I only use session's variables in modal pop-up windows...
When I open a non-modal pop-up window, I replace all session's variables with ASP.NET cache and new object collections...
But it's very tiresome!
Other browsers (i.e. Firefox) don't have this problem...
I believe this is actually a bug in IE; I have reported it here to see what feedback I get: http://social.msdn.microsoft.com/Forums/en-US/83bb3b91-1c1f-4d51-9281-9bc5f51d3640/log-in-fails-cookie-is-not-sent-to-originating-tab?forum=iewebdevelopment
I have a similar, though not identical problem. We load a webpage that opens a popup with window.open() into an IE browser control. On machines that have either IE6 and IE8, the popup window is always assigned a new SessionID by ASP when launched from the control. However, when launched from a normal browser (IE or Firefox), the popup window gets the existing SessionID.
I can see when launching from the control that a new iexplore.exe process is spawned; thus the session loss behavior makes sense given what has been mentioned about in-memory cookies not being carried over to the new process.
I'm still trying to figure out a workaround myself ...
Update
Figured out a workable fix! It is possible to subclass SessionIDManager and specify that this class should be used instead of the default (<sessionState sessionIDManagerType="..."> in Web.config). The subclass can look for a query parameter containing the existing session id in an override of CreateSessionID(), and return it if found. This essentially allows a page to request being "merged" into an existing session it has knowledge of.
The call to window.open() then simply needs that query parameter specified in its URL.
Haw-Bin
Had a similar problem with PHP5 and IE8. When opening one certain popup window in Javascript with window.open, IE8 lost the session cookie and forced the user to login agan.
Meanwhile, other popup windows worked OK.
The culprit turned out to be an image tag. The template system generates image src = values dynamically and a missing image resulted in an image tag with an empty src clause (
I supect this has something to do with IE interpreting the empty src-tag as an insecure URL and isolating the session in the popup without informing the user.
I was running into a similar issue with using session variables to pass values to a pop-up window. I just ended up writing the values to a persistent cookie and then reading the cookie in the popup window. This may not work with the issue you were having with forms authentication, but if are just using session variables to pass some values to a window in IE8, persistent cookies seems to have worked for me.
edit: see also this thread
You Can Also Use the LocalStoprage method to reset the value in parent window.
localStorage("Key")="Value";//Javascript