Tips Tricks Samples

Check a users' session hasn't expired before submitting

When running session authentication, especially on a secure connection (SSL) it can be hugely annoying for a user if they try and submit a form only to be told that their session has expired. To combat this I wrote a bit of Javascript in conjunction with a couple of HTML pages which checks your session before trying to submit the data. If the session has expired then you're prompted to log in again before being allowed to continue.

So step 1, before submitting your form use the following script:
//**************************************************************************************
//First check if the session is alive
 var xml = new ActiveXObject("Microsoft.XMLHTTP");
 var pos=0;
 currURL = (document.location.href).toLowerCase();
 pos = currURL.indexOf('://');
 pos += 3;
 pos = currURL.indexOf('/', pos);
 vurl = trim(currURL.substring(0, pos));
 xml.open("GET", vurl + "/authchecker.nsf/auth?readform", false);
 xml.send(null);
 var bError = false;
 if (xml.responseText.indexOf("Anonymous") > -1) {
  //The session has expired so prompt user to login again before submitting
  var validSession = window.showModalDialog("/authchecker.nsf/commonframeset?readform&bottomframe=/authchecker.nsf/QuickLogin.html", "Login", "dialogHeight: 270px; dialogWidth: 400px; dialogTop: px; dialogLeft: px; edge: Raised; center: Yes; help: No; resizable: No; status: No;");
  if (validSession != "true"){
   bError = true;
   if (validSession != "")
    alert(validSession);
  }
 }
//End Session Checker (Except for bError check around following chunk
//************************************************************************
 if (!bError)
  document.forms[0].submit();

What it does is open a URL using the XMLHTTP ActiveX control in Internet Explorer. I always have a form on the server which will return the current username and rights as an XML document (in this case accessed at "/authchecker/auth?readform"):
<?xml version="1.0" encoding="utf-8" ?> <userinformation>   <name>CN=Matthew White/O=FCL</name>   <accesslist>     <access>CN=Matthew White/O=FCL</access>     <access>*</access>     <access>*/O=FCL</access>     <access>Administrators</access>     <access>[FCLAdmin]</access>   </accesslist>   <cookie>DomAuthSessId=24A0C25E003E5F604B5A1CAC544D7C98</cookie> </userinformation>
The XML returned is checked to see if your username is Anonymous, if it is then we know that your session has expired so we have to prompt for your username and password instead of submitting the form. So we open the quick login screen using the ShowModalDialog method in IE. If the user enters a correct username and password then the modal dialog closes down and the submit continues, otherwise the login screen with reappear until they have logged in or they cancel by closing the dialog box. Even if they can't log in it means that they do not lose any work.

Download the sample NSF