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) View Comments

    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.


    Most Recent Comments
    mfreeman 09/12/09 07:27:00 PM EDT

    Question: Where (in which module and where in the module) would you put this custom tag? That is, would you put it in the Application.cfm file (which gets appended at the top of all ColdFusion scripts) or would you put it in the first ColdFusion script of your application (the index.cfm perhaps as the first line of code) or perhaps put a copy in every script of your application as the first line of code?

    Thanks much,
    mfreeman

    @ThingsExpo Stories
    As data explodes in quantity, importance and from new sources, the need for managing and protecting data residing across physical, virtual, and cloud environments grow with it. Managing data includes protecting it, indexing and classifying it for true, long-term management, compliance and E-Discovery. Commvault can ensure this with a single pane of glass solution – whether in a private cloud, a Service Provider delivered public cloud or a hybrid cloud environment – across the heterogeneous enter...
    DXWorldEXPO LLC announced today that ICC-USA, a computer systems integrator and server manufacturing company focused on developing products and product appliances, will exhibit at the 22nd International CloudEXPO | DXWorldEXPO. DXWordEXPO New York 2018, colocated with CloudEXPO New York 2018 will be held November 11-13, 2018, in New York City. ICC is a computer systems integrator and server manufacturing company focused on developing products and product appliances to meet a wide range of ...
    More and more brands have jumped on the IoT bandwagon. We have an excess of wearables – activity trackers, smartwatches, smart glasses and sneakers, and more that track seemingly endless datapoints. However, most consumers have no idea what “IoT” means. Creating more wearables that track data shouldn't be the aim of brands; delivering meaningful, tangible relevance to their users should be. We're in a period in which the IoT pendulum is still swinging. Initially, it swung toward "smart for smart...
    Major trends and emerging technologies – from virtual reality and IoT, to Big Data and algorithms – are helping organizations innovate in the digital era. However, to create real business value, IT must think beyond the ‘what’ of digital transformation to the ‘how’ to harness emerging trends, innovation and disruption. Architecture is the key that underpins and ties all these efforts together. In the digital age, it’s important to invest in architecture, extend the enterprise footprint to the cl...
    Headquartered in Plainsboro, NJ, Synametrics Technologies has provided IT professionals and computer systems developers since 1997. Based on the success of their initial product offerings (WinSQL and DeltaCopy), the company continues to create and hone innovative products that help its customers get more from their computer applications, databases and infrastructure. To date, over one million users around the world have chosen Synametrics solutions to help power their accelerated business or per...
    Coca-Cola’s Google powered digital signage system lays the groundwork for a more valuable connection between Coke and its customers. Digital signs pair software with high-resolution displays so that a message can be changed instantly based on what the operator wants to communicate or sell. In their Day 3 Keynote at 21st Cloud Expo, Greg Chambers, Global Group Director, Digital Innovation, Coca-Cola, and Vidya Nagarajan, a Senior Product Manager at Google, discussed how from store operations and ...
    In an era of historic innovation fueled by unprecedented access to data and technology, the low cost and risk of entering new markets has leveled the playing field for business. Today, any ambitious innovator can easily introduce a new application or product that can reinvent business models and transform the client experience. In their Day 2 Keynote at 19th Cloud Expo, Mercer Rowe, IBM Vice President of Strategic Alliances, and Raejeanne Skillern, Intel Vice President of Data Center Group and ...
    Dion Hinchcliffe is an internationally recognized digital expert, bestselling book author, frequent keynote speaker, analyst, futurist, and transformation expert based in Washington, DC. He is currently Chief Strategy Officer at the industry-leading digital strategy and online community solutions firm, 7Summits.
    We are seeing a major migration of enterprises applications to the cloud. As cloud and business use of real time applications accelerate, legacy networks are no longer able to architecturally support cloud adoption and deliver the performance and security required by highly distributed enterprises. These outdated solutions have become more costly and complicated to implement, install, manage, and maintain.SD-WAN offers unlimited capabilities for accessing the benefits of the cloud and Internet. ...
    Founded in 2000, Chetu Inc. is a global provider of customized software development solutions and IT staff augmentation services for software technology providers. By providing clients with unparalleled niche technology expertise and industry experience, Chetu has become the premiere long-term, back-end software development partner for start-ups, SMBs, and Fortune 500 companies. Chetu is headquartered in Plantation, Florida, with thirteen offices throughout the U.S. and abroad.
    Bill Schmarzo, author of "Big Data: Understanding How Data Powers Big Business" and "Big Data MBA: Driving Business Strategies with Data Science," is responsible for setting the strategy and defining the Big Data service offerings and capabilities for EMC Global Services Big Data Practice. As the CTO for the Big Data Practice, he is responsible for working with organizations to help them identify where and how to start their big data journeys. He's written several white papers, is an avid blogge...
    Bill Schmarzo, author of "Big Data: Understanding How Data Powers Big Business" and "Big Data MBA: Driving Business Strategies with Data Science," is responsible for setting the strategy and defining the Big Data service offerings and capabilities for EMC Global Services Big Data Practice. As the CTO for the Big Data Practice, he is responsible for working with organizations to help them identify where and how to start their big data journeys. He's written several white papers, is an avid blogge...
    From 2013, NTT Communications has been providing cPaaS service, SkyWay. Its customer’s expectations for leveraging WebRTC technology are not only typical real-time communication use cases such as Web conference, remote education, but also IoT use cases such as remote camera monitoring, smart-glass, and robotic. Because of this, NTT Communications has numerous IoT business use-cases that its customers are developing on top of PaaS. WebRTC will lead IoT businesses to be more innovative and address...
    Charles Araujo is an industry analyst, internationally recognized authority on the Digital Enterprise and author of The Quantum Age of IT: Why Everything You Know About IT is About to Change. As Principal Analyst with Intellyx, he writes, speaks and advises organizations on how to navigate through this time of disruption. He is also the founder of The Institute for Digital Transformation and a sought after keynote speaker. He has been a regular contributor to both InformationWeek and CIO Insight...
    Gemini is Yahoo’s native and search advertising platform. To ensure the quality of a complex distributed system that spans multiple products and components and across various desktop websites and mobile app and web experiences – both Yahoo owned and operated and third-party syndication (supply), with complex interaction with more than a billion users and numerous advertisers globally (demand) – it becomes imperative to automate a set of end-to-end tests 24x7 to detect bugs and regression. In th...
    Michael Maximilien, better known as max or Dr. Max, is a computer scientist with IBM. At IBM Research Triangle Park, he was a principal engineer for the worldwide industry point-of-sale standard: JavaPOS. At IBM Research, some highlights include pioneering research on semantic Web services, mashups, and cloud computing, and platform-as-a-service. He joined the IBM Cloud Labs in 2014 and works closely with Pivotal Inc., to help make the Cloud Found the best PaaS.
    Cloud-enabled transformation has evolved from cost saving measure to business innovation strategy -- one that combines the cloud with cognitive capabilities to drive market disruption. Learn how you can achieve the insight and agility you need to gain a competitive advantage. Industry-acclaimed CTO and cloud expert, Shankar Kalyana presents. Only the most exceptional IBMers are appointed with the rare distinction of IBM Fellow, the highest technical honor in the company. Shankar has also receive...
    "Evatronix provides design services to companies that need to integrate the IoT technology in their products but they don't necessarily have the expertise, knowledge and design team to do so," explained Adam Morawiec, VP of Business Development at Evatronix, in this SYS-CON.tv interview at @ThingsExpo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA.
    Business professionals no longer wonder if they'll migrate to the cloud; it's now a matter of when. The cloud environment has proved to be a major force in transitioning to an agile business model that enables quick decisions and fast implementation that solidify customer relationships. And when the cloud is combined with the power of cognitive computing, it drives innovation and transformation that achieves astounding competitive advantage.
    The Founder of NostaLab and a member of the Google Health Advisory Board, John is a unique combination of strategic thinker, marketer and entrepreneur. His career was built on the "science of advertising" combining strategy, creativity and marketing for industry-leading results. Combined with his ability to communicate complicated scientific concepts in a way that consumers and scientists alike can appreciate, John is a sought-after speaker for conferences on the forefront of healthcare science,...