You will be redirected in 30 seconds or close now.

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

Related Topics: ColdFusion

ColdFusion: Article

Creating a Remember Me Login

Implementing a login script on your site

Many of my articles in this column have dealt with theoretical concepts and syntax of implementing those concepts in ColdFusion. In this article, I want to concentrate on the implementation steps you might take when building something.

Most Web applications have a "sign me up" feature that allows users to register. Registered users often have access to additional information or features that anonymous users don't. I'm going to walk you through the process of creating a simple login form, including database authentication and a "remember me" checkbox.

The Database
Before you start coding this application, you'll need to create a database. Most login schemes include a username and password. You can put that information in a table called Users. The table will also need a unique identifier, called a primary key in database terms. Here is a sample of data from the table:

1 Jeff Houser
2 CFDJ Author
3 ColdFusion Macromedia

Normally, a users table would have much more information than just a username and password. A name, address, and e-mail address are common additions. For the purposes of this example, we'll keep it simple. In a real-world application, you should consider encrypting the passwords in your database for security purposes. You can do this using ColdFusion's hash function. More information about the hash function is located at Click Here. You would use the hash function before saving the user's password into the database. For the purposes of this example, the passwords will remain in plain text.

You could implement a login script using just the users table we defined, but you'll find it limiting. The user is either logged in, or not logged in. There is no distinction between different levels of access. Suppose, for example, that anonymous users can look at products, registered users can post reviews of products, and admin users can change product information. You'll need something more than an "Authenticated" or "Not Authenticated" security structure. To do this we'll need to be able to group users into security groups. The SecurityGroups table will need a primary key and a group name. This is an example of some possible groups:

1 Admin
2 Anonymous
3 Registered

You'll also need an intersection or linking table to associate a user with his or her groups. This table will contain the GroupID and the UserID. The reason for creating this as a separate table is so that a single user can be in multiple groups, and a single group can have multiple users inside of it. This is known as a many-to-many relationship in the world of database design.

Here is an example of the SecurityUserGroups intersection table:

1 (Admin) 1 (Jeff / Houser)
3 (Registered) 1 (Jeff / Houser)
3 (Registered) 3 (ColdFusion / Macromedia)

I added the group and user names next to the ID in parentheses to more easily show the relations. In a relational database, you would store only the ID. Our finished database structure is seen in Figure 1.

Before accessing this database from your ColdFusion code, you'll have to create a datasource in the ColdFusion administrator. Setting up the datasource is beyond the scope of this article, but it's a pretty straightforward task and you can read about setting up datasources for any database at Click Here.

The Login Form
With our database ready for use, we can start examining the login form. Most forms have two parts: an input page and a processing page. The input page asks for the username and password. It also has a checkbox for a "Remember Me" functionality. The code behind the form is shown in Listing 1.

The login form can be seen here: (Figure 2)

Enter Jeff in the username field and Houser in the password field. Check the Remember Me box and click submit. This brings us to the processing page (see Listing 2).

The RememberMe form variable value comes from a checkbox. If not checked when the form is submitted, the variable will not exist on the form processing page. You can use the cfparam tag to default if this situation occurs. The second step in the process is to validate the user's login information against the database. The cfquery tag is used to run the database query. The query joins the users table and the SecurityUserGroups table, where the username and password fields are equal to the input of the form. The query retrieves all information from the users table and the list of GroupIDs from the intersection table. If the database stored hashed passwords, we would change the query comparison to:

Users.password = '#hash(form.password)#'

This allows us to correctly compare two hashed values, not plain text passwords. This way we are keeping the user's password information secure.

We can check the RecordCount variable of our query to see if the query returned any rows. If the query did not return any rows, then the user did not enter a valid username and password combination. The login should fail. If rows are returned, then the login was a success. The code creates two session variables to process the login. To make use of session variables, you'll have to use the cfapplication tag. ColdFusion's application framework is beyond the scope of this article; however, you can read about it at Click Here.

The first value, LoggedIn, is a Boolean value that specifies that the user has logged in. I would default this value to false when the session is initialized. The second variable, groups, contains a list of all the groups that the user is in. The ValueList will give us a list from the column in the query.

