Creating session variable properly with application.cfc
I haven't had the chance to use application.cfc when creating web application. Usually this is how I create session variable ,such as, session.userid after user validation. Here is an example:
First, on my application.cfm I did :
<cfapplication name="SomeName" sessionmanagement="Yes" setclientcookies="Yes" CLIENTMANAGEMENT="No" sessiontimeout="#CreateTimeSpan(0,1,0,0)#" applicationtimeout="#CreateTimeSpan(1,0,0,0)#">
Then on my loginaction.cfm page, I validate user login with something like:
<cfquery name="ValidateUser" datasource="#application.DSN#">
SELECT UserId, Username, Password FROM users
WHERE Username = <cfqueryparam cfsqltype="cf_sql_varchar" value="#Form.username#">
AND Password = <cfqueryparam cfsqltype="cf_sql_varchar" value="#Form.Password#">
</cfquery>
<CFIF ValidateUser.Recordcount NEQ 0>
<CFSET session.UserId = "#ValidateUser.UserId#">
</CFIF>
Once this session.UserId is created then I can use it on any query throughout the application.
Now, I want to use Application.cfc instead of Application.cfm. From my reading Within Application.cfc I can create a Function called:
OnApplicationStart, OnSessionStart, etc
It is said that: OnSessionStart is the perfect place to define session-scoped variables (ex. SESSION.Cart for eCommerce cart data).
If this method is invoked manually, be sure to call StructClear() on the SESSION scope before you re-initialized the data values. HOWEVER! before clearing the scope, get a copy of the CFID/CFTOKEN values so that you can store them back into the session during re-initialization.
I don't quite understand this explanation and especially when I want to create my session.UserId using the logic I explain above.
Below is my test when trying to work with application.cfc:
On my loginaction.cfm:
<cfinvoke component="cfcomponents.application" method="OnSessionEnd" UserName ="#Trim(Form.MyUsername)#"
Password = "#Trim(Form.myPassword>
On Application.cfc:
<cfcomponent displayname="Application" output="true" hint="Handle the application.">
<cffunction name="OnApplicationStart" access="public" returntype="boolean" output="false" hint="Fires when the application is first created.">
<cfset application.dsn = "OnBoardBuddy">
<cfreturn true/
</cffunction>
<!--- Is this the right way to set session.userid when using application.cfc? --->
<cffunction name="OnSessionEnd" access="public" returntype="void" output="false" hint="Fires when the session is terminated.">
<cfquery name="ValidateUser" datasource="#application.DSN#">
SELECT UserId, Username, Password FROM users
WHERE Username = <cfqueryparam cfsqltype="cf_sql_varchar" value="#Form.username#">
AND Password = <cfqueryparam cfsqltype="cf_sql_varchar" value="#Form.Password#">
</cfquery>
<CFIF ValidateUser.Recordcount NEQ 0>
<CFSET session.UserId = "#ValidateUser.UserId#">
</CFIF>
</cffunction>
</cfcomponent>
