Welcome!

You will be redirected in 30 seconds or close now.

ColdFusion Authors: Yakov Fain, Jeremy Geelan, Maureen O'Gara, Nancy Y. Nee, Tad Anderson

Related Topics: ColdFusion

ColdFusion: Article

Avoiding Unwanted Session Timeouts

Avoiding Unwanted Session Timeouts

Even the most productive and effective application can be rendered useless by a poor user interface. Before we start, I want you to consider, for example, the following frustrating scenario....

Joe is a salesperson at a company that uses a Web-based online expense report system. It's the end of the month, so he logs into the system and starts filling out his expense report. Many fields need to be filled out, and in the middle of entering the data he goes searching for receipts and other paperwork. For security reasons the system is set to timeout his session if 15 minutes go by without any "activity." After working on his expense report for 25 minutes and having his session timeout without his knowing it, he presses the save button. The application has timed out and he's forced back to the login screen.

Joe isn't quite sure what just happened, so he logs in again and goes to his expense report. Of course, none of his work was saved and he curses at the "stupid program." He starts to redo his expense report, searches through a mound of paperwork and again fills out dozens of fields. This time it takes him only 16 minutes but when he presses the save button the system has again timed out his session and he's forced back to the login screen.

Angry and dejected, he calls Jane in the IT department. She quickly walks him through saving an expense report (taking less than 15 minutes) and of course it works just perfectly. Joe tries in vain to explain to her that he tried to save his expense report twice and both times it wouldn't save. When Jane gets off the phone she thinks to herself, "Typical stupid user." Joe is thinking "Typical stupid program." Frustration all round! (See Figure 1.)

The Problem
Developing applications for a secure intranet or extranet almost always leads to the idea of a session. Since HTTP is a stateless protocol, the ability to authenticate a user with a login is often tied to sessions. ColdFusion makes much of this easy for developers with its session-scoped variables. But they leave a security hole: if Joe logs in so his status is saved in a session variable then leaves for lunch without logging out, anyone can come in and access information using his login.

The accepted solution to this problem is to timeout the session. This means that the system terminates the session and forces Joe to log in again if there hasn't been any activity for a specified number of minutes. The problem with this solution is that activity must be server-side activity since the session is tracked on the server. By this criterion, filling out form fields doesn't count as "activity" since it doesn't include any communication with the server.

It would be nice if we could somehow warn Joe that he is about to timeout and offer him an opportunity to save his work. CF can't do this on its own since it's a server-side scripting language. Action may be taking place on the client side that the server and CF are not aware of.

JavaScript: setTimeout
JavaScript is a scripting language that runs on the client's browser and works well in conjunction with CF. Javascript has a powerful function called setTimeout (don't let the name fool you, it has nothing to do with the session timeout we've been discussing). The setTimout function allows you to run a piece of JavaScript at a specified interval:

setTimeout(JavascriptCode, Timeinterval);

The JavascriptCode is often specified as a function and the Timeinterval is specified in milliseconds. The following code will run the ShowHello function in 5,000 milliseconds (five seconds):

