trying to check for a session if itexist and has value - coldfusion

i am writing a code to check for session and session value and if they do not exists or exists but have empty value or 0, i want them redirected
here is my start
<cfset lstofSessionsToCheck = 'EmplyID,Username'>
<cfset st = {}>
<cfloop collection="#session#" item="i">
<cfset SetVariable("st.session.#i#",duplicate(session[i]))>
</cfloop>
<cfparam name="redirection" default="false">
<cfif session.Username eq ''>
<cfset redirection = true>
<cfelseif session.EmplyID eq ''>
<cfset redirection = true>
</cfif>
it is missing some checks here
check if session is defined before it checks its value
if its defined, its value should not be empty or 0 or -1
please guide,m i am almost near its end but stuck at that

session is a special scope in ColdFusion and either always or never exists. It depends on the state of the sessionManagement attribute in your Application.cfc (or Application.cfm/<cfapplication>). In case sessionManagement is false, accessing session will immediately throw an exception. I assume you are not seeing this error, so session management is enabled in your environment. That leaves you with checking if the session fields are initialized. Your new best friend is called structKeyExists().
<!--- username needs to exist and must not be empty --->
<cfset hasUsername = (
structKeyExists(session, "Username") and
(len(session.Username) gt 0)
)>
<!--- ID needs to exist, must be a number and > 0 --->
<cfset hasID = (
structKeyExists(session, "EmplyID") and
isNumeric(session.EmplyID) and
(session.EmplyID gt 0)
)>
<!--- if either username or ID is not properly set, do a redirect --->
<cfif (not hasUsername) or (not hasID)>
<cfset redirection = true>
</cfif>
You can simplify the last line to a single expression:
<cfset redirection = ((not hasUsername) or (not hasID))>
As for your usage of setVariable(): You should generally avoid this function (along with evaluate()) as they can be easily exploited and pose a security risk.
Rewrite:
<cfset st = {}>
<cfloop collection="#session#" item="i">
<cfset SetVariable("st.session.#i#",duplicate(session[i]))>
</cfloop>
to
<cfset st = {}>
<cfset st.session = {}>
<cfloop collection="#session#" item="i">
<cfset st.session[i] = duplicate(session[i])>
</cfloop>
(And by the way, i is actually a key here, not a numeric index. Only use i with a for loop.)

I'm not sure the best way to do this is by looping through the entire thing every time you check. Unless those values are coming from a database or something after authentication?
Typically, if you want to restrict access to a page, you would check the session scope using structKeyExists(), for just a couple specific things.
The code would look something like this:
<!---This code sees if the user is logged in at all. If they are missing important information, I clear the session scope and redirect them to the login page. --->
<cfif !structKeyExists(SESSION, 'Username')>
<cfset structClear(SESSION)>
<cflocation url="YourPageHere" addtoken="maybe">
</cfif>
<!---This code checks for a specific permission to be defined. If not, it stops or redirects the user.--->
<cfif structKeyExists(SESSION, 'CanEditUsers') AND SESSION.CanEditUsers eq 1>
<!---your code here--->
<cfelse>
<cflocation url="YourPageHere" addtoken="maybe">
</cfif>
This is only a rough example - but hopefully puts you on the right path. Let me know if anything is unclear or needs to be edited to better fit your situation.

Related

Coldfusion set time out in .cfc page?

