You are on page 1of 28

Developing Cold Fusion Applications Tutorial

This document accompanies the CF pages that are labeled lesson1, etc. The application is a simple Human Resources application. Our final application will include CF pages for user input, processing input, and outputting results. Additionally, I have include files demonstrating login procedures, the application framework, and security. These files are not fully documented. Additional references are the Allaire Documentation available for free from their web-site or you can purchase a book on ColdFusion, the book written by Ben Forta generally considered the best.

Lesson 1 Web Development Process of Static Pages


1. 2. 3. 4. 5. Add simple text to the page: My Name is Ron Use the toolbar to edit the Font for the text you typed above. Save the file as: name.cfm (a good habit is to explicitly type the .cfm) ftp the file to your directory on the server In the browser address box input the address of where you saved the file: http://ein5990.eng.fiu.edu/userc20/cftemplates/Name.cfm 6. Go back to CF Studio. By right mouse click on a tag the edit window appears. For example, right click on the text you typed and you can change the font tag.

Lesson 2 CFSET
1. 2. 3. 4. 5. 6. Open the file from lesson 1 and rename it for lesson 2 (use SAVE AS) Under the text type <CFSET MyAge = 32> Add <BR> and then text My Age is Add <CFOUTPUT>#MyAge#</CFOUTPUT> Save the file and view it in the browser. Select view source from your browser window. Do you see the CF tags? Why not?

* CFSET is used to assign a local variable * CFOUTPUT is required to output any Cold Fusion variable to the page. * Notice that CFStudio color codes the different types of tags, variables, etc.

Lesson 3 More about variables


1. Create a new CF page 2. create a local variable using CFSET for FirstName (remember to put around the value of the variable) 3. create a local variable called LastName

4. create a final variable that concatenates the first two variables


<CFSET FullName = FirstName & & LastName>

<CFOUTPUT>#FullName#</CFOUTPUT>

5. Add text, My Name is: 6. Add a cfoutput tag to output the variable FullName after the text 7. Save the file, ftp to server, and view in browser. 8. An alternative method is to put the text inside of the cfoutput tags

<CFOUTPUT>My Name is: #FullName#</CFOUTPUT>

9. Save the file, ftp to server, and view in browser. There should be no difference between having the text inside or outside of the CFOUTPUT tags.

Variables
Several different types of variables: Local Form Session CGI Client Cookie All CF Variables are typeless, you dont need to specify integer, text, or other types. Variable scope is different for each variable type. For example, the local variable we created with <CFSET> is only scoped for that page, furthermore, the variable is only available after the CFSET line since the CF code is interpreted sequentially.

Summary:
Two tags were demonstrated: <CFSET> to define and set the value of local variables <CFOUTPUT> to replace the variable with its value and output it to the HTML page. - you put all variables in between # signs to replace variable name with its value. - You can put text, HTML tags, and client variables in between CFOUTPUT tags. It ignores them except for the # signs. - CFOUTPUT is a very important tag.

Lesson 4 Querying a Database


1. Create a new page 2. Use the CFQUERY tag to embrace SQL query to the database.

<CFQUERY NAME=EmployeeList DATASOURCE=Hrdatabase> SELECT FirstName, LastName, StartDate, Salary, Temporary FROM Employees </CFQUERY> <CFOUTPUT QUERY=EmployeeList> #FirstName# #LastName# #StartDate# #Salary# #Temporary# </CFOUTPUT>

Summary
The CFQUERY tag is used to enclose SQL queries that are sent to the Datasource specified. In a properly setup Cold Fusion Development environment you can view the table structure through CF Studio which greatly aids you in writing the SQL. To output the results of the query you use the CFOUTPUT tags but include the query name as shown. The variable names to output are the column names from the query you wrote. All other rules for CFOUTPUT still apply.

About CFQUERY
The SQL does not get a semicolon (;) delimiter for the end of the SQL. Also, text must be in single quotes when used in the WHERE clause. For example:
SELECT FirstName, LastName FROM Employee WHERE FirstName = #Form.FirstName#

However, numbers do not use single quotes.


SELECT FirstName, LastName FROM Employee WHERE EmployeeID = #EmployeeID#

Lesson 5 Formatting the data


