How do I check if a session variable is set? - coldfusion

I kept getting the "Error in custom script module" when checking if the session variable is set or not in my details page. Even if the session variable not set, wasn't this statement supposed to give me either true or false instead of error out?
<cfif StructKeyExists(session.mysiteShibboleth, "isAuthenticated") and (session.mysiteShibboleth.isAuthenticated) >
<cflog text="Session-Defined-5: isAuthenticated" type="Information" file="Authentication">
<cfelse>
<cflog text="Session-Defined-7: It's not authenticated'" type="Information" file="Authentication">
</cfif>
In my authenticate.cfm file, this is where the session variables are set.
<cfif cgiReferer eq shibboleth_url>
<cfscript>
session.mysiteShibboleth = StructNew();
session.mysiteShibboleth.username=REReplace(http_header.headers.eppn, "#mysite.com","","ALL");
session.mysiteShibboleth.mail=http_header.headers.eppn;
session.mysiteShibboleth.groups=ArrayToList(REMatch('WEB\.[A-Z.-]+', http_header.headers.member));
session.mysiteShibboleth.isAuthenticated="true";
</cfscript>
</cfif>
I have also tried the following and it's still error out. I have read this thread and it doesn't seem to resolve my issue.
<cfif IsDefined("session.mysitecShibboleth.isAuthenticated")>

