I'm writing a web application using the ColdFusion on Wheels framework and ran into something that I didn't expect. This is partly because of my "vague" understanding of object-oriented programming. In my Wheels application I have in my Controller.cfc an init function which looks like this:
<cfcomponent extends="Wheels"> <cffunction name="init"> <cfset filters(through="checkLogin", except="login,authenticate,logout,resetPassword,forgotPassword")> </cffunction> <cffunction name="checkLogin"> <cfif StructKeyExists(session, "user")> <cfset loggedInUser = model("user").findByKey(session.user.id)/> <cfelse> <cfset redirectTo(controller="users", action="login")/> </cfif> </cffunction>
Pretty basic. So each time one of my controllers does something it inherits this init function and verifies the user has a session value, if not, send them back to the login screen. Worked great!
However in trying to DRY up my Controllers, and seeing an example that Tom has on his blog I wanted to create an init() within one of my controllers, say “Contacts.cfc”, that would populate a structure with a list of values I use over and over again (think yes/no or gender or US states). So in the Contacts.cfc controller I had this
<cfcomponent extends="Controller" output="false"> <cffunction name = "init"> <cfset filters(through="getYesNoValues", only="new,edit")/> <cfset filters(through="getStatesValues", only="new,edit")/> </cffunction> </cfcomponent>
This worked great! However, I noticed that after I came back to my application after 30 minutes (when my session scope times out and my session.user.id would be destroyed) that I could still navigation through my CFWheels application within the Contacts controller, even though I was no longer logged into the application and shouldn’t be able to see this information!
I learned that if I create a “init()” function in my Contacts controller, then it doesn’t run my “init()” function in my Controller.cfc, so it’s not checking my session to make sure it’s valid.
I was able to solve this by changing my Contacts.cfc controller init() to call the Controller.cfc init() function by using the Super.init(), like so:
<cfcomponent extends="Controller" output="false"> <cffunction name = "init"> <cfset Super.init() /> <cfset filters(through="getYesNoValues", only="new,edit")/> <cfset filters(through="getStatesValues", only="new,edit")/> </cffunction> </cfcomponent>
This seems to work as I expect now. If my session times out, and I try to work with my Contacts.cfc controller, then I’m sent back to the user login. Turns out this was documented in the (excellent) CFWheels documentation on Filters
No comments:
Post a Comment