ColdFusion MX 6 Login Security (Page 4 of 6)

36. 	<cfif NOT isDefined("request.User.LoggedIn")>
38. 	   <cfinclude template="login.cfm">
39. 	   <cfabort>
40. 	<cfelse>
42. 	   <cflock scope="SESSION" throwontimeout="Yes" timeout="5" type="EXCLUSIVE">
43. 	       <cfset session.User = Duplicate(request.User)>
44. 	   </cflock>
45. 	   <cflocation url="index.cfm">
46. 	</cfif>
47. </cfif>

Since both the username and password were entered correctly, the Request.User structure was created along with two keys. This will cause the conditional logic on line 36 (above) to evaluate to FALSE causing the else block to be processed. Inside the else block, we duplicate the Request.User structure into a newly created session structure and redirect to the main page of the site, index.cfm.

The idea of this login form and how it works is pretty simple. Let's recap. The form will be submitted, the Application template will recognize that the form was submitted and immediately include the authentication template. The authentication template runs and either creates a local error message variable, or a request structure based on whether or not the user supplied valid data. Either way, page processing will be returned to the Application template every time (specifically to line 36). We know whether or not the user supplied valid data based upon whether or not the Request.User structure is defined. I do a test for the structure key Request.User.LoggedIn, because this is the flag I chose to use (line 36). If the user enters an incorrect username or an incorrect password for a valid username, the login template is included and the appropriate error message is displayed. If the user enters a valid username and corresponding password, they will be redirected to the main page of the site.

Going back to the Application.cfm template, let's review the last portion of the code just after our FORM check.

50. <cflock scope="SESSION" throwontimeout="Yes" timeout="5" type="READONLY">
51. 	<cfif NOT isDefined("session.User.LoggedIn")>
52. 		<cfinclude template="login.cfm">
53. 		<cfabort>
54. 	</cfif>
55. </cflock>

Like all the code in the Application template, this block of code is run upon every *.cfm page request. Remember requirement three on the first page of the tutorial? It should protect all of our ColdFusion templates in the event an unauthorized user attempts access, or an authorized users session times out. This block of code protects our application and makes authentication a requirement. It handles both initial entry to the application and also session time-outs.