NO MORE CAREER
POLITICIANS!
Get Out Of Our House: Replacing congress with TRUE citizens!
Contact Doug!
Learn About Doug!
View Doug Boude's online resume
updated 11/18/2009

View Doug Boude's profile on LinkedIn
Link to me!

Follow Doug Boude on Twitter
Follow me!

Be Doug's friend on Facebook
Befriend me!
(I promise not to follow you home)
OO Lexicon
Chat with Doug!
Recent Entries
You may also be interested in...
Web Hosting

best web hosting - top web hosting sites, thetop10bestwebhosting.com

Czech your Page Rank!
Check Page Rank of any web site pages instantly:
This free page rank checking tool is powered by Page Rank Checker service
Surf's Up!
Visit Egosurf.org and massage YOUR web ego!
My Score: 9,001
Doug's Books

Read (and recommend)

  • Men are from Mars, Women are from Venus
  • The Wisdom of Crowds: Why the Many Are Smarter Than the Few and How Collective Wisdom Shapes Business, Economies, Societies and Nations
  • Blink: The Power of Thinking Without Thinking
  • Head First Design Patterns
  • Transact-SQL Programming
  • What's So Amazing About Grace?
  • Just So Stories (Rudyard Kipling collection)

Reading

  • Prayer: Does it Make Any Difference?
  • Data Mining (Practical Machine Learning Tools and Techniques)
<< November, 2008 >>
SMTWTFS
1
2345678
9101112131415
16171819202122
23242526272829
30
Search Blog

Recent Comments
Re: Using Google as your CF Mail Server (by Mike at 9/07 4:02 PM)
Re: Viewing Option Text (in IE7) that's Wider than the Select List (by Nithin Chacko Ninan at 9/07 1:34 AM)
Re: Viewing Option Text (in IE7) that's Wider than the Select List (by Nithin Chacko Ninan at 9/07 1:33 AM)
Re: Configuring Apache To Use Multiple Versions of ColdFusion (by Lola LB at 9/06 6:28 AM)
Re: Configuring Apache To Use Multiple Versions of ColdFusion (by ComboFusion at 9/06 5:17 AM)
Re: Railo 3.1 on Windows Server 2008 and IIS7 - Part 3 of 3 (by Jon at 8/27 2:04 PM)
Re: Hosts File Changes Not Acknowledged on Vista 64 (by Spacy at 8/24 3:46 PM)
Re: THE DAY CFUNITED DIED (by ComboFusion at 8/23 10:50 AM)
Re: My Grandpa (by Tasha at 8/10 4:29 PM)
Re: Just What IS a 'Service Layer', Anyway? (by dougboude at 8/02 10:10 AM)
Categories
Archives
Photo Albums
Funnies (5)
Family (3)
RSS

Powered by
BlogCFM v1.11

09 November 2008
Basic Security in Coldbox using Transfer and Coldspring - Part II (of II)
wiring and autowiring

In the first post on this subject, I shared my 10,000 foot view of what pieces needed to go where in a Coldbox app in order to implement security. A lot of the code in that post was probably unfamiliar looking to many people (I know it would have been to me a couple of days ago!). So in this post I want to share how I implemented Transfer and Coldspring in the security process, clarify what some of that code was doing, and whatever other details about it I may have also come to know.