You need to make sure that session.mysiteShibboleth exists before you check for a key on mysiteShibboleth. That is likely the source of your problem, but if you gave us the actual error message received, we could help you better.
Also, note that <cfif IsDefined("session.mysitecShibboleth.isAuthenticated")> has an errant c in the variable name.
** Edit: Adding code example
<cfif StructKeyExists(session, "mysiteShibboleth">
<cfif StructKeyExists(session.mysiteShibboleth, "isAuthenticated") and (session.mysiteShibboleth.isAuthenticated) >
. . .
</cfif>
<cfelse>
. . .
</cfif>

Related

trying to check for a session if itexist and has value

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.

CFIF statement checking if database (MSSQL) is connecting or exists

I am trying to write an if statement in Coldfusion 16 to check to see if it can connect to the database or that it exists. If it can connect to the database then show the page otherwise show down for maintenance. How should I just check to make sure the database is up? Any help with this would be greatly appreciated.
<cfquery name="DBUP" datasource="datasource">
SELECT ID
FROM dbo.Entry
</cfquery>
<cfif DBUP>
Show Page
<cfelse>
Show Down For Maintenance
</cfif>
You shouldn't directly put a error message or file in a catch statement. We should check one more condition ie) Error code is 0 or not. Imagine in some time the developer may give wrong query like undefined column or missing syntax etc... In that time also the catch will executed. So as per the requirement we have to check the datasource exists or not. If we want to check all type of issue means we no need of the error code conditions.
<cftry>
<cfset showPage = true>
<cfquery name="DBUP" datasource="datasource">
SELECT ID FROM dbo.Entry
</cfquery>
<cfcatch type="database">
<!--- The error code 0 is mentioned Datasource could not be found/exits. --->
<cfif cfcatch.cause.errorcode eq 0 >
<cfset showPage = false >
<!--- Data source does not exists --->
</cfif>
</cfcatch>
</cftry>
Based on showPage value do you business logic here
....
....
....
You will need to add it in Application.cfc onRequest method probably.
<cftry>
<cfquery name="DBUP" datasource="datasource">
SELECT ID
FROM dbo.Entry
</cfquery>
<cfcatch type="any">
Show DOwn For Maintenance
<!---everything optional below this line--->
<!---can show some custom message--->
<cfinclude template="errorMsg.cfm">
<!---stop the processing further--->
<cfabort>
</cfcatch>
</cftry>

Catching an error message

I'm using Coldfusion Fusebox 3 and I would like to know how I can keep my app from throwing an error message if someone thoughtlessly removes the Circuit and fuseaction from the URL.
For example, if the original URL is:
http://www.noname/Intranet/index.cfm?fuseaction=Bulletins.main
...and someone removes the circuit information so it reads like the following: http://www.noname/Intranet/index.cfm?fuseaction=
...the app throws an error message. Can I code against something like this happening?
Here is my fbx_Settings.cfm file as it exists right now. Thank you.
Try something along these lines, haven't had chance to test but should go something like this in your index.cfm file.
<cfprocessingdirective suppressWhiteSpace="yes">
<cftry>
<!--- Include the config file --->
<cfinclude template="../config.cfm">
<cfset variables.fromFusebox = True>
<cfinclude template="fbx_fusebox30_CF50.cfm">
<cfif Len(fusebox.fuseaction) EQ 0>
<!--- Error Handle --->
</cfif>
<cfcatch type="Any">
<!---<cfset SendErrorEmail("Error", cfcatch)><cfabort />--->
</cfcatch>
</cftry>
</cfprocessingdirective>
or better still, in your switch file have a default case such as:
<cfdefaultcase>
<cfinclude template="act_HandleError.cfm">
<cflocation url="hompage.cfm" addtoken="false">
</cfdefaultcase>
Hope this helps!

why can I not catch an error message in a Coldfusion cftry/cfcatch statement?

I have a form where I can upload logos a plenty. I'm validating files (empty form fields, wrong extension, ...) inside a cftry/cfcatch statement.
When I find an error in the cftry, I do this:
<cfthrow type="FileNotFound" message="#tx_settings_app_error_create_first#" />
and inside my 'cfcatch'
<cfcatch>
<cfoutput><script type="text/javascript">window.onload = function(){alert("#cfcatch.message#");window.location.href="hs_apps.cfm"; } </script></cfoutput>
</cfcatch>
This works fine, catches all errors and alerts the user what is wrong.
Now I wanted to use the same handler on a database call where I'm checking for duplicate username. Still the same:
<cfquery datasource="#Session.datasource#" name="duplicates">
SELECT a.app_alias
FROM apps AS a
WHERE a.iln = <cfqueryparam value = "#Session.loginID#" cfsqltype="cf_sql_varchar" maxlength="13">
AND a.app_alias = <cfqueryparam value = "#form.app_basic_alias#" cfsqltype="cf_sql_varchar" maxlength="50">
</cfquery>
<cfif duplicates.recordcount GT 0>
<cfthrow type="FileNotFound" message="#tx_settings_apps_error_dup#" />
</cfif>
The cfcatch is also the same.
However. This now procudes a server error page and I'm thrown out of the application.
Question:
Any idea, why I'm struggling to get cftry/cfcatch to work here? I'm clueless.
Thanks!
EDIT:
Here is the full code
<cfif isDefined("send_basic")>
<cfset variables.timestamp = now()>
<cfset variables.orderview = "1">
<cfif form.send_basic_type EQ "new">
<cftry>
<cfif module_check.recordcount GT 0>
<cfloop query="module_check">
<cfif module_check.module_name EQ "preorder">
<cfset variables.module_name = module_check.module_name>
<cfset variables.b2b_preord_ok = "true">
</cfif>
</cfloop>
<cfif form.app_basic_orderview EQ "preo">
<cfset variables.orderview = "0">
</cfif>
</cfif>
<!--- PROBLEM HERE: DUPLICATES --->
<cfquery datasource="#Session.datasource#" name="duplicates">
SELECT a.app_alias
FROM apps AS a
WHERE a.iln = <cfqueryparam value = "#Session.loginID#" cfsqltype="cf_sql_varchar" maxlength="13">
AND a.app_alias = <cfqueryparam value = "#form.app_basic_alias#" cfsqltype="cf_sql_varchar" maxlength="50">
</cfquery>
<cfif duplicates.recordcount GT 0>
<cfthrow type="FileNotFound" message="#tx_settings_apps_error_dup#" />
</cfif>
<!--- IF PASS, CREATE/UPDATE --->
<cfquery datasource="#Session.datasource#">
INSERT INTO apps ( ... )
VALUES( ... )
</cfquery>
<cfset variables.app_action = "Applikation erstellt">
<!--- success --->
<cfoutput><script type="text/javascript">window.onload = function(){alert("#tx_settings_app_cfm_create#");}</script></cfoutput>
<cfcatch>
<cfoutput><script type="text/javascript">window.onload = function(){alert("#tx_settings_app_err_create#");}</script></cfoutput>
</cfcatch>
</cftry>
<cfelse>
<cftry>
<!--- UPDATE --->
<cfquery datasource="#Session.datasource#">
UPDATE apps
SET ... = ...
</cfquery>
<cfset variables.app_action = "Applikation aktualisiert">
<!--- success --->
<cfoutput><script type="text/javascript">window.onload = function(){alert("#tx_settings_app_cfm_update#");}</script></cfoutput>
<cfcatch>
<cfoutput><script type="text/javascript">window.onload = function(){alert("#tx_settings_app_err_update#");}</script></cfoutput>
</cfcatch>
</cftry>
</cfif>
</cfif>
The error message I'm getting it the message I specify =
<cfthrow type="FileNotFound" message="#tx_settings_apps_error_dup#" />
Which if caught should alert the text behind tx_settings_apps_error_dup. If I dump the cfcatch, cfcatch.message is my specified text, so the error gets caught allright, only I get a server error page vs. an alert. I'm using exactly the same handler for fileuploads and form submits. I don't get why it's not working here?
Thanks for helping out!
WORKAROUD:
Note nice, but suffice(s):
<cfif dups.recordcount NEQ 0>
<cfoutput><script type="text/javascript">window.onload = function(){alert("#tx_settings_apps_error_dup#"); location.href = "hs_apps_detail.cfm?create=newApp&id=none";}</script
</cfoutput>
<cfabort>
</cfif>
So when a duplicate is found I alert the user, reload the exact same page and cfabort to prevent the old page from processing further. Patch that is.
(moved this down from being just a comment)
OK, so the catch is definitely catching the exception if you're able to dump it, so it's not that the try/catch ain't working, it's something else. Bear in mind that processing will continue until the end of the request after your catch block, and only then will the output buffer be flushed, and your alert() sent to the browser. It sounds to me like after your output the alert, and processing continues, some OTHER error is occurring which is causing the server's error page to display. I recommend getting rid of the error page temporarily and eyeballing the actual error CF is raising.
NB: if you want processing to stop immediately in the catch block after you output the alert(), you're going to need to tell CF that, ie: with a <cfabort>. Otherwise, as per above, it'll just keep going.
I think exceptions that are caught by the server error page are still logged in the exception log, but I could be wrong. You could always put an onError() handler in your Application.cfc, log whatever error occurred, then rethrow the error so the error page still deals with it. That way you get the info on the error, and the punter still sees the nice error page.

How do I redirect based on referral in ColdFusion

I have a coldfusion web site I need to change. Have no idea or experience with this environment (I do know ASP.NET). All I need to do is to write a condition based on the referral value (the URL) of the page, and redirect to another page in some cases.
Can anyone give me an example of the syntax that would perform this?
All of the other examples would work...also if you're looking to redirect based on a referral from an external site, you may want to check CGI.HTTP_REFERER. Check out the CGI scope for several other options.
<cfif reFindNoCase('[myRegex]',cgi.http_referer)>
<cflocation url="my_new_url">
</cfif>
...my example uses a regex search (reFind() or reFindNoCase()) to check the referring URL...but you could also check it as a list with / as a delimiter (using listContainsNoCase()) depending on what you're looking for.
Lets assume your the URL variable you are basing this on is called goOn (http://yoursite.com?goOn=yes) then the following code would work:
<cfif structKeyExists(url, "goOn") AND url.goOn eq "yes">
<cflocation url="the_new_url" addtoken="false">
</cfif>
Nothing will happen after the cflocation.
There is a CGI variable scope in ColdFusion that holds information on the incoming request. Try the following:
<cfif CGI.SCRIPT_NAME EQ 'index.cfm'>
<cflocation url="where you want it to redirect" />
</cfif>
To see what else is available within the CGI scope, check out the following:
http://livedocs.adobe.com/coldfusion/8/htmldocs/Expressions_8.html#2679705
Haven't done coldfusion in a little while but:
<cfif some_condition_based_on_your_url>
<cflocation url="http://where_your_referrals_go">
</cfif>
<!--- continue processing for non-redirects --->
A dynamic version.
<cfif isdefined("somecondition")>
<cfset urlDestination = "someurl">
<cfelseif isdefined("somecondition")>
<cfset urlDestination = "someurl">
.
.
.
<cfelse>
<cfset urlDestination = "someurl">
</cfif>
<cflocation url = urlDestination>