Tutorials

ColdFusion MX 6 Login Security (Page 2 of 6)

If you downloaded the source files, you can follow along in our scenario. There is only one entry in the Users table of the loginSecurity database. The username is "Aaron" and the password is "mypassword". Because the password was encrypted using ColdFusion's Hash() function (more on this later), it will look like gibberish in the database; this is fine. As outlined on the previous page, when a user submits the login form, the Application.cfm template will recognize the form submittal and immediately redirect to authenticate.cfm. If you open up this template you'll see that the first thing we do is query the database in an attempt to match the user-supplied username with a username in the database.

14. <cfquery name="GetUserDetails" datasource="##request.datasource##">
15. 	SELECT Username, Password
16. 	FROM Users
17. 	WHERE Username = '##FORM.Username##'
18. </cfquery>
	

Next, we create an IF statement that handles the results of our query. There are two and only two scenarios here. Either the username supplied in the FORM exists in the database or it does not. Also, there will be only one instance of a particular username in the database. There cannot be two different User records that have a Username of "Aaron." Of course, this doesn't happen by magic, and should be taken care of in your procedure to add/create users (not covered in this tutorial).

20. <cfif GetUserDetails.RecordCount eq 0>
25. 	<cfset variables.errorMessage = "The Username you provided, <b>" 
          & FORM.Username & "</b>, is an invalid Username.">
26. <cfelse>
28. 	<cfset variables.hashedPassword = Hash(FORM.Password)>
29. 	<cfif variables.hashedPassword neq GetUserDetails.Password>
31. 		<cfset variables.errorMessage = "The Password you supplied for
                   user <b>" & FORM.Username & "</b> was incorrect.">
32. 	<cfelse>
34. 		<cfset request.User = StructNew()>
35. 		<cfset request.User.LoggedIn = "1">
36. 		<cfset request.User.Username = FORM.Username>
37. 	</cfif>
38. </cfif>
	

Let's go over both scenarios and how our application will handle them. First, if the user supplies a username that does not exist in our database the conditional login on line 20 will evaluate to TRUE. This will result in the creation of a local variable to hold the appropriate error message. Once this variable is set, page processing will return to the Application template - specifically, line 36. On this line, we test for the existence of a structure key called Request.User.LoggedIn. Obviously, since the user failed to supply a correct username, this key does not exist and the conditional statement will evaluate to TRUE. The login form will be shown again, and this time will display the error message we set in the authenticate template.

PREVIOUS | NEXT

RSS