I am having difficulty having session values stick when I create them. The default value exists at all times. Below is my rudimentary login tool.
The compare function works fine, but when after the cflock and redirect, session.userId and session.isLoggedIn are still 0 and false, respectively.
config/app.cfm
<cfset this.name = "xxx">
<cfset this.sessionManagement = true />
<cfset this.sessionTimeout= createtimespan(0,2,0,0) />
<cfset this.setClientCookies = false />
<cfset this.datasource = "xxx" />
events/onRequestStart.cfc
<cfscript>
if ( !StructKeyExists(session, "userId") ) {
session.userId = 0;
session.isloggedIn = false;
}
</cfscript>
controllers/admin.cfc
<cfcomponent extends="Controller">
<cffunction name="init">
</cffunction>
<cffunction name="login">
</cffunction>
<cffunction name="main">
</cffunction>
<cffunction name="login_proc">
<cfset local.userName = "xxx" />
<cfset local.password = "yyy" />
<cfif isPost() and StructKeyExists(params, "username")>
<cfif compare(params.username, local.username) eq 0 AND compare(params.password, local.password) eq 0>
<cflock scope="Session" type="exclusive" timeout="3">
<cfset session.userId = local.userName />
<cfset session.isLoggedIn = true />
</cflock>
<cfset redirectTo(action="main")>
<cfelse>
<cfset
flashInsert(
error_msg="Incorrect login."
)>
<cfset redirectTo(action="login")>
</cfif>
<cfelse>
<cfset redirectTo(action="login")>
</cfif>
</cffunction>
</cfcomponent>
views/admin/login.cfm
<cfform action="/-rootdir-/index.cfm/admin/login_proc" method="post">
<p>
<label for="login">Username</label>
<cfinput type="text" name="username" size="20" required="yes" message="Enter your username" autofocus />
</p>
<p>
<label for="password">Password</label>
<cfinput type="password" name="password" size="20" required="yes" message="Enter your password" />
</p>
<input type="submit" name="login" value="Go" />
</cfform>
It's this line in your config/app.cfm
causing the trouble:
<cfset this.setClientCookies = false />
With setClientCookies
set the way you have it, cfid
, cftoken
, jsessionid
, etc. cookies are not being passed to the client, and ColdFusion has no information about the client's session after the redirect happens.
If you absolutely must have this setting, then you need to pass cfid
and cftoken
in all of your redirects and links.
<cfset redirectTo(action="main", addToken=true)>
<!--- Can't use linkTo anymore unless you override `urlFor` in the controller to use ColdFusion's built-in UrlSessionFormat() function --->
<a href="#UrlSessionFormat(urlFor(action='main'))#>My link</a>
I doubt you want this behavior though.