Many websites employ user authentication to control access to all or some of their pages. For the ColdFusion and PHP server models, Dreamweaver has an easy-to-use set of User Authentication server behaviors. These include signing users up, logging them in and out, and restricting access to those who haven't logged in.
The User Authentication tools are available for ColdFusion, PHP, ASP, and JSP server models, but not for ASP.NET. Rather than using scripts on each page to check users' access to a particular page, like the other server models, ASP.NET uses application-wide and directory-wide configuration files to secure access to different parts of your site. This topic is beyond the scope of this book. For complete coverage of user authentication, check out ASP.NET Development with Macromedia Dreamweaver MX from Peachpit Press or Macromedia Dreamweaver MX 2004 and Databases from New Riders.
Enabling Sessions for ColdFusion
User authentication systems rely on session managementkeeping track of the sessions of each user visiting your site. If you're using ColdFusion, you need to explicitly enable sessions for your web application (your site) before your user authentication will work. To enable sessions, create an empty file called Application.cfm (be sure to start it with a capital A) and upload it to your web server as part of your site. Put the following code in the file:
The first line of this code assigns your web application a name. You can substitute your own one-word name for myApp . The last line specifies that the session will end after 20 minutes of user inactivity. You can change that time by entering a different value in place of the 20 .
This is only the bare beginnings of what you can do with the Application.cfm file . For more information, check out Bryan Ashcraft's tutorial "Enabling Session Variables in ColdFusion," available at http://www.communitymx.com.
Signing up a user, or adding him or her to the login system, is just a matter of creating a form and using it to insert a new record into the database. This was covered in Chapter 22, "Creating Dynamic Pages." To prevent duplicate usernames, the Check for Duplicate Username behavior is also available.
To set up a user sign-up page, do the following:
Plan your setup. Determine where the user should be redirected if the sign-up is successful or if it's not. Create those pages in advance.
In your database, create a table to hold user information, including username and password, as well as a unique ID.
ColdFusion users should enable sessions on the server by creating the Application.cfm file. See the preceding sidebar, "Enabling Sessions for ColdFusion," for details.
Create a dynamic page and build a form for collecting this information from visitors . If your page requires database recordsets for any of its display, add them now. (No recordset is required to add a user.)
Select the form. From the Server Behaviors panel or the Application Insert bar, choose Insert Record. You see the dialog box shown in Figure 23.24. Align each form field with a database field. Also assign the page that users will be sent to on successful signup .
Figure 23.24. The Insert Record dialog box for entering a new user into the system.
From the Server Behaviors panel, choose User Authentication > Check New Username. When the dialog box opens, specify which field must be unique and what page to redirect the user to if a duplication is found.
Exercise 23.4. Creating a User Registration Page for the Antiques Barn Site (ColdFusion and PHP)
The Antiques Barn has turned into a members -only site, so now users need to sign in to browse the catalog. The first step in setting this up is presenting users with a sign-up page. In this exercise, you'll build the Antiques Barn membership sign-up page. Before starting this exercise, you need to have completed at least Exercise 23.1, which defines the site and builds the main template.
Three pages are involved in the sign-up: the sign-up page itself, a thank-you page for successful submission, and a sorry page for errors. All three are in your site folder (with the relevant filename extensions). Start by opening the sign-up page ( signup.cfm and so on). Apply the main template to it, putting all body content in the maincontent region.
While you're here, take a moment to examine the form fields in the file. Select each field. You see that the text fields have names such as fname, lname, email, and pword. The drop-down menu is called favorite. These names match the field names in the database's customers table. Although it's not necessary to match form field names and database field names , it's a good convention to use, and it will come in handy when you fill out the Insert Record dialog box.
The form needs a dynamic drop-down menu that displays the antique categories in the database. This means collecting a recordset. In the Bindings panel, click the + button, and choose Recordset (Query). Collect all fields from the categories table, ordered by name, as shown in Figure 23.25.
Figure 23.25. Collecting the recordset for displaying antique categories.
(Recalling a similar exercise task from Chapter 22, can you tell why you don't have to worry about collecting only a single instance of each different category? In the revised database structure, categories have their own table, which lists each category once. So no use of the DISTINCT keyword is necessary.)
Select the Favorites menu. In the Property Inspector, click the Dynamic button to open the Dynamic List/Menu dialog box, shown in Figure 23.26. Leave the static option at (select one). For the dynamic values, choose the category name as the label and the category ID as the value. The name is what the user needs to see, but the ID is what the database needs to store as this user's favorite kind of antique.
Figure 23.26. Setting up the dynamic list of favorite categories for the Antiques Barn sign-up page.
The form is now set up. The next step is to submit the form and add a new user to the database. In the Server Behaviors panel, click the + button and choose Insert Record. When the dialog box shown in Figure 23.27 opens, choose to insert this record into the customers table of the more_antiques database. The field names should automatically match up to database fields because they've been named to match database field names. The id database field doesn't have a matching record, but it is automatically assigned by the database.
Figure 23.27. Settings for inserting a new user into the customers table.
Before closing this dialog box, choose the thankyou page ( thank-you.cfm and so on) in the After inserting, go to field. Then click OK.
You don't want two matching usernames, so you also need to check for duplicates before processing the record. From the Server Behaviors panel, click the + button and choose User Authentication > Check New Username. When the dialog box opens, choose username as the field that must be unique, and enter the sorry page ( sorry.cfm and so on) to redirect to if the name isn't unique. Click OK to close the dialog box.
Try it out! Preview it in a browser. Try creating a new user, and also try submitting the form without any data and being redirected to the sorry page by entering a username that's already in use (fred is being used, so try giving yourself that username). When the sorry page appears, notice the URL for the pagea URL parameter containing the problematic username has been appended.
This means that you can easily dress up the sorry page with some personalized information. Open the sorry page. In the Bindings panel, click the + button and choose URL Parameter. For the parameter name, enter the same name that appeared in the sorry page URL: requsername . When you close the dialog box, the parameter appears as one of your page's data bindings. (Note that you can also apply the main template to this page to dress it up further. You can do the same to the thankyou page if you're so inclined.)
In the Document window, select the word USERNAME. Then select the requsername parameter from the Bindings panel, and click Insert (at the bottom of the panel). Your sorry document should now look like the one shown in Figure 23.28.
Figure 23.28. Using the requsername URL parameter to create dynamic text.
After a user has signed up and is in the database, he or she needs to be able to log in, which requires a login page. This involves creating another form and applying the Log In User behavior.
To create a login page, do the following:
Plan your setup. Determine where the user will be redirected if he logs in successfully and where he will be sent if his login is unsuccessful . Create these pages in advance.
Create a new dynamic page, and build a form containing fields for username and password and a Submit button. If any recordsets are required for other parts of this page, collect them now.
Select the form and, from the Server Behaviors panel, choose User Authentication > Log In User. In the dialog box that appears, shown in Figure 23.29, choose the form fields to validate from and the database fields to validate against. (This is easiest if you've named things carefully !) Then assign the redirection destinations for successful and unsuccessful login.
Figure 23.29. The dialog box for the Log In User behavior.
Exercise 23.5. Creating a User Login Page (ColdFusion and PHP)
In this exercise, you continue building the user sign-up system by adding a login page. You must have completed Exercise 23.4 before attempting this one.
Start by opening the login page ( login.cfm and so on). This file contains a form with a username and password field and an image being used as a Submit button. To make it look its best, apply the main template, putting all body content in the maincontent area.
Add the login script. From the Server Behaviors panel, choose User Authentication > Log In User. In the dialog box that appears, match your settings to those shown in Figure 23.30. Note that if login is successful, the user is merrily sent along to the catalog page. If it fails, the user stays on the current page.
Figure 23.30. Log In User settings for the Antiques Barn login page.
Check things out in a browser. If you've already signed yourself up (and therefore added your name to the database), use the username and password you signed in with. If not, use fred and fred. If you enter everything correctly, you'll be sent to the catalog page.
There's not much point in requiring users to log in if it doesn't affect their ability to see things on your site. As soon as the login system is in place, restricting access to certain pages makes use of it. In Dreamweaver, the Restrict Access to Page behavior accomplishes this. You should apply this behavior to any page in the site that should be seen only by authenticated users.
To restrict access to a page, follow these steps:
Plan your setup. What should happen if an unauthorized user tries to access the page? Where should he or she be redirected? Create this page if necessary.
Open a dynamic page. The behavior is added to the page as a whole, so you don't need to select anything.
From the Server Behaviors panel, choose User Authentication > Restrict Access to Page. In the dialog box that appears, restrict access based on username and password, and assign the page that the user is redirected to if he doesn't have access.
Remember to repeat this process for all restricted pages, not just the main entrance page. In the normal course of browsing, of course, users can't get to any internal pages except through the main page. But that won't stop someone from typing the detail page's URL directly into the browser address field and viewing the page that way. If you really want your site to be restricted, you have to restrict more than just the main entry page.
For security purposes, it's good to give users a chance to explicitly log themselves out. That's as simple as attaching a Log User Out server behavior to a logout text link or button. Because only logged-in users can log out, these logout actions should be placed on restricted pages.
To create a logout system, do the following on every restricted page:
Plan the setup. Determine where the user should be redirected when he logs out. (He can't stay here on the restricted page!) This might be a page that says, "You have been logged out," it might be the login page, or it might just be the site's main unrestricted page. Create the page if it doesn't already exist.
Determine where in your page layout you want the logout link to appear, and add it.
Select the link (text link or linked image). From the Server Behaviors panel, choose User Authentication > Log User Out. In the dialog box that appears, choose to log the user out when he clicks the selected link (this option should be set by default if you had a link selected when you chose the behavior). Assign a page to redirect the user to on successful logout.
Remember, users also automatically log out if they don't interact with any of your site's pages within a certain amount of time or if they quit their browsers.
Exercise 23.6. Creating Restricted Access Pages (ColdFusion and PHP)
Only Antiques Barn subscribers are allowed to browse the antiques catalog. This means that the catalog and catalogdetail pages must be restricted to logged-in users. In this exercise, you'll add restricted-access scripts to both of those pages.
Start by opening the catalog page. In the Server Behaviors panel, click the + button, and choose User Authentication > Restrict Access to Page. When the dialog box opens, choose to restrict based on username and password. If access is denied , go to the login page. Click OK to close the dialog box.
Users also like the opportunity to log out. To add this, you need to edit the main template. Open the main file (from the Templates folder in the Files list, or from the Assets panel), and insert a new editable region in the left margin cell . Call this region sidebar , as shown in Figure 23.31. Save the template and close it, letting it update all pages.
Figure 23.31. Adding a new editable region to the main template.
Back in the catalog page, place the cursor in the new sidebar region, and insert the logout.gif image (in the images folder).
With this image selected, go to the Server Behaviors panel, and choose User Authentication > Log Out User. On logout, redirect the user back to the login page.
Check things out in a browser. If you've been practicing logging yourself in, quit your browser and relaunch it to start a new session. Then try visiting the catalog page without logging in. You should go directly to the login page.
For full security, you should also restrict access to the catalogdetail page. For this exercise, you can skip this extra step if you like. But if you want to protect the detail page, open it and repeat what you did in steps 1 and 2.