I have one .cfc that I use for all communication between client and server code. This cfc page has about 10 different function. Each function has different purpose and I have queries for Select, Insert, Update and Delete. I'm wondering if I should set timeout on the top of the .cfc page inside cfcomponent tag or this should be set inside of the each function or do I even need this? In our current system we have some many error messages like: The request has exceeded the allowable time limit Tag: CFQUERY.
I would like to prevent any similar error messages in my app. Here is example of my cfc page:
<cfcomponent>
<cfset currentDate = DateFormat(Now(),'mm/dd/yyyy')>
<cfset currentTime = TimeFormat(Now(),'hh:mm tt')>
<cfinvoke component="appEntry" method="getRecord" returnvariable="CHKAccess">
<cfinvokeargument name="user" value="userdata"/>
<cfinvokeargument name="app" value="myApp"/>
</cfinvoke>
<cfset adminAccess = false>
<cfset userAccess = false>
<cfif CHKAccess.RecordCount EQ 1>
<cfif CHKAccess.pd_hfmAccess EQ 'A'>
<cfset adminAccess = true>
</cfif>
<cfif CHKAccess.pd_hfmAccess EQ 'U'>
<cfset userAccess = true>
</cfif>
</cfif>
<cffunction name="getData" access="remote" output="true" returnformat="JSON">
<cfargument name="keyVal" type="string" required="true">
<cfset fnResults = structNew()>
<cfif userAccess>
<cfquery name="getRec" datasource="tes">
SELECT some columns
FROM Test
</cfquery>
<cfset fnResults.status = "200">
<cfelse>
<cfset fnResults.status = "400">
<cfset fnResults.message = "Invalid access attempt.">
</cfif>
<cfreturn fnResults>
</cffunction>
<!--- More functions below --->
</cfcomponents>
If anyone have suggestion what would be the best fix please let me know. Thank you.
You should set the requesttimeout in the method that contains that long-running cfquery.
You don't want to "punish" all methods for just one method. If you set it for all, how do you know which one is slow and which one is okay, unless you don't care?

ColdFusion Link to Previous Page Clears only that Page Session Variables

I have a page (form) set up like this:
<cfif not structKeyExists(session, "checkout")>
<cflocation url="ownerInfo.cfm" addToken="false">
</cfif>
<cfif not structKeyExists(session.checkout, "vehicle")>
<cfset session.checkout.vehicle = {ownership=""}
<cfparam name="form.ownership" default="#session.checkout.vehicle.ownership#">
<cfif structKeyExists(form, "submit")>
<cfset errors = []>
<cfif not arrayLen(errors)>
<cfset session.checkout.vehicle = {ownership=form.ownership}
<cflocation url="ownerCheck.cfm" addToken="false">
</cfif>
</cfif>
I am trying to figure out how I can reset this form by having a link on another page that when this page is linked back to it will reset all the session variables to null making the entire page needing to be filled out again.
This is what I have tried but am unsuccessful.
<cfif session.checkout.vehicle.ownership != null />
<cfset session.checkout.vehicle.ownership = null />
</cfif>
I cannot use <cfset StructClear(Session)> because I do not want all the session variables cleared from the previous pages only want this page to reset.(Not All Pages or All Session Variables). Any help with this would be greatly appreciated!
You can do using structDelete(structure,key)
<cfif session.checkout.vehicle.ownership != null />
<cfset structDelete(session.checkout.vehicle,'ownership ')>
</cfif>
If you want to clear the session scope variables if the ownership key already exists in the session scope then you can do:
<cfif structKeyExists(session.checkout.vehicle, "ownership")>
<!--- struct key exists so delete it --->
<cfset structDelete(session.checkout.vehicle, "ownership")>
</cfif>
You can actually just do:
<cfif structKeyExists(session.checkout, "vehicle")>
<!--- try and delete ownership key might not exist --->
<cfset structDelete(session.checkout.vehicle, "ownership")>
</cfif>
As long as the parent scope exists, you can try and delete the ownership key without first checking that it exists.
If you want to know if the key did exist then structDelete accepts a 3rd boolean parameter so it'll return true if it did exists and false if it didn't.
<cfset didExist = structDelete(session.checkout.vehicle, "ownership", true)>
An alternative approach to solving your problem would be to reset the form if it's not a form (POST) submission. So you'd do:
<cfif structKeyExists(form, "submit")>
<!--- form has been submitted store values in session and redirect... -->
<cfelse>
<!--- form not submitted so clear the session vars... --->
</cfif>

Can CFThread, when wrapping over cfhttp, solves my Timeout error issue?

