views:

632

answers:

2

I'm using django and jquery to implement authenticated sessions and Ajax requests.

I have authenticated session timeouts to log authenticated users out after a long period of inactivity on my site. Some of the pages on my site have a lot of AJAX calls in them that require the user to be in an authenticated session. When a user leaves such a page open for a long time and has the session auto-timed out, any AJAX calls made will just fail and show a browser error. My web stack (django) returns a redirect to login for these AJAX requests, but they just show up as errors to $.ajax() (using jquery.)

How could I reload the page and send the user to the login page through an AJAX request when I find that their auth session has timed out?

+1  A: 

Simple really, have whatever script you're querying return some sort of error code, maybe

{'error', 'notloggedin'}

then, all you need to do is check for this value in your javascript. If it's found, you then do something like

window.location.href = '/login/';

to make the javascript redirect to the login page (changing the path as necessary)

Mez
With the django auth method the django framework tries to redirect the request to the "login" url with a next of the page you were trying to access. So this approach wouldn't work in this case.
MikeN
@MikeN: I think Martin's suggestion will still work for you. Instead of using the auth decorators, use the user_passes_test function in your view. You can then get settings.LOGIN to return to the AJAX caller if that fails.
Jarret Hardie
@MikeN: URL for user_passes_test in the docs: See: http://docs.djangoproject.com/en/dev/topics/auth/#limiting-access-to-logged-in-users-that-pass-a-test
Jarret Hardie
I don't like having to customize so much work in all of my views, how could I override the auth decorator or use middleware to accomplish that?
MikeN
+4  A: 

One way would be to have a script that just pings a page to see whether or not it's still logged in, but this would increase the number of AJAX requests you'd have to do.

Another option is to have the complete function of $.ajax() check the HTTP status code on the XMLHttpRequest object that is passed in:

$.ajax({..., complete = function(xhr, textStatus){
    if(xhr.status > 300 && xhr.status < 400) //you got a redirect
        window.location.href = '/login/';
    ...
    }, ...);
tghw