Welcome!

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

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:

UserIDUsernamePassword
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:

GroupIDGroupName
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:

GroupIDUserID
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
<cfelse>
 No Access
</cfif>

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.

Conclusion
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 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.
Noted IoT expert and researcher Joseph di Paolantonio (pictured below) has joined the @ThingsExpo faculty. Joseph, who describes himself as an “Independent Thinker” from DataArchon, will speak on the topic of “Smart Grids & Managing Big Utilities.” Over his career, Joseph di Paolantonio has worked in the energy, renewables, aerospace, telecommunications, and information technology industries. His expertise is in data analysis, system engineering, Bayesian statistics, data warehouses, business intelligence, data mining, predictive methods, and very large databases (VLDB). Prior to DataArcho...
Cultural, regulatory, environmental, political and economic (CREPE) conditions over the past decade are creating cross-industry solution spaces that require processes and technologies from both the Internet of Things (IoT), and Data Management and Analytics (DMA). These solution spaces are evolving into Sensor Analytics Ecosystems (SAE) that represent significant new opportunities for organizations of all types. Public Utilities throughout the world, providing electricity, natural gas and water, are pursuing SmartGrid initiatives that represent one of the more mature examples of SAE. We have s...
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...
The Internet of Things (IoT) is going to require a new way of thinking and of developing software for speed, security and innovation. This requires IT leaders to balance business as usual while anticipating for the next market and technology trends. Cloud provides the right IT asset portfolio to help today’s IT leaders manage the old and prepare for the new. Today the cloud conversation is evolving from private and public to hybrid. This session will provide use cases and insights to reinforce the value of the network in helping organizations to maximize their company’s cloud experience.
IoT is still a vague buzzword for many people. In his session at Internet of @ThingsExpo, Mike Kavis, Vice President & Principal Cloud Architect at Cloud Technology Partners, will discuss the business value of IoT that goes far beyond the general public's perception that IoT is all about wearables and home consumer services. The presentation will also discuss how IoT is perceived by investors and how venture capitalist access this space. Other topics to discuss are barriers to success, what is new, what is old, and what the future may hold.
Whether you're a startup or a 100 year old enterprise, the Internet of Things offers a variety of new capabilities for your business. IoT style solutions can help you get closer your customers, launch new product lines and take over an industry. Some companies are dipping their toes in, but many have already taken the plunge, all while dramatic new capabilities continue to emerge. In his session at Internet of @ThingsExpo, Reid Carlberg, Senior Director, Developer Evangelism at salesforce.com, to discuss real-world use cases, patterns and opportunities you can harness today.
All major researchers estimate there will be tens of billions devices – computers, smartphones, tablets, and sensors – connected to the Internet by 2020. This number will continue to grow at a rapid pace for the next several decades. With major technology companies and startups seriously embracing IoT strategies, now is the perfect time to attend @ThingsExpo in Silicon Valley. Learn what is going on, contribute to the discussions, and ensure that your enterprise is as "IoT-Ready" as it can be!
Software AG helps organizations transform into Digital Enterprises, so they can differentiate from competitors and better engage customers, partners and employees. Using the Software AG Suite, companies can close the gap between business and IT to create digital systems of differentiation that drive front-line agility. We offer four on-ramps to the Digital Enterprise: alignment through collaborative process analysis; transformation through portfolio management; agility through process automation and integration; and visibility through intelligent business operations and big data.
There will be 50 billion Internet connected devices by 2020. Today, every manufacturer has a propriety protocol and an app. How do we securely integrate these "things" into our lives and businesses in a way that we can easily control and manage? Even better, how do we integrate these "things" so that they control and manage each other so our lives become more convenient or our businesses become more profitable and/or safe? We have heard that the best interface is no interface. In his session at Internet of @ThingsExpo, Chris Matthieu, Co-Founder & CTO at Octoblu, Inc., will discuss how thes...
Last week, while in San Francisco, I used the Uber app and service four times. All four experiences were great, although one of the drivers stopped for 30 seconds and then left as I was walking up to the car. He must have realized I was a blogger. None the less, the next car was just a minute away and I suffered no pain. In this article, my colleague, Ved Sen, Global Head, Advisory Services Social, Mobile and Sensors at Cognizant shares his experiences and insights.
We are reaching the end of the beginning with WebRTC and real systems using this technology have begun to appear. One challenge that faces every WebRTC deployment (in some form or another) is identity management. For example, if you have an existing service – possibly built on a variety of different PaaS/SaaS offerings – and you want to add real-time communications you are faced with a challenge relating to user management, authentication, authorization, and validation. Service providers will want to use their existing identities, but these will have credentials already that are (hopefully) ir...
Can call centers hang up the phones for good? Intuitive Solutions did. WebRTC enabled this contact center provider to eliminate antiquated telephony and desktop phone infrastructure with a pure web-based solution, allowing them to expand beyond brick-and-mortar confines to a home-based agent model. It also ensured scalability and better service for customers, including MUY! Companies, one of the country's largest franchise restaurant companies with 232 Pizza Hut locations. This is one example of WebRTC adoption today, but the potential is limitless when powered by IoT. Attendees will learn rea...
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 Internet of @ThingsExpo, Ivelin Ivanov, CEO and Co-Founder of Telestax, will share 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 ...
The Internet of Things (IoT) promises to create new business models as significant as those that were inspired by the Internet and the smartphone 20 and 10 years ago. What business, social and practical implications will this phenomenon bring? That's the subject of "Monetizing the Internet of Things: Perspectives from the Front Lines," an e-book released today and available free of charge from Aria Systems, the leading innovator in recurring revenue management.
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.
There’s Big Data, then there’s really Big Data from the Internet of Things. IoT is evolving to include many data possibilities like new types of event, log and network data. The volumes are enormous, generating tens of billions of logs per day, which raise data challenges. Early IoT deployments are relying heavily on both the cloud and managed service providers to navigate these challenges. In her session at 6th Big Data Expo®, Hannah Smalltree, Director at Treasure Data, to discuss how IoT, Big Data and deployments are processing massive data volumes from wearables, utilities and other mach...
P2P RTC will impact the landscape of communications, shifting from traditional telephony style communications models to OTT (Over-The-Top) cloud assisted & PaaS (Platform as a Service) communication services. The P2P shift will impact many areas of our lives, from mobile communication, human interactive web services, RTC and telephony infrastructure, user federation, security and privacy implications, business costs, and scalability. In his session at Internet of @ThingsExpo, Erik Lagerway, Co-founder of Hookflash, will walk through the shifting landscape of traditional telephone and voice s...
While great strides have been made relative to the video aspects of remote collaboration, audio technology has basically stagnated. Typically all audio is mixed to a single monaural stream and emanates from a single point, such as a speakerphone or a speaker associated with a video monitor. This leads to confusion and lack of understanding among participants especially regarding who is actually speaking. Spatial teleconferencing introduces the concept of acoustic spatial separation between conference participants in three dimensional space. This has been shown to significantly improve comprehe...
The Internet of Things is tied together with a thin strand that is known as time. Coincidentally, at the core of nearly all data analytics is a timestamp. When working with time series data there are a few core principles that everyone should consider, especially across datasets where time is the common boundary. In his session at Internet of @ThingsExpo, Jim Scott, Director of Enterprise Strategy & Architecture at MapR Technologies, will discuss single-value, geo-spatial, and log time series data. By focusing on enterprise applications and the data center, he will use OpenTSDB as an example...