Monday, November 2, 2009

Enforcing Session Timeout in Django with JavaScript

This article could also be called "How mixing AJAX and Django sessions broke my app."

Here's the rundown: Sessions are set to expire for security reasons. Normally, clicking a link or submitting a form would cause the browser to be redirected to the login page. Obviously this is bad because sensitive information might be visible on the screen. Not quite so obvious is the fact that, when your form submission requires AJAX validation of an address, that validation breaks behind the scenes. The poor user just gets an error message about an invalid address, and can't attempt the form submission which would send them to the login page.

The solution we used relies on having the session expiration added to the context in a context processor, then using JavaScript in our base template to redirect to the logout page if the user is inactive for too long.

Here's the JavaScript, which should be placed in a template block. Inheriting templates should have {{ block.super }} inside the block tags.

            <script type="text/javascript">

//for the session timeout
session_timeout = {{session_timeout}};
page_load_time = new Date().getTime();


function check_session_timeout(){

// check timeout
active_seconds = (new Date().getTime() - page_load_time) / 1000;
if (active_seconds >= session_timeout){
window.location = '/logout/';
}else{
setTimeout('check_session_timeout()', 5000)
}

}

//Start checking for session timeout
check_session_timeout();

</script>

1 comment:

  1. Perfect, This helped me achieve what I needed to achieve.

    ReplyDelete