Later in your application, when you have to decide whether a user should have access to a resource or not, you can use ListFind against the groups variable to see if the user is allowed. Here's an example:


<cfif ListFind(session.Groups, 1)>
 allow Access
 No Access

If the user is in the admin group he or she can see the resulting HTML code, or access the corresponding resource. If not, then he or she will not be given access.

In this code, we are rolling our own security scheme. Many applications will use this approach, due to the complexity of security functions in the pre-CFMX days. However ColdFusion MX introduced a much improved security scheme using some new tags: cflogin, cfloginuser, and cflogout. They allow you to log in a user and set up a list of roles that ColdFusion will handle internally. The roles tie in with the role attributes of functions inside a ColdFusion component. These new tags are not in wide use yet, but they are definitely worth checking out if you are building an application from the ground up (livedocs.macromedia.com/coldfusion/6.1/htmldocs/appsecu6.htm). The reason I don't use them in my development is because my biggest project of the moment is being built to run off of BlueDragon, which does not yet support the functions.

Remembering the User
The one portion of code that I haven't explained yet is the "remember me" portion, so let's look at it in detail. There are many different ways you could implement the "remember me" portion of code. In most methods, you'll set a cookie on the user's machine, and store the same value in the database. When the user returns to the site, you can check to see if the cookie exists. If it does, you can retrieve the user's information from the database based on the cookie value. Simpler systems where security is not an issue may store the user's primary key ID. More complex systems with heavier security requirements may assign a UniqueID value, created with the CreateUUID function. Some systems I've worked with will store the CFID and CFTOKEN values generated by ColdFusion and used for session management, and use those to remember the user.

For the purposes of our sample, we are going to store the user's primary key as a cookie, but remember that in applications where security is a priority, this is probably not your best move. If form.RememberMe is set to true, then we use the cfcookie tag to create a cookie on the user's browser. We name the cookie UserID. The value is set to the UserID value returned from the query. It is set to never expire.

Setting the cookie is only the first step. When a user comes to the site, something will have to be implemented to check to see if we know who they are, or not. We are going to put this code in the Application.cfm. The code in the Application.cfm will look like an abbreviated version of the code in the login-processing page (see Listing 3).

First the code checks whether the IsLoggedIn session variable is defined. If it isn't, then this is the first time a user has come to the site. Next, we check if the UserID cookie variable exists. If it does, Next we run a query to get the user data based on the UserID. If the query finds the user, the code sets the two session variables. If not, it defaults them to the value. If the cookie doesn't exist at all, it defaults the session values.

This article demonstrated a simple method for implementing a login script on your site. It incorporated many common security elements and used many common ColdFusion tags. The approach I took in this article is not the only approach that could be used, but it is simple yet elegant. For those who want more, you can check out the authenticationAPI included in Macromedia's DRK 7. In my next column I'll talk more in depth about ColdFusion's application framework and the cfapplication tag, including setting up the session and application scopes.

More Stories By Jeffry Houser

Jeffry is a technical entrepreneur with over 10 years of making the web work for you. Lately Jeffry has been cooped up in his cave building the first in a line of easy to use interface components for Flex Developers at www.flextras.com . He has a Computer Science degree from the days before business met the Internet and owns DotComIt, an Adobe Solutions Partner specializing in Rich Internet Applications. Jeffry is an Adobe Community Expert and produces The Flex Show, a podcast that includes expert interviews and screencast tutorials. Jeffry is also co-manager of the Hartford CT Adobe User Group, author of three ColdFusion books and over 30 articles, and has spoken at various events all over the US. In his spare time he is a musician, old school adventure game aficionado, and recording engineer. He also owns a Wii. You can read his blog at www.jeffryhouser.com, check out his podcast at www.theflexshow.com or check out his company at www.dot-com-it.com.

Comments (0)

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.