My application pulls lots of data from different applications according to the selected scopes. For e.g. Org level and SubOrg level scopes, this can cause to bring server down and everyday causes server crashing and timeouts.
So I wanted to know whether wrapping cfthread around my cfhttp will solve my timeout problem?
<cfinclude template="fundedScopes.cfm">
<!--- Call the funded scopes --->
<cfset dynVarName = "funded" & bizforShort>
<cfif structKeyExists(variables,dynVarName)>
<cfset howManyCustomScopes = listLen(structkeylist(variables[dynVarName],"|" ),"|" )>
<cfmodule template="#Request.Library.CustomTags.VirtualPath#Scheduler_LogDetail.cfm"
Step="Funded Level Cache" Detail="Custom Scopes to be cached: #howManyCustomScopes#"
LogData=""></cfmodule>
<cfloop collection="#variables[dynVarName]#" item="t">
<cfset tempurl = variables[dynVarName][t]["url"]>
<cfset tempurl = tempurl & "&retainCache=1">
<cfoutput>
<cfhttp url="#tempurl#" method="GET" resolveurl="false" timeout="3000">
#tempurl#<br>
<cfset scopesCachedCounter = scopesCachedCounter + 1>
<cfmodule template="#Request.Library.CustomTags.VirtualPath#Scheduler_LogDetail.cfm" Step="Funded Scopes Cache" Detail="#scopesCachedCounter#.- #t#" LogData="#tempurl#"></cfmodule>
</cfoutput>
</cfloop>
</cfif>

Error with undefined variables while looping over a query