Tables are the easiest method for controlling the layout of HTML pages. In this lesson we learn how to use the CFOUTPUT tag with HTML table tags to output each row of the query as a row of the table. 1. The CFOUTPUT tag must be outside of the table row <TR> tag. Then for each instance of the query a single row will be outputted. Also, note the use of special formatting tags for Dates and Currency.
<!--- display the query result set as a table with the appropriate headings ---> <TABLE WIDTH="95%"> <TR>

</TR> <CFOUTPUT QUERY="EmployeeList"> <TR> <TD>#FirstName#</TD> <TD>#LastName#</TD> <TD>#DateFormat(StartDate)#</TD> <TD>#DollarFormat(Salary)#</TD> <TD>#Temporary#</TD> </TR> </CFOUTPUT> </TABLE>

<TH <TH <TH <TH <TH

ALIGN="LEFT">First Name</TH> ALIGN="LEFT">Last Name</TH> ALIGN="LEFT">Start Date</TH> ALIGN="LEFT">Salary</TH> ALIGN="LEFT">Temporary</TH>

2. Except for full-time developers, memorizing the special formatting tags like DollarFormat(salary) is not realistic. Learn how to utilize the help in order to find special formatting tags.

Forms
Forms allow the user to input data. This can be used to insert new records into a database (use the SQL Insert); to update existing records (SQL Update); to search the database on specific criteria (the user-specified criteria goes in the Where clause). To use forms you need two pages: The form page and the action page. The form page is used to collect the data. The data is saved into a form variable. The form variables are sent to the action page where they are processed. Note, the scope of form variables is the action page. It is suggested that you include the words form and action in the file names. For example, on a form used to collect new employee information for inserting into the database call it InsertForm.cfm and call the corresponding action page InsertAction.cfm. All Cold Fusion pages must use the method POST. Check boxes and radio buttons do not send data to the Action page if they are not selected. Thus, on the action page you must use an IF statement to see if they were checked.

Lesson 6 Form Page


1. Forms must identify the action page the data will be sent to and the HTTP method to use. For Cold Fusion applications always use the POST method. The HTTP method is GET.
<FORM ACTION="ActionPage.cfm" METHOD="POST">

3. This course does not cover basic HTML. You should be familiar with all the controls (input devices) available for collecting data from the user.

Lesson 6 Action Page


1. To identify the variable as a form variable precede it with Form.
<CFOUTPUT> Last Name: #Form.LastName#<BR> Department:#Form.Department#<BR> Temporary Status: #Form.Temporary#<BR> </CFOUTPUT>

2. This is only a simple action page that shows what the user input.

Lesson 7 Action page with Conditional Logic to Check Input


There are several methods to validate user input and to check for values in radio buttons and check boxes. Here we will show the Cold Fusion approach. However, JavaScript is probably preferable for developing scalable web applications because it is performed on the client-side whereas Cold Fusion is performed on the server-side. In web applications this is a critical difference. The user must enter text into the box so we check if they leave the field blank by using an IF statement. The IF statement is shown below.
<!--- use conditional logic to determine if user entered information in the last name text field ---> <CFIF Form.LastName IS NOT ""> Last Name: <CFOUTPUT>#Form.LastName#<BR></CFOUTPUT> <CFELSE> Last Name Not Entered!<BR> </CFIF>

We can also use the IF logic to see if the checkbox for temporary is selected. Notice how we use this to specify whether the employee is temporary or permanent.
<!--- use conditional logic to determine if the temporary variable is defined (selected on the form page). If yes, display temporary, else, display permanent status ---> <CFIF IsDefined("Form.Temporary") IS "YES"> Status: Temporary Employee <CFELSE> Status: Permanent Employee </CFIF> An alternative approach to check the form input is with the Len tag. Also, you can define

two local variables Valid and Error. Then at the end just check if Not Valid.
<CFSET Valid = True>

<CFSET Error = > <!--- Check if a name has been provided ---> <CFIF Len(Form.Name) is 0> <CFSET Valid = False> <CFSET Error = Error & A Name is required.<BR>> </CFIF>

Here we check if the email entered is valid or not. This is a more complicated form validation since we cannot simple check if it is text or integer.
<!--- Check if the e-mail address is valid ---> <CFSET Dot = 0> <CFSET At2 = 0> <CFSET At = Find("@",Form.Email)> <CFIF At greater than 0> <CFSET At2 = Find("@",Form.Email,At+1)> <CFSET Dot = Find(".",Form.Email,At+1)> </CFIF> <CFIF (Len(Form.Email) is not 0) and (At is 0 or At2 greater than 0 or Dot is 0)> <CFSET Valid = False> <CFSET Error = Error & The E-mail Address is invalid.<BR>> </CFIF>