<SCRIPT Language="Javascript">
function ShowHello()
{
window.alert("Hello, world!");
}
setTimeout(ShowHello()', 5000);
</SCRIPT>

We defined a function called ShowHello and then use the setTimeout function to run the Show- Hello function in five seconds. Neat, but the real power of the setTimeout function is that you can have the specified function reset the Timeout function so that the specified function is called continually.

<SCRIPT Language="Javascript">
function ShowHello()
{
window.alert("Hello, world!");
setTimeout('ShowHello()', 5000);
}
setTimeout('ShowHello()', 5000);
</SCRIPT>

After the first five seconds the ShowHello function runs, and pops up an alert that says, "Hello world." After you press the OK button, the ShowHello function resets the setTimeout function to run itself again in another five seconds. This continues, with the result that every five seconds an alert pop ups. This works just like a timer. Hmmm, it seems we could use this same technique to help solve Joe's problem.

The Solution
By using a combination of Java-Script and CF, we can develop a custom tag that warns users that they're about to timeout, giving them a chance to save their work and refresh the page before they lose their information. It will have three inputs or attributes:

 

  • The number of minutes that the system is set to timeout a session
  • The number of minutes ahead of time that we want to warn the user (the threshold)
  • The actual warning message that will be displayed

    Using the <CFPARAM> tag, we define the attributes of the custom tag and set a default for each of them:

    <CFPARAM Name="Attributes.TimeOutMinutes"
    Default="30">
    <CFPARAM Name="Attributes.Warning-
    Threshold"
    Default="2">
    <CFPARAM Name="Attributes.Warning-
    Message"
    Default="You will timeout in
    #Attributes.WarningThreshold# minute(s)!">

    The next step is to set some global JavaScript variables. We need to know the time the current page was first accessed, as well as the threshold time. Using time in JavaScript is much easier if everything is converted to milliseconds, so the first thing we do is get the current Date/Time and convert it to milliseconds. Then we convert the Attributes.TimeOutMinutes to milliseconds by multiplying by 60,000 and then adding the result to the current time. This gives us the number of milliseconds that represents the exact time before the current session will timeout. We also convert to milliseconds the Attributes. Threshold, which is in minutes.

    <CFOUTPUT>
    <SCRIPT Language="Javascript">

    // Global variables
    StartTime = new Date();
    StartMils = Date.parse(StartTime.toLocaleString());
    TimeOutMils = StartMils + (60000 *
    #Attributes.TimeOutMinutes#);
    ThresholdMils = 60000 *
    #Attributes.WarningThreshold#;

    The next step is to create a CountDown function that will run every 10 seconds and check if it has reached the given threshold. We already learned how we can use JavaScript's setTimeout function to create a timer. The first line of this function clears JavaScript's Timeout mechanism just to be safe. Remember, although the names are similar, JavaScript's Timeout functions have nothing to do with the session timeout that we're dealing with. They are simply functions that we use to setup and run a piece of code every x number of milliseconds. We'll use this later to run CountDown every 10 seconds.

    Next, we get the current time and convert it into milliseconds to calculate how many milliseconds are left until the timeout occurs.

    function CountDown()
    {
    clearTimeout('timerLoop');
    CurrentTime = new Date();
    CurrentMils = Date.parse(CurrentTime.toLocaleString());
    RemainingMils = TimeOutMils - CurrentMils;

    Once we have the number of milliseconds until timeout, we can compare that to the threshold milliseconds. If the number of milliseconds until timeout is less than the threshold milliseconds, then we display the warning message. If we haven't reached the threshold then we use JavaScript's setTimeOut function to run our CountDown function again in 10 seconds, thus:

    if(RemainingMils < ThresholdMils)
    window.alert('#Attributes.WarningMessage#');
    else
    timerLoop = setTimeout('CountDown()', 10000);
    }

    Finally, we have to remember to run the CountDown function for the first time to set everything in motion and start the timer. Normally, you would call it in the <BODY> tag's onLoad event, but since we're writing a custom tag, we don't want to rely on the tag's user to remember to add it to the <BODY> tag. So we call it with inline JavaScript before closing the script, as shown here:

    // run CountDown for the first time
    CountDown();
    </SCRIPT>
    </CFOUTPUT>

    Save the preceding code as c:\cfusion\customtags\TimeOutWarning.cfm and you can use the tag by simply calling <CF_TIMEOUTWARNING>. For testing, add <CF_TIMEOUTWARNING WarningThreshold="1" TimeOutMinutes="2"> to a CF page. About a minute after loading the page, a warning will pop up, "You will timeout in 1 minute(s)!" (See Figure 2.)

    Conclusion
    As developers, we must always be conscious of user interface issues. As the scenario at the beginning of the article shows, user interface is the difference between an application that's usable and accepted and one that's unusable and the cause of frustration. Often the most productive and effective application is rendered useless because of a poor user interface. This custom tag is one way that you can help improve the user's experience and it only takes one line of code to implement.

    Now let's revisit our original example (see Figure 3).

    This time Joe logs in and begins to fill out his expense report. While shuffling through his receipts, he hears a beep. Looking at the screen he sees a warning message and realizes he's about to timeout. He presses the save button and continues shuffling through his receipts. Once he's done, he submits his expense report for approval and he can now actually get some work done. He no longer thinks "stupid program." Instead he appreciates the way his expense check is processed within three days.

    Throughout all of this, Jane in IT is able to play Solitaire without interruption.

  • More Stories By Daniel Jean

    Daniel Jean, CTO and cofounder of Galileo Development Systems, a provider of Web-based software solutions for the consulting and
    contract staffing industries, has worked in the client/server and Web development industry for 10 years.

    Comments (1)

    Share your thoughts on this story.

    Add your comment
    You must be signed in to add a comment. Sign-in | Register

    In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.


    IoT & Smart Cities Stories
    This month @nodexl announced that ServerlessSUMMIT & DevOpsSUMMIT own the world's top three most influential Kubernetes domains which are more influential than LinkedIn, Twitter, YouTube, Medium, Infoworld and Microsoft combined. NodeXL is a template for Microsoft® Excel® (2007, 2010, 2013 and 2016) on Windows (XP, Vista, 7, 8, 10) that lets you enter a network edge list into a workbook, click a button, see a network graph, and get a detailed summary report, all in the familiar environment of...
    At CloudEXPO Silicon Valley, June 24-26, 2019, Digital Transformation (DX) is a major focus with expanded DevOpsSUMMIT and FinTechEXPO programs within the DXWorldEXPO agenda. Successful transformation requires a laser focus on being data-driven and on using all the tools available that enable transformation if they plan to survive over the long term. A total of 88% of Fortune 500 companies from a generation ago are now out of business. Only 12% still survive. Similar percentages are found throug...
    IT professionals are also embracing the reality of Serverless architectures, which are critical to developing and operating real-time applications and services. Serverless is particularly important as enterprises of all sizes develop and deploy Internet of Things (IoT) initiatives. Serverless and Kubernetes are great examples of continuous, rapid pace of change in enterprise IT. They also raise a number of critical issues and questions about employee training, development processes, and opera...
    AI and machine learning disruption for Enterprises started happening in the areas such as IT operations management (ITOPs) and Cloud management and SaaS apps. In 2019 CIOs will see disruptive solutions for Cloud & Devops, AI/ML driven IT Ops and Cloud Ops. Customers want AI-driven multi-cloud operations for monitoring, detection, prevention of disruptions. Disruptions cause revenue loss, unhappy users, impacts brand reputation etc.
    At CloudEXPO Silicon Valley, June 24-26, 2019, Digital Transformation (DX) is a major focus with expanded DevOpsSUMMIT and FinTechEXPO programs within the DXWorldEXPO agenda. Successful transformation requires a laser focus on being data-driven and on using all the tools available that enable transformation if they plan to survive over the long term. A total of 88% of Fortune 500 companies from a generation ago are now out of business. Only 12% still survive. Similar percentages are found throug...
    Atmosera delivers modern cloud services that maximize the advantages of cloud-based infrastructures. Offering private, hybrid, and public cloud solutions, Atmosera works closely with customers to engineer, deploy, and operate cloud architectures with advanced services that deliver strategic business outcomes. Atmosera's expertise simplifies the process of cloud transformation and our 20+ years of experience managing complex IT environments provides our customers with the confidence and trust tha...
    The Japan External Trade Organization (JETRO) is a non-profit organization that provides business support services to companies expanding to Japan. With the support of JETRO's dedicated staff, clients can incorporate their business; receive visa, immigration, and HR support; find dedicated office space; identify local government subsidies; get tailored market studies; and more.
    At CloudEXPO Silicon Valley, June 24-26, 2019, Digital Transformation (DX) is a major focus with expanded DevOpsSUMMIT and FinTechEXPO programs within the DXWorldEXPO agenda. Successful transformation requires a laser focus on being data-driven and on using all the tools available that enable transformation if they plan to survive over the long term. A total of 88% of Fortune 500 companies from a generation ago are now out of business. Only 12% still survive. Similar percentages are found throug...
    As you know, enterprise IT conversation over the past year have often centered upon the open-source Kubernetes container orchestration system. In fact, Kubernetes has emerged as the key technology -- and even primary platform -- of cloud migrations for a wide variety of organizations. Kubernetes is critical to forward-looking enterprises that continue to push their IT infrastructures toward maximum functionality, scalability, and flexibility. As they do so, IT professionals are also embr...
    In his general session at 19th Cloud Expo, Manish Dixit, VP of Product and Engineering at Dice, discussed how Dice leverages data insights and tools to help both tech professionals and recruiters better understand how skills relate to each other and which skills are in high demand using interactive visualizations and salary indicator tools to maximize earning potential. Manish Dixit is VP of Product and Engineering at Dice. As the leader of the Product, Engineering and Data Sciences team at D...