@ThingsExpo Stories
The Internet of Things will greatly expand the opportunities for data collection and new business models driven off of that data. In her session at @ThingsExpo, Esmeralda Swartz, CMO of MetraTech, discussed how for this to be effective you not only need to have infrastructure and operational models capable of utilizing this new phenomenon, but increasingly service providers will need to convince a skeptical public to participate. Get ready to show them the money!
DevOps Summit 2015 New York, co-located with the 16th International Cloud Expo - to be held June 9-11, 2015, at the Javits Center in New York City, NY - announces that it is now accepting Keynote Proposals. The widespread success of cloud computing is driving the DevOps revolution in enterprise IT. Now as never before, development teams must communicate and collaborate in a dynamic, 24/7/365 environment. There is no time to wait for long development cycles that produce software that is obsolete at launch. DevOps may be disruptive, but it is essential.
The 3rd International Internet of @ThingsExpo, co-located with the 16th International Cloud Expo - to be held June 9-11, 2015, at the Javits Center in New York City, NY - announces that its Call for Papers is now open. The Internet of Things (IoT) is the biggest idea since the creation of the Worldwide Web more than 20 years ago.
Connected devices and the Internet of Things are getting significant momentum in 2014. In his session at Internet of @ThingsExpo, Jim Hunter, Chief Scientist & Technology Evangelist at Greenwave Systems, examined three key elements that together will drive mass adoption of the IoT before the end of 2015. The first element is the recent advent of robust open source protocols (like AllJoyn and WebRTC) that facilitate M2M communication. The second is broad availability of flexible, cost-effective storage designed to handle the massive surge in back-end data in a world where timely analytics is e...
"There is a natural synchronization between the business models, the IoT is there to support ,” explained Brendan O'Brien, Co-founder and Chief Architect of Aria Systems, in this SYS-CON.tv interview at the 15th International Cloud Expo®, held Nov 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA.
The Internet of Things will put IT to its ultimate test by creating infinite new opportunities to digitize products and services, generate and analyze new data to improve customer satisfaction, and discover new ways to gain a competitive advantage across nearly every industry. In order to help corporate business units to capitalize on the rapidly evolving IoT opportunities, IT must stand up to a new set of challenges. In his session at @ThingsExpo, Jeff Kaplan, Managing Director of THINKstrategies, will examine why IT must finally fulfill its role in support of its SBUs or face a new round of...
The BPM world is going through some evolution or changes where traditional business process management solutions really have nowhere to go in terms of development of the road map. In this demo at 15th Cloud Expo, Kyle Hansen, Director of Professional Services at AgilePoint, shows AgilePoint’s unique approach to dealing with this market circumstance by developing a rapid application composition or development framework.
The 3rd International Internet of @ThingsExpo, co-located with the 16th International Cloud Expo - to be held June 9-11, 2015, at the Javits Center in New York City, NY - announces that its Call for Papers is now open. The Internet of Things (IoT) is the biggest idea since the creation of the Worldwide Web more than 20 years ago.

ARMONK, N.Y., Nov. 20, 2014 /PRNewswire/ --  IBM (NYSE: IBM) today announced that it is bringing a greater level of control, security and flexibility to cloud-based application development and delivery with a single-tenant version of Bluemix, IBM's platform-as-a-service. The new platform enables developers to build ap...