Lesson 8 dynamically populate drop-down boxes


In most web applications when a drop-down select box is used the developer must enumerate all of the options. For example, if the select box is for states then all 50 states must be programmed into the HTML page. Cold Fusion provides a method to dynamically populate the select box options. So for example, if we wish to add Puerto Rico as a new state then we just add it once to the database and it will appear dynamically on all select boxes.
<!--- dynamically populate drop down select box to allow users to search by department ---> <P> Department<BR> <SELECT NAME="Department_Name"> <OPTION VALUE="All">All</OPTION> <CFOUTPUT QUERY="GetDepartments"> <OPTION VALUE="#Department_Name#"> #Department_Name# </OPTION> </CFOUTPUT> </SELECT>

CFINCLUDE

Use CFInclude to include code segments from other files. For example to include the title bar. On the page you insert into you put the following code segment:
<!--- include toolbar.cfm---> <cfinclude template="Toolbar.cfm">

The code you insert should not have the <HTML> AND </HTML> tags since it will be inserted into another page.

Lesson 8 Action page that dynamically generates SQL


In order to search on multiple items but also allow the user to only input a subset of them you use conditional logic embedded into the SQL. For example, this code allows the user to search on any single field or combination of all three fields. If the user does not enter a last name then it is not used in the query.
<!--- build dynamic query to get employee information based on user search criteria ---> <CFQUERY NAME="EmployeeSearch" DATASOURCE="HRSolution"> SELECT Employees.FirstName, Employees.LastName, Departments.Department_Name, Employees.StartDate, Employees.Salary, Employees.Temporary FROM Employees, Departments WHERE Departments.Department_ID = Employees.Department_ID <!--- use conditional logic to determine if user entered information in the last name text field ---> <CFIF IsDefined("Form.LastName") IS "YES"> <CFIF Form.LastName IS NOT ""> AND Employees.LastName LIKE '%#Form.LastName#%' </CFIF> </CFIF> <!--- use conditional logic to determine if the user would like to search on all departments or just an individual department ---> <CFIF IsDefined("Form.Department_Name") IS "YES"> <CFIF Form.Department_Name IS NOT "ALL"> AND Departments.Department_Name = '#Form.Department_Name#' </CFIF> </CFIF> <!--- use conditional logic to determine if the temporary variable is defined (selected on the form page) ---> <CFIF IsDefined("Form.Temporary") IS "YES"> AND Employees.Temporary = '#Form.Temporary#' </CFIF> </CFQUERY>

Sometimes there may be no records in the database that must the users search. Instead of letting the system generate an error you add the following code that utilizes a property of the query called RecordCount.
<!--- check to determine if any records have been returned based on the users search criteria ---> <CFIF EmployeeSearch.RecordCount IS "0"> No records match your search criteria. <br> Please click the back button and try again.

Lesson 9 Using Hidden Fields in forms to validate input


The name of the hidden field must be the Input Name with an underscore (_) Required. The message the user is prompted goes into the Value.
<!--- perform server side validation to ensure the user entered a last name, a valid date and numeric value for the salary field ---> <INPUT TYPE="HIDDEN" NAME="FirstName_Required" VALUE="First Name is Required!">

Here is the corresponding input text box.


<b>Employee First Name</b><BR> <INPUT TYPE="Text" NAME="FirstName" size="20" maxlength="50">

To enforce a date format use VariableName_Date or to enforce a real number use VariableName_float.

Lesson 9 Action page to insert values