I'm assuming that you already know what Coldspring is, what Transfer is, and the basics of an event-driven framework. For example, Coldspring is a framework that allows you to manage the relationships between your CFCs (CFC A needs a configuration bean injected into it, the configuration bean needs to be initialized with parameter X, etc.); Transfer is an ORM framework that stands between you and your database (in a good way) and lets you write your code "sans SQL"; and the basics of event-driven frameworks is that they have core components built into them that allow you (via the methods they expose to you) to reach into their very soul and leverage "core functionality", like retrieving global configuration settings, retrieve system beans, etc. Okay, all that having been said, here's the dialogue I had with my frameworks in order to get them all on the same page of the workbook (Personification to be followed up with real code snippets, don't worry. It just helps me simplify things when I animate the inanimate.  ):

1. "Hey, Coldbox;(via Coldbox.xml.cfm...) I'm using Coldspring to manage my components for me. What's that? You'll make your configuration settings available to Coldspring to use in its XML configuration file? When you fire up Coldspring you'll go through its configuration XML and replace any curly-braced variables with matching values from your own configuration BEFORE you initialize Coldspring? Aw, that's sweet. Thanks!"

2. "Hey Coldspring;(via Coldspring.xml.cfm...) I'm gonna need you to produce a few objects from our host MVC framework's core, Okay? What objects would those be? Oh, well, I'll be needing the Coldbox factory object since that's how you'll need to retrieve the rest of the framework's objects for me. I'll need you to ask the Coldbox Factory for an instance of the Coldbox framework itself since it has all the core methods that many of my model object will need; and I'll want a discrete instance of the Coldbox SessionStorage plugin as well so that my model objects can access my app's persistent scope. Let's see, what else...oh yes, I'll be using an ORM, so i'll need you to produce an instance of Transfer via its own factory. And then I'll just tell you about my model objects as I get them added to the app. Thanks, Coldspring! You're a real bud."

3. "Hey Transfer,(via Transfer.xml.cfm...)  I got a whole BOATLOAD of database objects I need you to make available to me. It's a very, very long list, so just read through it at your leisure."

My frameworks are very good listeners and so once I figured out exactly how to say what I wanted to say, they complied fully with my desires. So let's look at how I made them understand, shall we?

Dialogue 1
Within the Coldbox.xml.cfm file, in the <Settings> section, I made sure the following settings were like so:

<Setting name="IOCFramework" value="Coldspring" />
<!--IOC Definition File Path, relative or absolute -->
<Setting name="IOCDefinitionFile" value="config/coldspring.xml.cfm" />
<!--IOC Object Caching, true/false. For ColdBox to cache your IoC beans-->
<Setting name="IOCObjectCaching" value="false" />

 

As far as the rest of that dialogue, as long as I make sure the setting exists within the Coldbox.xml.cfm file, Coldbox will automatically replace any curly-braced variables in my Coldspring.xml.cfm file for me. For instance, in my Coldbox.xml.cfm file in the <YourSettings> section, I have the following Transfer values:

<YourSettings>
 <Setting name="TransferSettings.datasourcePath" value="/emailmanager/config/datasource.xml.cfm" />
 <Setting name="TransferSettings.configPath" value="/emailmanager/config/transfer.xml.cfm" />
 <Setting name="TransferSettings.definitionPath" value="/emailmanager/model/definitions" />
</YourSettings>

You'll see in the Coldspring snippets below the variable placeholders that correspond to these settings; it'll make more sense there. 

 (Note: presently, only curly-brace variables found within a <value>${myColdboxSetting}</value> tagset will be replaced. Don't put curly-brace vars in your bean's class path, for instance, and expect them to work. There is a way to do this which I'm investigating now, but by default it does not.)

Dialogue 2
We informed Coldspring of several different things, so let's look at them a chunk at a time.
"...produce a few objects from our host MVC framework's core...Coldbox factory object...Coldbox framework itself...a discrete instance of the Coldbox SessionStorage plugin...." Here is the XML to accomplish the previous:

<bean id="ColdboxFactory" class="coldbox.system.extras.ColdboxFactory" />
<bean id="Coldbox" factory-bean="ColdBoxFactory" factory-method="getColdbox" singleton="true" />
<bean id="oSession" factory-bean="ColdBoxFactory" factory-method="getPlugin" singleton="true">
 <constructor-arg name="plugin">
  <value>sessionstorage</value>
 </constructor-arg>
</bean>


If you aren't familiar with Coldspring's ability to produce a bean by executing a method referenced on a previously defined bean, well, you're looking at it in action (note the 'factory-bean/factory-method' attributes). I myself wasn't aware of this ability, so was quite happy to have discovered it. First we're defining Coldbox's object factory; then we're creating an instance of Coldbox by calling the Factory's "getColdbox" method; lastly I'm grabbing an instance of Coldbox's built-in "sessionStorage" plugin the same way, calling the generic "getPlugin" method and passing in the name of the plugin I want.

Next portion of that dialogue...
"...I'll be using an ORM, so i'll need you to produce an instance of Transfer via its own factory...." Here's that code (notice the curly brace vars; each one equates to a setting created in the Coldbox.xml.cfm file): 

<bean id="transferFactory" class="transfer.TransferFactory" singeleton="true">
 <constructor-arg name="datasourcePath">
  <value>${TransferSettings.datasourcePath}</value>
 </constructor-arg>
 <constructor-arg name="configPath">
    <value>${TransferSettings.configPath}</value>
 </constructor-arg>
 <constructor-arg name="definitionPath">
    <value>${TransferSettings.definitionPath}</value>
 </constructor-arg>
</bean>

<bean id="Transfer" factory-bean="TransferFactory" factory-method="getTransfer" singleton="true" />
<bean id="Datasource" factory-bean="TransferFactory" factory-method="getDatasource" singleton="true" />

Defining Transfer's own factory, then defining the other Transfer beans as results of executing Transfer Factory methods. Noice, eh?

 

 As far as the model, so far I have only one bean defined, and that is my "authenticationService" bean. Here's that Coldspring.xml:

<bean id="authenticationService" class="emailmanager.model.services.authenticationservice">
 <constructor-arg name="transfer">
  <ref bean="Transfer" />
 </constructor-arg>
 <constructor-arg name="oSession">
  <ref bean="oSession" />
 </constructor-arg>
</bean>

As you can see, I'm passing in an instance of Transfer and Coldbox's session manager upon instantiation. By doing so, my service object can perform database calls and manage persistent values.

 

 Dialogue 3
Transfer relies on an XML file to get its information about your database entities (tables) and their relationships to one another. I won't share the entire Transfer.xml.cfm file here since I've already got most of my entities defined for my app (long list), but here are the tables relevant to security:

<objectDefinitions>
 <package name="user">
  <object name="user" table="appuser" >
   <id name="id" type="string" generate="false"/>
   <property name="username" type="string" column="username" nullable="false"/>
   <property name="password" type="string" column="password" nullable="false"/>
   <property name="firstname" type="string" column="firstname" nullable="false"/>
   <property name="lastname" type="string" column="lastname" nullable="false"/>
   <property name="email" type="string" column="email" nullable="false"/>
   <property name="isActive" type="boolean" column="isActive" nullable="false"/>
   <property name="timezone" type="string" column="timezone" nullable="true"/>
   <onetomany name="usergroup" lazy="true">
       <link to="usergroup.usergroup" column="userid"/>
       <collection type="array">
         <order  property="id" order="asc"/>
       </collection>
   </onetomany>
  </object>
 </package>
 <package name="usergroup">
  <object name="usergroup" table="usergroup" >
   <id name="id" type="string" generate="false"/>
   <property name="groupid" type="string" column="groupid" nullable="false"/>
  </object>
 </package>
</objectDefinitions>

Now that I have all of that set up, let me share again the code from my authentication handler(controller) and authenticationService cfc (that I shared in my previous post on this topic)  that peform the login function.

 

 authentication handler

<cffunction name="doLogin" access="public" returntype="void" output="false">
 <cfargument name="Event" type="any" />
 <cfset var loggedin = "" />
 <cfset var rc = arguments.Event.getCollection() />
 <!--- attempt to authenticate using the credential supplied... --->
 <cfset loggedin = variables.authenticationService.login(username=rc.username,password=rc.password) />
 <cfif not loggedin><!--- login failed...send them back --->
  <cfset arguments.event.setValue("loginmessage","Login Failed. Please try again.") />
  <cfset arguments.event.setValue("loggedin",false) />
  <cfset arguments.event.overrideEvent("login") />
 <cfelse>
  <cfset arguments.event.setValue("loggedin",true) />
 </cfif>
 <cfset arguments.event.setvalue("xe.frmAction","authentication.doLogout") />
 <cfset arguments.event.setView("login") />
</cffunction>

The line to home in on is the one that begins "<cfset loggedin = ...". It is there that, from within my handler, I am accessing the authenticationService bean we defined in Coldspring.xml.cfm. You'll recall though that I did NOT define a relationship between my handler and authenticationService. How then did my handler get access to it?

In Model-Glue, we would have provided our controller a setter and getter for the authentication service, then Model-Glue itself would have auto-injected that bean for us. Well, Coldbox to the rescue, we have the same type of functionality available to us! Coldbox actually allows two ways to auto-inject Coldspring-defined beans: via setters and getters, as we are probably accustomed to; and via the <cfproperty> tag. Now, typically cfproperty doesn't really do much for us at all; but in a Coldbox handler it's a big ol' flag that says "inject it here! inject it here!. Okay, here's the additional line in our authentication handler that performs this magic:

<cfproperty name="authenticationService" type="ioc" scope="variables" />

I opted NOT to go the setter and getter route because of the fact that if I happened to have created a setter and getter that had the same name as a bean i defined, it would attempt to auto-inject whether I really wanted it to or not. In order to avoid this, I am choosing to explicitly name my auto-injections via the <cfproperty> tag. 

Okay, so our doLogin event is calling the authenticationService's 'login' method, passing in the username and password supplied; Let's look at authenticationService now.

<cffunction name="init" access="public" output="false" returntype="any">
 <cfargument name="transfer" type="any" required="yes" />
 <cfargument name="oSession" type="any" required="yes" />
 <cfset variables._transfer = arguments.transfer />
 <cfset variables._session = arguments.oSession />
 <cfreturn this />
</cffunction>

<cffunction name="login" access="public" returntype="boolean">
 <cfargument name="username" type="string" required="yes" />
 <cfargument name="password" type="string" required="yes" />
 <cfargument name="isActive" type="boolean" required="yes" default="true" />
 <!--- create a transfer user bean, passing in the username and password, then give it back --->
 <cfset var objUser = variables._transfer.readByPropertyMap("user.user",arguments) />
 <cfset retval = false />
 <cfif objUser.getID() IS "0"><!--- login failed... --->
  <cfset variables._session.setVar("loggedin",false) />
 <cfelse>
  <cfset variables._session.setVar("loggedin",true) />
  <cfset variables._session.setVar("user",objUser) />
  <cfset retval = true />
 </cfif>
 <cfreturn retval />
</cffunction>

 We instructed Coldspring to inject Transfer and oSession into this bean upon creation, and made provision for it via the init method. Pretty standard Coldspring stuff. In our login method, we call upon Transfer to create for us the "user.user" bean, giving it our argument collection to use as criteria (my arguments are named exactly as fields in that table). Also, in case you're wondering why we didn't ask Transfer for the "user" bean instead of the "user.user" bean, it's because in our Transfer.xml.cfm file we defined a package called "user" and within that package an object named "user". Hence the path "user.user".

 

 So, Transfer will create the requested bean and, if it matched the criteria passed in, the bean will be populated; otherwise it'll be empty, with a zero value for the primary numeric key ("ID"). After Transfer gives it back, I check the primary key. If it's zero, login obviously failed. If it's not, success! Stuff the user bean into session and return a boolean to the handler (controller).

I do hope you were able to follow this okay. I can't tell you how long I had to bang my head against it for it to sink in and gel, so I hope it saves someone else a few hours of digging through docs.

Doug out.

Posted by dougboude at 1:58 AM | PRINT THIS POST! | Link | 7 comments



Basic Security in Coldbox using Transfer and Coldspring - Part I

There's no denying it: the plethora of documentation and examples that exist for the Coldbox framework is invaluable and undoubtedly covers every possible scenario to one degree or another. As I press on into a project where the use of Coldbox, Coldspring, and Transfer has been mandated to me, I'm finding that, despite the documentation and tutorials, I'm still having to search around and piece together for myself some of the information I seek. So, to complement the existing volumes of Coldbox-centric information and for my own personal reference purposes, I'm going to post some of what I'm learning as it becomes coherent to me.  Tonight's post is focused on an overview of how to implement basic security in Coldbox using Transfer and Coldspring. I won't delve much into Transfer or Coldspring with this one (that post will follow soon) so that we can focus on the 10,000 foot view first.

As I mentioned, the first "block of functionality" I tackled was the implementation of security, so let's use that as our illustration. There is a lot of documentation on the subject and even a few example apps I found. But, the documentation left me with too much gray area as I attempted to relate what I read with my current level of understanding of the framework, and the example apps, though they worked wonderfully, didn't explain to me HOW they were working. I had to dissect the apps using my limited knowledge of Coldbox and painstakingly trace the event flow from one area of the framework and application to the next, referring to the documentation and even examining some of the framework's CFCs internally. The end result for me was the foundation for my own "flavor" of basic security implementation, and it this that I share.

First, my own visualization of the Coldbox event lifecycle. I realize that the true lifecycle in all its detail could consume many a diagram page, but for the purposes of someone simply desiring to add in a bit of functionality, I do believe I've illustrated all that is required.

The Coldbox event lifecycle highly simplified

A request comes in and right away Coldbox executes the interceptors it knows about. Interceptors are very aptly named, as they do just that: intercept the request before it gets too far and executes whatever methods are appropriate. In our case, we're interested in knowing right up front if the user attempting to fulfill an http request is authenticated or not. Intercept them, then, we shall.

Coldbox comes out of the box with a pre-built security interceptor (a CFC that is executed at what we typically know as the "onRequestStart" point), but being at the newbie point I am, I found it a bit too deep to assimilate. In order to understand how things really work, therefore, I created my own. I called it "security.cfc" and dropped it into my app's "interceptor" directory. The next step was to tell Coldbox that I have an interceptor in place. This is done in config/coldbox.xml.cfm, in the <Interceptors> section. Mine looks like this:

<Interceptors>
 <Interceptor class="interceptors.security" />
</Interceptors>

I eluded to it, but now is a good time to talk about one of the things that makes Coldbox unique among the MVC frameworks we CFers have to choose from. If you've not used any framework before that relies on what's typically referred to as "convention" (Ruby on Rails, Fusebox 5.x sans xml), then you are used to defining your events down to every last detail: what messages to broadcast, what methods to execute in what CFC, etc. But Coldbox rather follows the "convention" approach, which is simply naming your CFCs and methods in such a way that the framework knows what to do all by its lonesome. This really isn't a new thing to you at all though, because if you've used Application.cfc in any of your apps, then you have practiced this very thing! Consider this...did you ever have to TELL your app to run application.cfc? Nope, because of the fact that you NAMED it application.cfc, the framework (in this case, CF Server) looked for it and executed it. Inside of your application.cfc you had some methods, right? You had one named "onApplicationStart", one named "onRequestStart", one named "onSessionStart", etc. Why? Because you knew that if you named your method appropriately, the "framework" would execute it at just the right time in the http request lifecycle. This is absolutely no different in Coldbox. Inside our interceptors we create methods that are named according to when we want Coldbox to execute them. Granted, Coldbox uses a few names of its own to indicate a specific point in the event lifecycle (such as 'PreProcess'), but they boil down to the same concept as what we're accustomed to with Application.cfc. So, I told Coldbox "hey, I have an interceptor I want you to execute for me at the beginning of the event lifecycle", then within that interceptor I created methods to run at specific points in time. In the case of my Security.cfc interceptor, I have create a single method called "preProcess" (guess when it's going to be executed). Within this method I am checking to see if the current user is logged in. If yes, do nothing; if no, redirect to my login event. In my simple scenario, "logged in" means i found session.loggedin and it was set to 'true'. Here's my interceptor method:

 

 

<cffunction name="preProcess" access="public" returntype="void" output="false">
 <cfargument name="event" required="true" type="coldbox.system.beans.requestContext" />
 <cfset var loggedin = false />
 <cfset oSession = getPlugin("sessionstorage") />
 <cfif (NOT oSession.exists("loggedIn") OR NOT oSession.getVar("loggedIn")) AND listfind("authentication.doLogin",arguments.Event.getCurrentEvent()) eq 0>
  <cfset arguments.Event.setValue("loginmessage","Please Log In") />
  <cfset arguments.Event.overrideEvent("authentication.login") />
 <cfelse>
  <cfset arguments.Event.setValue("message","we're logged in!") />
 </cfif>
</cffunction>

 

 

 

Let's assume the user is NOT logged in. My interceptor resets the current event to my login event, "authentication.login", and processes it. POP QUIZ: Based on the event name "authentication.login", what CFC and method within that CFC do you suppose Coldbox will be executing? I'm sure you guessed right, so let's go look at the 'Login' method within my 'authentication.cfc'.

Hmmm, where IS my authentication.cfc? It's not an interceptor...where is it? Ah, it's where Coldbox ASSUMES it will be (there's that "convention" thing again!): sitting in the "handlers" directory. We Model-Gluers and other MVC framework people might think of it more commonly as "controllers", but the Coldbox vernacular is "handlers", as in "event handlers". Here is the Login method:

<cffunction name="login" access="public" returntype="void" output="false">
 <cfargument name="Event" type="any">
 <cfset arguments.event.setvalue("loginmessage","You need to log in!") />
 <cfset arguments.event.setValue("loggedin",false) />
 <cfset arguments.event.setvalue("xe.frmAction","authentication.doLogin") />
 <cfset arguments.event.setView("footer") />
 <cfset arguments.event.setView("login") />
</cffunction>

 

 

 

Being the good controller/handler that it is, it's doing next to nothing except setting a few values in the event bucket and tossing some views into the view collection so that we can properly give the user a login form.

Now we see the login form, nothing fancy, just a prompt for a username and password. The user enters it, hits the submit button, and off we go to our form's action: authentication.doLogin .

<cffunction name="doLogin" access="public" returntype="void" output="false">
 <cfargument name="Event" type="any" />
 <cfset var loggedin = "" />
 <cfset var rc = arguments.Event.getCollection() />
 <!--- attempt to authenticate using the credentials supplied... --->
 <cfset loggedin = variables.authenticationService.login(username=rc.username,password=rc.password) />
 <cfif not loggedin><!--- login failed...send them back --->
  <cfset arguments.event.setValue("loginmessage","Login Failed. Please try again.") />
  <cfset arguments.event.setValue("loggedin",false) />
  <cfset arguments.event.overrideEvent("login") />
 <cfelse>
  <cfset arguments.event.setValue("loggedin",true) />
 </cfif>
 <cfset arguments.event.setvalue("xe.frmAction","authentication.doLogout") />
 <cfset arguments.event.setView("login") />
</cffunction>

Ignore the details for a moment, and let it suffice to say that we are grabbing the credentials out of the event bucket, submitting them to our model for authentication, and getting back a boolean value indicating success or failure. Again, our controller/handler method is doing next to nothing (as it should), except setting some values for the view to use.

 

 

Wanna see the "login" method in the model?

<cffunction name="login" access="public" returntype="boolean">
 <cfargument name="username" type="string" required="yes" />
 <cfargument name="password" type="string" required="yes" />
 <cfargument name="isActive" type="boolean" required="yes" default="true" />
 <!--- create a transfer user bean, passing in the username and password, then give it back --->
 <cfset var objUser = variables._transfer.readByPropertyMap("user.user",arguments) />
 <cfset retval = false />
 <cfif objUser.getID() IS "0"><!--- login failed... --->
  <cfset variables._session.setVar("loggedin",false) />
 <cfelse>
  <cfset variables._session.setVar("loggedin",true) />
  <cfset variables._session.setVar("user",objUser) />
  <cfset retval = true />
 </cfif>
 <cfreturn retval />
</cffunction>

We're passing it two parameters and setting a third by default, then passing those parameters to Transfer to see if it can successfully populate a User bean with them. If yes, store the user bean to session so we can utilize it other places and return a boolean 'true'; if not, store the empty user object to session (in case we still want to use it somewhere else...at least we know it will exist) and return a boolean false.

 

 

That's it in a nutshell! If I were me looking at this post two days ago, however, I would be very hungry to know the details of how I set up Coldspring and Transfer to play together, and how it is I am accessing my session scope and Transfer from within my model. In order to encapsulate the purpose of this post (give an overview of basic application flow for the purpose of implementing security), however, I shall end it here. But my next post will be the nitty gritty of how I wired all these pieces together.

Hope this helps someone, and do feel free to contribute your own wisdom to the comments!

Posted by dougboude at 12:30 AM | PRINT THIS POST! | Link | 3 comments