Most commercial Web sites have secure areas that are accessible only to authorized users. Here's one schema for managing access control for a Web site.
Many times you need to limit access to particular templates on your site, either for customers who must purchase enhanced capabilities or for administrative functions available to a select few. The framework described in this article gives you a flexible access control scheme that can easily be added to your Web site.
Database Design
Like all good dynamic systems, this one starts with the database design. It boils down to two simple concepts: users and permissions, where permissions regulate access to various features. We'll have two main tables in our schema: USERS and PERMISSIONS.
The USERS table contains information about the users such as their login name and password. The PERMISSIONS table contains a list of permissions that govern which features a user may or may not access. Each user can be assigned numerous permissions so we need an additional table, USER_PERMISSIONS, to represent this many-to-many relationship (see Figure 1).
This structure gives us a great deal of flexibility. We may only want to define permissions to distinguish between administrative and normal users, or we may want a finer-grained approach with permissions for each ColdFusion template on our site. With this database design we can define as many permissions as we need.
Using Session Variables
We've defined our permissions, but how do we use them? This is where our old friend the session variable comes into play. Typically, when you log in we set a flag in a session variable to track your login. We'll add an additional variable to your session that keeps a list of your permissions. Once this session variable is set, we can check it in our templates to see if you have access.
Code Walk-Through
The two steps to implementing this permission framework in ColdFusion are:
Checking for permissions in our template is straightforward. We examine the list of permissions in your session variable to see if it contains the one needed to access this template. If the permission isn't found, we display a message stating this, then we stop the remainder of the template from running.
<CFIF ListFind(Session.permissions, "Admin") IS 0>We can also use the permissions in other ways. For instance, we may not want to display links to pages you don't have permission to access. In the following example we'll show the link to the administrative report only if you have the "Admin" permission.
<CFINCLUDE TEMPLATE="NoAccessMessage.cfm">
<CFABORT>
</CFIF>
<CFIF ListFind(Session.permissions, "Admin") IS 1>Conclusion
<A HREF="AdminReport.cfm">Administrative Report</A>
</CFIF>