I have an error while looping over a query using cfloop.
When I use a cfdump on the query (inside the loop, mind you), I can see all the data just fine. But when I try to get the value of each variable as you normally do in cfloop, I get a message that says they are undefined. I then changed each variable to reference the query specifically, and now the problem is that the variable is undefined in the query. Here's the code:
<cffunction name="writeCourses">
<cfargument name="recordset" required="yes" type="query">
<cfif recordset.RecordCount NEQ 0>
<cfset temp = "">
<cfoutput>
<cfloop query="recordset">
<!--- <cfdump var="#recordset#"> <cfabort/> --->
<cfset temp = temp & "<strong>#recordset.courseType# #recordset.courseNum# ">
<cfif isDefined("recordset.courseTHM") AND recordset.courseTHM EQ 1>
<cfset temp = temp & "(#left(recordset.courseNum,3)#4) ">
</cfif>
<cfif isDefined("recordset.courseName")>
<cfset temp = temp & "#recordset.courseName# </strong><br>">
</cfif>
<cfset temp = temp & "#recordset.courseDESC#<br>">
<cfset temp = temp & "#recordset.courseHours#<br><br>">
</cfloop>
</cfoutput>
<cfelse>
<cfset temp = "">
</cfif>
<cfreturn temp>
</cffunction>
So as you can see, each variable is enclosed in ## tags. Originally none of them were proceeded by recordset. but they were still undefined. And when I uncomment the cfdump and cfabort tags, those work fine and I can see the recordset query with all the data as it should be.
Every other time I have used cfloop with a query it works as expected. Also, I did not write this code, I am having to modify it (the original author no longer works here).
Here's an example of the recordset dump:
The error message:
Detail: [empty string]
ErrNumber: 0
Message: Element COURSETYPE is undefined in RECORDSET.
Resolvedname: RECORDSET
The error line is:
<cfset temp = temp & "<strong>#recordset.courseType# #recordset.courseNum# ">
<cfif isDefined("recordset.courseTHM") AND recordset.courseTHM EQ 1>
<cfset temp = temp & "(#left(recordset.courseNum,3)#4) ">
</cfif>
<cfif isDefined("recordset.courseName")>
<cfset temp = temp & "#recordset.courseName# </strong><br>">
</cfif>
That's all one line :/
The stored procedure/function calling the above:
<cffunction name="getCoursesByDept">
<cfargument name="deptCode" required="yes" type="string">
<CFSTOREDPROC procedure="dbo.GetCourses" datasource="WebCatalog">
<CFPROCPARAM type="IN" dbvarname="#deptCode" value="#deptCode#" cfsqltype="CF_SQL_CHAR">
<CFPROCRESULT name="result">
</CFSTOREDPROC>
<cfinvoke method="writeCourses" recordset="#result#" returnvariable="output">
<cfreturn output>
</cffunction>
Your problem appears to be failure to scope. Here are your first 4 lines:
<cffunction name="writeCourses">
<cfargument name="recordset" required="yes" type="query">
<cfif recordset.RecordCount NEQ 0>
<cfset temp = "">
Try it like this:
<cffunction name="writeCourses">
<cfargument name="recordset" required="yes" type="query">
<cfset var temp = "">
<cfif arguments.recordset.RecordCount NEQ 0>
The differences are the use of the var keyword for your local variable temp, and adding the arguments scope to the recordset variable.
(In addition to Dan's comments ...)
If [the procedure] can't find anything it returns a query containing
an error message (i.e. no course found)
Then that means the COURSETYPE column does not always exist in the resultset, which is exactly what the error message is reporting. If the procedure returns any result, regardless of the contents, the code inside the cfif block will execute. Since the first line of code uses that column, without verifying it exists, it would cause the exact error you are seeing.
Also, as I mentioned in the comments, you really need to localize the function variables result, output, temp, etectera. Lack of var scoping can create problems, even within same page, if you reuse variable names. As #Dan suggested you should fully scope all variables - in particular, the function arguments.
(As an aside, I understand you are modifying existing code, but the error message should really be handled in CF, not inside the procedure. The procedure's job is just to return data. The CF code should check the recordCount and take the appropriate action if no records are found.)

ColdFusion searching robots.txt for specific page exception

We're adding some functionality to our CMS whereby when a user creates a page, they can select an option to allow/disallow search engine indexing of that page.
If they select yes, then something like the following would apply:
<cfif request.variables.indexable eq 0>
<cffile
action = "append"
file = "C:\websites\robots.txt"
output = "Disallow: /blocked-page.cfm"
addNewLine = "yes">
<cfelse>
<!-- check if page already disallowed in robots.txt and remove line if it does --->
</cfif>
It's the <cfelse> clause I need help with.
What would be the best way to parse robots.txt to see if this page had already been disallowed? Would it be a cffile action="read", then do a find() on the read variable?
Actually, the check on whether the page has already been disallowed would probably go further up, to avoid double-adding.
You keep the list of pages in database and each page record has a indexable bit, right? If yes, simpler and more reliable approach would be to generate new robots.txt each time some page is added/deleted/changes indexable bit.
<!--- TODO: query for indexable pages ---->
<!--- lock the code to prevent concurrent changes --->
<cflock name="robots.txt" type="exclusive" timeout="30">
<!--- flush the file, or simply start with writing something --->
<cffile
action = "write"
file = "C:\websites\robots.txt"
output = "Sitemap: http://www.mywebsite.tld/sitemap.xml"
addNewLine = "yes">
<!--- append indexable entry to the file --->
<cfloop query="getPages">
<!--- we assume that page names are not entered by user (= safe names) --->
<cffile
action = "append"
file = "C:\websites\robots.txt"
output = "Disallow: /#getPages.name#.cfm"
addNewLine = "yes">
</cfloop>
</cflock>
Sample code is not tested, be aware of typos/bugs.
Using the Robots.txt files for this purpose is a bad idea. Robots.txt is not a security measure and you're handing "evildoers" a list of pages that you don't want indexed.
You're much better off using the robots meta tag, which will not provide anyone with a list of pages that you don't want indexed, and gives you greater control of the individual actions a robot can perform.
Using the meta tags, you would simply output the tags when generating the page as usual.
<!--- dummy page to block --->
<cfset request.pageToBlock = "/blocked-page.cfm" />
<!--- read in current robots.txt --->
<cffile action="read" file="#expandPath('robots.txt')#" variable="data" />
<!--- build a struct of all blocked pages --->
<cfset pages = {} />
<cfloop list="#data#" delimiters="#chr(10)#" index="i">
<cfset pages[listLast(i,' ')] = '' />
</cfloop>
<cfif request.variables.indexable eq 0>
<!--- If the page is not yet blocked add it --->
<cfif not structKeyExists(pages,pageToBlock)>
<cffile action="append" file="C:\websites\robots.txt"
output="Disallow: #request.pageToBLock#" addNewLine="yes" />
<!--- not sure if this is in a loop but if it is add it to the struct for nex iteration --->
<cfset pages[request.pageToBlock] = '' />
</cfif>
</cfif>
This should do it. Read in the file, loop over it and build a struct of the bloocked pages. Only add a new page if it's not already blocked.