We simple use SQL and the Insert command to insert the user entered data into the database. Notice how we use the form variables in the Values section.
<!--- insert a new employee record into the employee table ---> <CFQUERY NAME="InsertEmployee" DATASOURCE="HRSolution"> INSERT INTO Employees (FirstName, LastName, Department_ID, StartDate, Salary, Temporary) VALUES ('#Form.FirstName#','#Form.LastName#', #Form.Department_ID#,#Form.StartDate#, #Form.Salary#, '#TempStatus#') </CFQUERY>

Application Framework
An application is a set of ColdFusion Templates that enables you to: Maintain state by setting variables that can be accessed from any template in the application (scope is the entire application). Provide custom error messages Enhance the security of an application The application framework consists of an application.cfm template that must be saved in the root directory and variables that have scope throughout the entire application. These variables are: Variable Type Client Session Application Server Description Tied to a single client (or browser) and can persist over multiple sessions. Exists for a single client in a single session For an application and accessible by multiple clients. Accessible by all clients and applications in a single server.

The application.cfm template is processed first, before all other *.cfm templates in the application. The process of a user request for a page is as follows: 1. User requests a cfm page in the application. 2. Before the *.cfm page is processed, ColdFusion checks the directory for an application.cfm template. 3. If no application.cfm template is found it checks the next higher directory. 4. If no application.cfm template is ever found then processing of the requested *.cfm template takes place as usual. 5. If the application.cfm template is found then it is processed first, and then the *.cfm template requested is processed. 6. After the *.cfm template is requested ColdFusion then searches for a OnRequestEnd.cfm template. If found this template is then processed. The application.cfm template is consequently processed everytime a *.cfm template is requested in the application. Consequently, you could define global variables and procedures in the application.cfm template that will be processed each time. To enable session, client, and application management you use the following tag:
<CFAPPLICATION NAME=MyAppName CLIENTMANAGEMENT = Yes/No SESSIONMANAGEMENT = Yes/No SETCLIENTCOOKIES = Yes/No SESSIONTIMEOUT= #CreateTimeSpan(days, hours, minutes, seconds)#

CLIENTSTORAGE = registry or cookie or name of datasource SetDomainCookies = Yes/No >

Attribute NAME SESSIONMANAGEMENT SESSIONTIMEOUT CLIENTMANAGEMENT CLIENTSTORAGE SETCLIENTCOOKIES

Description Name of the application Enables session variables Time limit after which session expires (dont make too long) Enables client variables Specifies where to store client variables Specifies whether you use cookies when defining session and client variables (otherwise you must pass it on the URL)

Value Name Yes/No Use the createtimesp an function. Yes/no Registry or cookie or data source Yes/No

Default No

Required Yes No

No Registry Yes

No No No

Client Management
Client variables are for a single client and persist over multiple sessions. Two client variables are set by default:
CFID An CFTOKEN

incremental ID for each client that connects to the server A random number used in conjunction with CFID to uniquely identify a particular client. You use these for: User display preferences such as background colors User content preferences such as stocks to watch, show sports stories, etc. Counts of how many times a user visits and when they visit last Items in a shopping cart and past purchases Scores for quizzes or games

Default Client Variables


LastVisit the date and time of the last visit. HitCount the number of hits on the application TimeCreated when the client cookie was first created

Storage Alternatives
The three storage options are registry, cookies, or external data sources. The registry has limited memory and in a multi-server clustered environment cannot be used. The cookies have limitations since clients may turn them off. Using a datasource eliminates these problems but it increases the number of database calls from the application server. Client variables are limited to 255 characters and no arrays or query recordsets.

Session Management
Session variables are stored in the Servers RAM (not very scalable). Session variables are intended to be used for a short period of time. You use session variables for: Enforcing user login Storing arrays instead of passing them between templates Storing calculations Storing query recordsets.

Notice, you can store more complex and larger variable data in session variables than client variables. To create a session variable:
<CFLOCK TIMEOUT = 30 NAME=#Session.SessionID#> <CFSET session.user_name = #form.user_name#> </CFLOCK>

The CFLOCK tag is used to prevent problems with simultaneous read/write to shared variables. Although, a session variable is not shared it is recommended to use the CFLOCK. What CFLOCK does is it prevents others from use the shared resource until the first user releases it. A default session variable created is session.SessionID. You can use this to identify a single session and user. The other two variable types; application and server are not discussed here due to infrequent use.

Lesson 10 Sophisticated Login Pages


The database should have a table with two attributes, UserID and Password. The system login requires three pages: LoginForm.cfm LoginAction.cfm and Main.cfm. The LoginForm is used to input username and password. The LoginAction checks via query

the database to see if they match. If they do not match the user is prompted to try again. If they match the user is sent to the Main.cfm page via a CFLOCATION tag.

LoginForm.cfm
<FORM ACTION="LoginAction.cfm" METHOD="POST"> <P>Please enter your user ID:<BR> <INPUT TYPE="Text" NAME="user_id" SIZE="20"> <P>Please enter your Password:<BR> <INPUT TYPE="password" NAME="password" SIZE="20"> <P> <INPUT TYPE="Submit" NAME="Submit" VALUE="Login"> </FORM>

LoginAction.cfm
<!------------------------------------------------------Security_check query verifies that form.user_name and form.password are valid. --------------------------------------------------------> <CFQUERY NAME="security_check" DATASOURCE="#db#"> SELECT passwords.user_id, passwords.password, passwords.user_name FROM passwords WHERE passwords.user_id = '#form.user_id#' AND passwords.password = '#form.password#' </CFQUERY> <!------------------------------------------------------If form.user_name and form.password are not valid then Prompt the user to log in again. --------------------------------------------------------> <CFIF SECURITY_CHECK.RECORDCOUNT IS 0> <CFOUTPUT> <HTML> <HEAD> <TITLE>#title#</TITLE> </HEAD> <BODY BGCOLOR="#bgcolor#"> <DIV ALIGN="center"> <CFINCLUDE TEMPLATE="login.cfm"> <FONT FACE="#face#" SIZE="2"> Your User ID and Password are not in our database.<BR>Please try again.

</FONT> </DIV> </BODY> </HTML> </CFOUTPUT> <CFABORT> <!------------------------------------------------------If the user_name and password are verified, then the session is started, client.user_name is set, and the user is redirected to the home.cfm template --------------------------------------------------------> <CFELSE> <CFLOCK TIMEOUT="30" THROWONTIMEOUT="Yes" NAME="#Session.SessionID#" TYPE="Exclusive"> <CFSET SESSION.STARTED = TRUE> </CFLOCK> <CFSET CLIENT.USER_NAME = "#security_check.user_name#"> <CFLOCATION URL="home.cfm" ADDTOKEN="no"> </CFIF> <CFABORT> - Stops processing of page. <CFLOCATION> - is a goto statement that

sends the user to the page (URL) listed.

Error Handling
You can define generalized error handling for your application. Validation Errors: Occur when a user improperly completes and submits a form, such as not filling in a text box. Request Errors: Occur due to misplaced template in an include tag, misspelled variable name or similar error. To define custom error handling you use:
<CFERROR TYPE=REQUEST TEMPLATE=error_request.cfm MAILTO=Ronald@eng.fiu.edu>

And you must create of course the page error_request.cfm. The CFERROR tag is best placed within the application.cfm template.

There are default error variable names such as error.diagnostics which you can use. The reader is referred to ColdFusion user manual for the list of these variables.

Trouble Shooting
Trouble shooting skills require you to apply logic and the process of elimination.

Common Errors:
1. Spelling Mistakes Spelling of the code as well as the variables. 2. No closing tag For example, #Form.UserID and you forget the closing # sign. 3. type mismatch with databases Text requires single quotes and numbers do not. Also, need to validate form input to see that it matches the database table format. 4. Mis-matching names Naming conventions are crucial. As sites become more complex if you haphazardly name variables, forms, and pages then you will have difficulty managing your site. For example, did you call a page to update employee records (UpdateEmployeeForm.cfm) but you called the form to insert new employee records (EmployeeInsertForm.cfm). This is inconsistent naming and will become difficult to manage.

The HR Database

The Department Table

The Employee Table

<!--- Application.cfm ---> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <!------------------------------------------------------Set application name; client variables on; session variables on; allow cookies; session timeout after 20 minutes; Application timeout after 2 days; store client variables in registry --------------------------------------------------------> <CFAPPLICATION NAME="MyApp" SESSIONMANAGEMENT="Yes" SETCLIENTCOOKIES="Yes" SESSIONTIMEOUT="#CreateTimeSpan(0, 0, 20, 0)#" APPLICATIONTIMEOUT="#CreateTimeSpan(2, 0, 0, 0)#" CLIENTMANAGEMENT="Yes" CLIENTSTORAGE="Registry"> <!------------------------------------------------------Used to reset application, session, and client variables for testing purposes. You must remove the comments surrounding the next set of code variables to clear all variable scopes, and then replace the comments so the application will run normally. --------------------------------------------------------> <!--<CFSET STRUCTCLEAR(APPLICATION)> <CFSET STRUCTCLEAR(SESSION)> <CFLOOP INDEX="x" LIST="#GetClientVariablesList()#"> <CFSET DELETED = DELETECLIENTVARIABLE("#x#")> </CFLOOP> <CFCOOKIE NAME="cfid" EXPIRES="NOW"> <CFCOOKIE NAME="cftoken" EXPIRES="NOW"> <CFCOOKIE NAME="cfglobals" EXPIRES="NOW"> <CFABORT> ---> <!------------------------------------------------------Set Server constants that can be accessed by any client --------------------------------------------------------> <CFLOCK TIMEOUT="30" THROWONTIMEOUT="Yes" NAME="server" TYPE="Exclusive"> <CFIF NOT #ISDEFINED("server.season")#> <!-----------------------------------------------The season is currently set to a string, but could easily be determined automatically by time of year. -------------------------------------------------> <CFSET SERVER.SEASON = "Spring Time"> </CFIF> </CFLOCK> <!------------------------------------------------------Set Application constants -------------------------------------------------------->

<CFLOCK TIMEOUT="30" THROWONTIMEOUT="Yes" NAME="#Application.ApplicationName#" TYPE="Exclusive"> <CFIF NOT #ISDEFINED("Application.Started")#> <CFSET APPLICATION.TITLE = "My Quiz Application"> <CFSET APPLICATION.DB = "quiz"> <CFSET APPLICATION.EMAIL = "kmotlagh@geocities.com"> <CFSET APPLICATION.BGCOLOR = "##ffffff"> <CFSET APPLICATION.FACE = "Arial"> <CFSET APPLICATION.STARTED = TRUE> </CFIF> </CFLOCK> <!------------------------------------------------------Test to see if user has logged in. If they haven't a non-persistent login variable is set. This is so you do not have to use a <CFLOCK> tag around the next block of code. --------------------------------------------------------> <CFLOCK TIMEOUT="30" THROWONTIMEOUT="Yes" NAME="#Session.SessionID#" TYPE="ReadOnly"> <CFIF NOT ISDEFINED("Session.Started")> <CFSET LOGIN = ""> </CFIF> </CFLOCK> <CFIF ISDEFINED("Login")> <!---------------------------------------------------Since the session.started variable has not yet been set (it is set when the user successfully logs in in the login2.cfm template), the processing of the login2.cfm would be aborted unless the following cfif statement is added -----------------------------------------------------> <CFSET PATH=GETDIRECTORYFROMPATH(#CGI.CF_TEMPLATE_PATH#)> <CFIF (CGI.CF_TEMPLATE_PATH IS NOT "#path#login.cfm") AND (CGI.CF_TEMPLATE_PATH IS NOT "#path#login2.cfm")> <CFINCLUDE TEMPLATE="login.cfm"> <!-----------------------------------------------Aborts processing of any template except login.cfm and login2.cfm until user has logged in -------------------------------------------------> <CFABORT> </CFIF> </CFIF>

<CFSET Valid = True> <CFSET Error = > <!--- Check if a name has been provided ---> <CFIF Len(Form.Name) is 0> <CFSET Valid = False> <CFSET Error = Error & A Name is required.<BR>> </CFIF> <!--- Check if a phone number has been provided ---> <CFIF Len(Form.Phone) is 0> <CFSET Valid = False> <CFSET Error = Error & A Phone Number is required.<BR>> </CFIF> <!--- Check if the phone number is valid ---> <CFIF (Len(Form.Phone) is not 0) and (not IsNumeric(Replace(Form.Phone,-,)) or Len(Replace(Form.Phone,-,)) is not 7)> <CFSET Valid = False> <CFSET Error = Error & The Phone Number is invalid.<BR>> </CFIF> <!--- Check if the e-mail address is valid ---> <CFSET Dot = 0> <CFSET At2 = 0> <CFSET At = Find("@",Form.Email)> <CFIF At greater than 0> <CFSET At2 = Find("@",Form.Email,At+1)> <CFSET Dot = Find(".",Form.Email,At+1)> </CFIF> <CFIF (Len(Form.Email) is not 0) and (At is 0 or At2 greater than 0 or Dot is 0)> <CFSET Valid = False> <CFSET Error = Error & The E-mail Address is invalid.<BR>> </CFIF> <!--- Check if the form is valid or not ---> <CFIF not Valid> <STRONG>Sorry. An error occurred.</STRONG><HR> <CFOUTPUT>#Error#</CFOUTPUT> <EM>Please correct the error</EM> <FORM METHOD=POST ACTION=submit.cfm> <TABLE BORDER=0 CELLPADDING=5> <TR> <TD>Name</TD> <TD><INPUT TYPE=TEXT NAME=Name SIZE=30 MAXLENGTH=50></TD> </TR> <TR> <TD>Phone</TD> <TD><INPUT TYPE=TEXT NAME=Phone SIZE=8 MAXLENGTH=8></TD> </TR> <TR> <TD>E-mail</TD> <TD><INPUT TYPE=TEXT NAME=Email SIZE=20 MAXLENGTH=30></TD> </TR> <TR>

<TD></TD> <TD><INPUT TYPE=SUBMIT></TD> </TR> </TABLE> </FORM> <CFELSE> <!--- Place normal form-processing code here ---> <H1>The Form is Valid!</H1> </CFIF>

<HTML> <HEAD> <TITLE>Sending Your Greeting</TITLE> </HEAD> <BODY> <CFIF Form.to is not ""> <CFMAIL TO="#Form.to#" FROM="address@some.host" SUBJECT="A Greeting"> Hi! This is a quick, computer-generated greeting sent to You courtesy of #Form.name# and the CFMAIL tag. </CFMAIL> <H1>Message Sent</H1> <CFOUTPUT> <P>Your message to #Form.to# has been sent </P> </CFOUTPUT> <CFELSE> <H1>Oops </H1> <P>You need to provide an E-mail address for the recipient. Hit the Back button to return to the form and provide one. Thanks.</P> </CFIF> </BODY> </HTML>

<HTML> <HEAD> <TITLE>Job Scheduled</TITLE> </HEAD> <BODY> <CFSCHEDULE ACTION="Update" TASK="#Form.username#-#Form.report#" OPERATION="HTTPRequest" URL="http://cold.fusion.server/reports/#Form.report#.cfm" FILE="#Form.report#-results" PATH="\\homedirserver\#Form.username#\" PUBLISH="Yes" STARTDATE="#dateformat(now(),mm/dd/yy)#" STARTTIME="23:00" ENDDATE="#dateformat(now(),mm/dd/yy)#" ENDTIME="" INTERVAL="Daily"> <H1>Job Scheduled</H1> <HR> <CFOUTPUT> The report #Form.report#.cfm has been scheduled to run tonight at 11:00 p.m. for #Form.username#. </CFOUTPUT> <P> Click <A HREF="form.html">here</A> to schedule another report. </BODY> </HTML>

Security
ColdFusion provides three tags for enforcing security of an application. These tags work with a directory of usernames and passwords for authentication and authorization to access certain resources. To establish security you must: 1. Specify a secure server (the ColdFusion Server in our case). 2. Specify a user directory to contain a list of users and groups of users to specify permissions to specific resources. This is done through the ColdFusion Administration Page. 3. Define a security context. A security context defines a cohesive group of resources and their security information. This is done through the ColdFusion Administration Page. 4. Associate User Directory with a Security Context. This is done through the ColdFusion Administration Page. 5. Define Security Rules. Rules define what actions are available on which resources. This is done through the ColdFusion Administration Page. 6. Create a Security Policy that defines what user(s) are covered by what policies. This is done through the ColdFusion Administration Page. 7. In the Application.cfm page use the appropriate tags to authenticate users.

Tags
CFAUTHENTICATE checks a username and password combination against a given security context. Once checked, you can use the IsAuthenticated and IsAuthorized tags to obtain results. You would use the CFAuthenticate tag in the application.cfm page since this page is accessed before all templates.
<CFAUTHENTICATE SECURITYCONTEXT=HumanResourceSalary USERNAME=User name goes here PASSWORD=Password goes here>

The IsAuthenticated function is used to check if a user is authenticated. The function returns either True or False. Obviously, you could use IsAuthenticated to advantage with a CFIF tag. The IsAuthorized tag is used to secure specific resources based on the access policies created in the security context.
IsAuthorized (ResourceType, ResourceName, Action)

Resource type must match a resource in the security context definition. It can be: Application, CFML, File, Component, Collection, CustomTag, or UserObject.

Actions depend on the resource type since not every action is possible with every resource. For example, for a File actions can be Read or Write. You are referred to the CF manual for further details. Example Application.cfm listing
<!--- CHECK FOR A USERNAME ---> <CFPARAM name=HaveUsername default=Yes> <CFIF IsDefined("Cookie.Username")> <CFSET USERNAME=Cookie.Username> <CFELSE> <CFSET USERNAME=""> <CFIF IsDefined("Form.Username")> <CFSET USERNAME=Form.Username> <CFCOOKIE NAME="username" VALUE="#Form.Username#"> <CFELSE> <CFSET HaveUsername = "No"> </CFIF> </CFIF> <!--- CHECK FOR A PASSWORD ---> <CFPARAM name=HavePassword default=Yes> <CFIF IsDefined("Cookie.Password")> <CFSET PASSWORD=Cookie.Password> <CFELSE> <CFSET PASSWORD=""> <CFIF IsDefined("Form.Password")> <CFSET PASSWORD=Form.Password> <CFCOOKIE NAME="password" VALUE="#Form.Password#"> <CFELSE> <CFSET HavePassword = "No"> </CFIF> </CFIF> <!--- CHECK AUTHENTICATION STATUS AND IF NOT AUTHENTICATED HANDLE IT ---> <CFIF NOT IsAuthenticated()> <!--- IF WE HAVE A PASSWORD AND USERNAME, TRY AUTHENTICATING ---> <CFIF HaveUsername and HavePassword> <CFTRY> <CFAUTHENTICATE SECURITYCONTEXT="EmployeeList" USERNAME="#USERNAME#" PASSWORD="#PASSWORD#" SETCOOKIE="Yes"> <!--- IF AN EXCEPTION IS THROWN, HANDLE IT ---> <CFCATCH TYPE="Security"> <CFCOOKIE NAME="username" VALUE="" EXPIRES="NOW"> <CFCOOKIE NAME="password" VALUE="" EXPIRES="NOW"> <CFLOCATION URL="index.cfm"> </CFCATCH>

</CFTRY> </CFIF> <!--- OUTPUT A LOGIN FORM ---> <FORM ACTION="index.cfm" METHOD="POST"> Username: <INPUT TYPE=text NAME="username"><BR> Password: <INPUT TYPE=password NAME="password"><BR> <INPUT TYPE=submit VALUE="LOGIN"> </FORM> <CFABORT> </CFIF> <!--- USER IS AUTHENTICATED, SO WE CONTINUE ---> <CFAPPLICATION NAME="admin">

<CFSET Valid = True> <CFSET Error = > <!--- Check if a name has been provided ---> <CFIF Len(Form.Name) is 0> <CFSET Valid = False> <CFSET Error = Error & A Name is required.<BR>> </CFIF> <!--- Check if a phone number has been provided ---> <CFIF Len(Form.Phone) is 0> <CFSET Valid = False> <CFSET Error = Error & A Phone Number is required.<BR>> </CFIF> <!--- Check if the phone number is valid ---> <CFIF (Len(Form.Phone) is not 0) and (not IsNumeric(Replace(Form.Phone,-,)) or Len(Replace(Form.Phone,-,)) is not 7)> <CFSET Valid = False> <CFSET Error = Error & The Phone Number is invalid.<BR>> </CFIF> <!--- Check if the e-mail address is valid ---> <CFSET Dot = 0> <CFSET At2 = 0> <CFSET At = Find("@",Form.Email)> <CFIF At greater than 0> <CFSET At2 = Find("@",Form.Email,At+1)> <CFSET Dot = Find(".",Form.Email,At+1)> </CFIF> <CFIF (Len(Form.Email) is not 0) and (At is 0 or At2 greater than 0 or Dot is 0)> <CFSET Valid = False> <CFSET Error = Error & The E-mail Address is invalid.<BR>> </CFIF> <!--- Check if the form is valid or not ---> <CFIF not Valid> <STRONG>Sorry. An error occurred.</STRONG><HR> <CFOUTPUT>#Error#</CFOUTPUT> <EM>Please correct the error</EM> <FORM METHOD=POST ACTION=submit.cfm> <TABLE BORDER=0 CELLPADDING=5> <TR> <TD>Name</TD> <TD><INPUT TYPE=TEXT NAME=Name SIZE=30 MAXLENGTH=50></TD> </TR> <TR> <TD>Phone</TD> <TD><INPUT TYPE=TEXT NAME=Phone SIZE=8 MAXLENGTH=8></TD> </TR> <TR> <TD>E-mail</TD> <TD><INPUT TYPE=TEXT NAME=Email SIZE=20 MAXLENGTH=30></TD> </TR> <TR>

<TD></TD> <TD><INPUT TYPE=SUBMIT></TD> </TR> </TABLE> </FORM> <CFELSE> <!--- Place normal form-processing code here ---> <H1>The Form is Valid!</H1> </CFIF>

You might also like