Advanced Persistent Threats (APTs) are increasing at an unprecedented rate. The threat landscape of today is drastically different than just a few years ago. Attacks are much more organized and sophisticated. They are harder to detect and even harder to anticipate. In the foreseeable future it's going to get a whole lot harder. Everything you know today will change. Keeping up with this changing landscape is already a daunting task. Your organization needs to use the latest tools, methods and expertise to guard against those threats. But will that be enough? In the foreseeable future attacks w...
Building low-cost wearable devices can enhance the quality of our lives. In his session at Internet of @ThingsExpo, Sai Yamanoor, Embedded Software Engineer at Altschool, provided an example of putting together a small keychain within a $50 budget that educates the user about the air quality in their surroundings. He also provided examples such as building a wearable device that provides transit or recreational information. He then reviewed the resources available to build wearable devices at home including open source hardware, the raw materials required and the options available to power s...
“The age of the Internet of Things is upon us,” stated Thomas Svensson, senior vice-president and general manager EMEA, ThingWorx, “and working with forward-thinking companies, such as Elisa, enables us to deploy our leading technology so that customers can profit from complete, end-to-end solutions.” ThingWorx, a PTC® (Nasdaq: PTC) business and Internet of Things (IoT) platform provider, announced on Monday that Elisa, Finnish provider of mobile and fixed broadband subscriptions, will deploy ThingWorx® platform technology to enable a new Elisa IoT service in Finland and Estonia.
From telemedicine to smart cars, digital homes and industrial monitoring, the explosive growth of IoT has created exciting new business opportunities for real time calls and messaging. In his session at @ThingsExpo, Ivelin Ivanov, CEO and Co-Founder of Telestax, shared some of the new revenue sources that IoT created for Restcomm – the open source telephony platform from Telestax. Ivelin Ivanov is a technology entrepreneur who founded Mobicents, an Open Source VoIP Platform, to help create, deploy, and manage applications integrating voice, video and data. He is the co-founder of TeleStax, a...
The Internet of Things is not new. Historically, smart businesses have used its basic concept of leveraging data to drive better decision making and have capitalized on those insights to realize additional revenue opportunities. So, what has changed to make the Internet of Things one of the hottest topics in tech? In his session at @ThingsExpo, Chris Gray, Director, Embedded and Internet of Things, discussed the underlying factors that are driving the economics of intelligent systems. Discover how hardware commoditization, the ubiquitous nature of connectivity, and the emergence of Big Data a...
We certainly live in interesting technological times. And no more interesting than the current competing IoT standards for connectivity. Various standards bodies, approaches, and ecosystems are vying for mindshare and positioning for a competitive edge. It is clear that when the dust settles, we will have new protocols, evolved protocols, that will change the way we interact with devices and infrastructure. We will also have evolved web protocols, like HTTP/2, that will be changing the very core of our infrastructures. At the same time, we have old approaches made new again like micro-services...
The Internet of Things is a misnomer. That implies that everything is on the Internet, and that simply should not be - especially for things that are blurring the line between medical devices that stimulate like a pacemaker and quantified self-sensors like a pedometer or pulse tracker. The mesh of things that we manage must be segmented into zones of trust for sensing data, transmitting data, receiving command and control administrative changes, and peer-to-peer mesh messaging. In his session at @ThingsExpo, Ryan Bagnulo, Solution Architect / Software Engineer at SOA Software, focused on desi...
Today’s enterprise is being driven by disruptive competitive and human capital requirements to provide enterprise application access through not only desktops, but also mobile devices. To retrofit existing programs across all these devices using traditional programming methods is very costly and time consuming – often prohibitively so. In his session at @ThingsExpo, Jesse Shiah, CEO, President, and Co-Founder of AgilePoint Inc., discussed how you can create applications that run on all mobile devices as well as laptops and desktops using a visual drag-and-drop application – and eForms-buildi...
Disruptive macro trends in technology are impacting and dramatically changing the "art of the possible" relative to supply chain management practices through the innovative use of IoT, cloud, machine learning and Big Data to enable connected ecosystems of engagement. Enterprise informatics can now move beyond point solutions that merely monitor the past and implement integrated enterprise fabrics that enable end-to-end supply chain visibility to improve customer service delivery and optimize supplier management. Learn about enterprise architecture strategies for designing connected systems tha...
"For over 25 years we have been working with a lot of enterprise customers and we have seen how companies create applications. And now that we have moved to cloud computing, mobile, social and the Internet of Things, we see that the market needs a new way of creating applications," stated Jesse Shiah, CEO, President and Co-Founder of AgilePoint Inc., in this SYS-CON.tv interview at 15th Cloud Expo, held Nov 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA.
Recurring revenue models are great for driving new business in every market sector, but they are complex and need to be effectively managed to maximize profits. How you handle the range of options for pricing, co-terming and proration will ultimately determine the fate of your bottom line. In his session at 15th Cloud Expo, Brendan O'Brien, Co-founder at Aria Systems, session examined: How time impacts recurring revenue How to effectively handle customer plan changes The range of pricing and packaging options to consider