Tag Archives: ColdFusion

jQuery Autocomplete with HTML in Dropdown Selection Menu

With jQuery 1.8 and prior, you could include some simple HTML in the selection menu and it would render. With post 1.8 converting the results as strings, the HTML failed to render.

Workaround

The source page (states.php) for the jQuery is coded as such:

try {
  $conn = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
}
catch(PDOException $e) {
    echo $e->getMessage();
}

$return_arr = array();

if ($conn)
{
	$ac_term = "%".$_GET['term']."%";
	$query = "SELECT * FROM states where state like :term";
	$result = $conn->prepare($query);
	$result->bindValue(":term",$ac_term);
	$result->execute(); 

	/* Retrieve and store in array the results of the query.*/
	while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
		$row_array['id'] = $row['id'];
		$row_array['value'] = trim($row['state'],"\r");
		$row_array['label'] = "<img src='me.jpg' height='20'>" . trim($row['state'],"\r");
		$row_array['abbrev'] = $row['abbrev'];

        array_push($return_arr,$row_array);
    }

}
/* Free connection resources. */
$conn = null;
/* Toss back results as json encoded array. */
echo json_encode($return_arr);

The example simply concatenates on an image file. For the purpose of demonstration, the image is the same for all results.

Since the latest versions of jQuery are now replacing the ‘<' and '>‘ with (ampersand)lt; and (ampersand)gt; respectively, the results need to be looped and corrected. This can be done in the ‘open’ event of the autocomplete. For more information on the ‘open’ event, see the jQuery UI documentation.

The latest version of jquery causes the item altered in the open event to be too wide. The override of the renderItem function fixes this.

$("#state").autocomplete({
				source: "states_image.php",
				minLength: 2,
				select: function(event, ui) {
					$('#state_id').val(ui.item.id);
					$('#abbrev').val(ui.item.abbrev);
				}
			});

			$["ui"]["autocomplete"].prototype["_renderItem"] = function( ul, item) {
				return $( "<li></li>" )
  				.data( "item.autocomplete", item )
  				.append( $( "<a></a>" ).html( item.label ) )
  				.appendTo( ul );
			};

So you get something that looks like this:

Demo

Usual recommended jQuery and CF reading:

Clicks and Impressions from Google Adwords API using ColdFusion

Requests for simple data like clicks and impressions from the Google Adwords API can be made via SOAP requests. For more complex data and calculations, the client libraries are more aptly suited.

This example does not use the sandbox. Calls to it will counts against the Adwords units. It also uses the latest version of the API, version v201003.

The requests require an authorization token which can be obtained via the ClientLogin method. Store this token in a session or application variable to prevent a CAPTCHA challend from Google for multiple authorization requests.

<cfif NOT StructKeyExists(application, "adw_loginAuth")>
	<cfset googleLogin(api.email,api.password) />
</cfif>

<cffunction name="googleLogin" access="private" hint="GA account authorization">
        <cfargument name="email" type="string" required="yes" default="">
        <cfargument name="password" type="string"required="yes" default="">
        <cfargument name="gaLoginUrl" type="string" required="no" default="https://www.google.com/accounts/ClientLogin">

        <cfset var loginAuth = "" />

        <cfhttp url="#arguments.gaLoginUrl#" method="post">
            <cfhttpparam name="accountType" type="url" value="GOOGLE">
            <cfhttpparam name="Email" type="url" value="#arguments.email#">
            <cfhttpparam name="Passwd" type="url" value="#arguments.password#">
            <cfhttpparam name="service" type="url" value="adwords">
            <cfhttpparam name="source" type="url" value="my-adwords-not-yours">
        </cfhttp>

        <cfif NOT FindNoCase("Auth=",cfhttp.filecontent)>
            <cfset loginAuth = "Authorization Failed" />
        <cfelse>
            <cfset loginAuth = Mid(cfhttp.filecontent, FindNoCase("Auth=",cfhttp.filecontent) + (Len("Auth=")), Len(cfhttp.filecontent)) />
        </cfif>
        <!--- authToken in application var to prevent Google from sending captcha request (recommended by Google) --->
        <cflock scope="application" type="exclusive" timeout="5">
			<cfset application.adw_loginAuth = loginAuth />
		</cflock>
</cffunction>

The Adwords API is called with an http post request to the appropriate service with the data request specified using SOAP.

<cfsavecontent variable="CampaignRequestXML">
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns="https://adwords.google.com/api/adwords/cm/v201003">
	<soapenv:Header>
		<RequestHeader>
            <authToken>#application.adw_loginAuth#</authToken>
            <userAgent>V2010 Get All Campaign Info</userAgent>
            <developerToken>ADWORDS-API-DEV-TOKEN</developerToken>
            <clientEmail>CLIENT-EMAIL</clientEmail>
        </RequestHeader>
    </soapenv:Header>
    <soapenv:Body>
    	<get>
        	<selector>
            	<ids></ids>
					<statsSelector>
						<dateRange>
							<min>20100101</min>
							<max>20100715</max>
						</dateRange>
                        <startDate/>
						<endDate/>
                        <network>ALL</network>
						<clicks/>
						<impressions/>
					</statsSelector>
            </selector>
        </get>
    </soapenv:Body>
</soapenv:Envelope>
</cfsavecontent>

Clicks and impressions are obtained using the campaign service. Data returned from the Adwords API is also in the SOAP format. After stripping the prefixes out of the SOAP response that will prevent the XMLSearch function in ColdFusion from working as expected, the data can be extracted and stored in variables and displayed.

<!--- http SOAP request and xml parse --->
<cfset CampaignResponseXML = adwordsSOAPresponse(CampaignRequestXML) />

<cffunction name="adwordsSOAPresponse" access="private" returnType="string">
	<cfargument name="xmlSOAPrequest" type="string" required="yes" default="">

	<cfif application.adw_loginAuth NEQ "Authorization Failed">
        <cfhttp url="https://adwords.google.com/api/adwords/cm/v201003/CampaignService" method="post">
           <cfhttpparam name="SOAPAction" type="header" value=""/>
           <cfhttpparam type="xml" value="#trim(arguments.xmlSOAPrequest)#"/>
        </cfhttp>
        <cfset responseXML = cfhttp.filecontent />
    <cfelse>
        <p>Google Authorization Failed.</p>
        <cfabort />
    </cfif>

    <!---remove soap: prefix or any other prefix from nodes that have it --->
    <cfset responseXML = responseXML.ReplaceAll("(</?)(\w+:)","$1") />
    <!--- remove xmlns: --->
    <cfset responseXML = responseXML.ReplaceAll("xmlns(:\w+)?=""[^""]*""","") />
    <!--- remove xsi element prefixes --->
    <cfset responseXML = responseXML.ReplaceAll('(/?)(xsi:)','$1') />

    <cfreturn responseXML />
</cffunction>

Now the data can be extracted to an array using XMLSearch. Then put into an array of structures to make it easy to dump.

<cfset CampaignResponseXML = adwordsSOAPresponse(CampaignRequestXML) />

<cfset CampaignEntryNodes = XmlSearch(CampaignResponseXML, '//entries/') />

<cfloop from="1" to="#ArrayLen(CampaignEntryNodes)#" index="num">
	<cfset entryStruct = StructNew() /> 

    	<cfset entryStruct.id = CampaignEntryNodes[num].id.XmlText />
        <cfset entryStruct.name = CampaignEntryNodes[num].name.XmlText />
        <cfset entryStruct.status = CampaignEntryNodes[num].status.XmlText />
        <cfset entryStruct.clicks = CampaignEntryNodes[num].campaignStats.clicks.XmlText />
        <cfset entryStruct.impressions = CampaignEntryNodes[num].campaignStats.impressions.XmlText />

		<cfset totalClicks = totalClicks + CampaignEntryNodes[num].campaignStats.clicks.XmlText />
        <cfset totalImpressions = totalImpressions + CampaignEntryNodes[num].campaignStats.impressions.XmlText />
        <cfset arrayAppend(campaignStatsArray,duplicate(entryStruct)) />

</cfloop>

<cfdump var="#campaignStatsArray#">
<p>Total clicks: #totalClicks#<br />
Total Impressions: #totalImpressions#</p>

Code in its entirety:

<!--- cfapplication is not needed if application.cfc exists --->
<cfapplication name="adwordsapi" applicationtimeout="#createtimespan(2,0,0,0)#" />

<cfset totalClicks = 0 />
<cfset totalImpressions = 0 />
<cfset campaignStatsArray = ArrayNew(1) />
<cfset campaignID = "" />
<cfset campaignStatusArray = ArrayNew(1) />
<!---
	Adwords API parameters:
	Set email and password to adwords account
	Dev token is from MCC API details
--->
<cfscript>
   api = structnew();
   api.email = "GMAIL-ADDRESS-HERE";
   api.password = "GMAIL-PASSWORD";
   api.devtoken = "API-DEV-TOKEN";
   api.campaignService = "https://adwords.google.com/api/adwords/cm/v201003/CampaignService";
   api.clientEmail = "CLIENT-EMAIL-HERE";
   api.startDate = DateFormat(Now(), 'yyyymmdd');
   api.endDate = DateFormat(Now(), 'yyyymmdd');
</cfscript>

<cfif NOT StructKeyExists(application, "adw_loginAuth")>
	<cfset googleLogin(api.email,api.password) />
</cfif>

<cffunction name="googleLogin" access="private" hint="GA account authorization">
        <cfargument name="email" type="string" required="yes" default="">
        <cfargument name="password" type="string"required="yes" default="">
        <cfargument name="gaLoginUrl" type="string" required="no" default="https://www.google.com/accounts/ClientLogin">

        <cfset var loginAuth = "" />

        <cfhttp url="#arguments.gaLoginUrl#" method="post">
            <cfhttpparam name="accountType" type="url" value="GOOGLE">
            <cfhttpparam name="Email" type="url" value="#arguments.email#">
            <cfhttpparam name="Passwd" type="url" value="#arguments.password#">
            <cfhttpparam name="service" type="url" value="adwords">
            <cfhttpparam name="source" type="url" value="adwords-clicks-impressions">
        </cfhttp>

        <cfif NOT FindNoCase("Auth=",cfhttp.filecontent)>
            <cfset loginAuth = "Authorization Failed" />
        <cfelse>
            <cfset loginAuth = Mid(cfhttp.filecontent, FindNoCase("Auth=",cfhttp.filecontent) + (Len("Auth=")), Len(cfhttp.filecontent)) />
        </cfif>
        <!--- authToken in application var to prevent Google from sending captcha request (recommended by Google) --->
        <cflock scope="application" type="exclusive" timeout="5">
			<cfset application.adw_loginAuth = loginAuth />
		</cflock>
</cffunction>

<cffunction name="adwordsSOAPresponse" access="private" returnType="string">
	<cfargument name="xmlSOAPrequest" type="string" required="yes" default="">

	<cfif application.adw_loginAuth NEQ "Authorization Failed">
        <cfhttp url="#api.campaignService#" method="post">
           <cfhttpparam name="SOAPAction" type="header" value=""/>
           <cfhttpparam type="xml" value="#trim(arguments.xmlSOAPrequest)#"/>
        </cfhttp>
        <cfset responseXML = cfhttp.filecontent />
    <cfelse>
        <p>Google Authorization Failed.</p>
        <cfabort />
    </cfif>

    <!---remove soap: prefix or any other prefix from nodes that have it --->
    <cfset responseXML = responseXML.ReplaceAll("(</?)(\w+:)","$1") />
    <!--- remove xmlns: --->
    <cfset responseXML = responseXML.ReplaceAll("xmlns(:\w+)?=""[^""]*""","") />
    <!--- remove xsi element prefixes --->
    <cfset responseXML = responseXML.ReplaceAll('(/?)(xsi:)','$1') />

    <cfreturn responseXML />
</cffunction>

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Adwords API</title>
</head>
<body>
<cfoutput>

<!---Campaign Info --->
<cfsavecontent variable="CampaignRequestXML">
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns="https://adwords.google.com/api/adwords/cm/v201003">
	<soapenv:Header>
		<RequestHeader>
            <authToken>#application.adw_loginAuth#</authToken>
            <userAgent>V2010 Get All Campaign Info</userAgent>
            <developerToken>#api.devtoken#</developerToken>
            <clientEmail>#api.clientEmail#</clientEmail>
        </RequestHeader>
    </soapenv:Header>
    <soapenv:Body>
    	<get>
        	<selector>
            	<ids></ids>
					<statsSelector>
						<dateRange>
							<min>#api.startDate#</min>
							<max>#api.endDate#</max>
						</dateRange>
                        <startDate/>
						<endDate/>
                        <network>ALL</network>
						<clicks/>
						<impressions/>
					</statsSelector>
            </selector>
        </get>
    </soapenv:Body>
</soapenv:Envelope>
</cfsavecontent>

<!--- http SOAP request and xml parse --->
<cfset CampaignResponseXML = adwordsSOAPresponse(CampaignRequestXML) />

<cfset CampaignEntryNodes = XmlSearch(CampaignResponseXML, '//entries/') />

<cfloop from="1" to="#ArrayLen(CampaignEntryNodes)#" index="num">
	<cfset entryStruct = StructNew() /> 

    	<cfset entryStruct.id = CampaignEntryNodes[num].id.XmlText />
        <cfset entryStruct.name = CampaignEntryNodes[num].name.XmlText />
        <cfset entryStruct.status = CampaignEntryNodes[num].status.XmlText />
        <cfset entryStruct.clicks = CampaignEntryNodes[num].campaignStats.clicks.XmlText />
        <cfset entryStruct.impressions = CampaignEntryNodes[num].campaignStats.impressions.XmlText />

		<cfset totalClicks = totalClicks + CampaignEntryNodes[num].campaignStats.clicks.XmlText />
        <cfset totalImpressions = totalImpressions + CampaignEntryNodes[num].campaignStats.impressions.XmlText />
        <cfset arrayAppend(campaignStatsArray,duplicate(entryStruct)) />

</cfloop>

<cfdump var="#campaignStatsArray#">
<p>Total clicks: #totalClicks#<br />
Total Impressions: #totalImpressions#</p>

</cfoutput>
</body>
</html>

Using jQuery Autocomplete to Populate Another Autocomplete – ASP.NET, ColdFusion, and PHP Examples

As requested, this post covers using one jquery autocomplete to populate another jquery autocomplete on the same page. This example will use a jquery autocomplete to choose a state then, based on the state, another jquery autocomplete will be populated with zip codes for that state. Basically, the state chosen gets used as a filter in the query for the second autocomplete.

Form

The form for the examples is the same with fields for the autocompletes (state and zip_code) plus input fields for the values returned by the autocompletes.

<form action="YOUR-FILE-HERE"  method="post">
<fieldset>
<legend>jQuery UI Multi-Autocomplete Example</legend>
<p>Start typing the name of a state or territory of the United States</p>

<p><label for="state">State (abbreviation in separate field): </label>
<input type="text" id="state"  name="state" /> <input readonly="readonly" type="text" id="abbrev" name="abbrev" maxlength="2" size="2"/></p>

<input type="hidden" id="state_id" name="state_id" />

<p><label for="zip_code">Zip (only Zips from state selected above): </label>
<input type="text" id="zip_code" name="zip_code" maxlength="5" size="15" /></p>

<p class="ui-widget"><label for="city">City:</label>
<input readonly="readonly" type="text" id="city" name="city" /></p>

<p><input type="submit" name="submit" value="Submit" /></p>
</fieldset>
</form>

jQuery

The jquery is also the same for each example. Notice that the zip_code field is initially disabled to prevent entry before the results have been filtered.

Also, note that the source and secondary URL extension will have to be modified depending on the language you are using.

$(function() {

			//clear values on refresh
			$('#abbrev').val("");
			$('#city').val("");

			$("#zip_code").attr('disabled', true);

			$("#state").autocomplete({
				source: "states.[cfm|aspx|php]",
				minLength: 2,
				select: function(event, ui) {
					$('#state_id').val(ui.item.id);
					$('#abbrev').val(ui.item.abbrev);
					$("#zip_code").attr('disabled', false);
				},
				change: function(event, ui){
					secondary_url = "zips.[cfm|aspx|php]?filter=" + ui.item.abbrev;
					$("#zip_code").autocomplete("option", "source", secondary_url);
				}
			});

			$("#zip_code").autocomplete({
				source: "",
				minLength: 2,
				select: function(event,ui){
					$('#city').val(ui.item.city);
				}
			});

		});

Processing

Each programming language differs slightly in the processing. And, since there are hundreds of zip codes per state, the results are limited to 20. If the zip code desired is not returned in the top 20 after entering the minimum 2 characters, typing more characters will yield more precise results.

PHP

Refer to the example for using the jquery autocomplete with PHP. The code below only shows the zip select database processing.

PDO version

/* Connection vars here for example only. Consider a more secure method. */
$dbhost = 'YOUR_SERVER';
$dbuser = 'YOUR_USERNAME';
$dbpass = 'YOUR_PASSWORD';
$dbname = 'YOUR_DATABASE_NAME';

try {
  $conn = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
}
catch(PDOException $e) {
    echo $e->getMessage();
}

$return_arr = array();

if ($conn)
{
	$ac_filter = $_GET['filter'];
	$ac_term = $_GET['term']."%";
	$query = "SELECT zip, city FROM zips WHERE abbrev = :filter AND zip like :term  LIMIT 20";
	$result = $conn->prepare($query);
	$result->bindValue(":filter",$ac_filter);
	$result->bindValue(":term",$ac_term);
	$result->execute(); 

	/* Retrieve and store in array the results of the query.*/
	while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
		$row_array['label'] = $row['zip'] . " " . $row['city'];
		$row_array['value'] = $row['zip'];
		$row_array['city'] = $row['city'];

        array_push($return_arr,$row_array);
    }

}
/* Free connection resources. */
$conn = null; 

/* Toss back results as json encoded array. */
echo json_encode($return_arr);

Non-PDO version

<?php
$dbhost = 'YOUR_SERVER';
$dbuser = 'YOUR_USERNAME';
$dbpass = 'YOUR_PASSWORD';
$dbname = 'YOUR_DATABASE_NAME';

$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ('Error connecting to mysql');
mysql_select_db($dbname);

$return_arr = array();

if ($conn)
{
	$fetch = mysql_query("SELECT zip, city FROM zips WHERE abbrev = '" . mysql_real_escape_string($_GET['filter']) . "' AND zip like '" . mysql_real_escape_string($_GET['term']) . "%' LIMIT 20"); 

	/* Retrieve and store in array the results of the query.*/

	while ($row = mysql_fetch_array($fetch, MYSQL_ASSOC)) {
		$row_array['label'] = $row['zip'] . " " . $row['city'];
		$row_array['value'] = $row['zip'];
		$row_array['city'] = $row['city'];

        array_push($return_arr,$row_array);
    }

}
/* Free connection resources. */
mysql_close($conn);

/* Toss back results as json encoded array. */
echo json_encode($return_arr);
?>

ASP.NET

Refer to the complete example of using the jquery autocomplete with ASP.NET for more information.

<%@ Page Language="VB" Debug="false" %>
<%@ Import Namespace="System.Web.Script.Serialization" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>

<script runat="server">
    Dim serializer As JavaScriptSerializer

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
        serializer = New JavaScriptSerializer()
        Response.Write(JSONData(Request.QueryString("Term")))
    End Sub

    Public Class Zip
        Public zipcode As String
		Public label As String
		Public value As String
        Public city As String
    End Class

    Private Function JSONData(ByVal term As String) As String

        Dim zipArray As New ArrayList
        Dim index As Integer = 0

        Dim objConn As New SqlConnection("Server=YOUR-SERVER;Database=YOUR-DATABASE;User ID=YOUR-USERID;Password=YOUR-PASSWORD")
        Dim myds As New DataSet("Zips")

        objConn.Open()

        Dim adapter As New SqlDataAdapter("SELECT TOP 20 zip, city FROM zips WHERE abbrev = @ac_filter AND zip like @ac_term + '%'", objConn)
        adapter.SelectCommand.Parameters.Add("@ac_filter", SqlDbType.VarChar)
        adapter.SelectCommand.Parameters("@ac_filter").Value = Request.QueryString("filter")
        adapter.SelectCommand.Parameters.Add("@ac_term", SqlDbType.VarChar)
        adapter.SelectCommand.Parameters("@ac_term").Value = term
        adapter.Fill(myds, "Zips")

        For Each dr As DataRow In myds.Tables(0).Rows
            Dim zp As New Zip()
            zp.label = dr("zip").ToString() & " " & dr("city").ToString()
            zp.value = dr("zip").ToString()
            zp.city = dr("city").ToString()
            zipArray.Add(zp)
        Next

        objConn.Close()

        Return serializer.Serialize(zipArray)
    End Function

</script>

ColdFusion

Refer to the complete example of using the jquery autocomplete with ColdFusion for more information.

ColdFusion’s serializeJSON function has an odd bug that will not let you send numbers as strings. This turns the zip codes into numbers which we do not want. To workaround this, I added a space in front of the zip code then removed it from the JSON output with the Replace function. Not the best idea, but it works.

<cfset returnArray = ArrayNew(1) />

<cfquery name="qryStates" dataSource="autocomplete">
	SELECT TOP 20 zip, city FROM zips WHERE abbrev = '<cfqueryparam value="#URL.filter#" cfsqltype="cf_sql_varchar">' AND zip like '<cfqueryparam value="#URL.term#" cfsqltype="cf_sql_varchar">%'
</cfquery>

<cfloop query="qryStates">
	<cfset zipsStruct = StructNew() />
    <cfset zipsStruct["label"] = ToString(zip) & " " & city />
    <!---Had to add leading space to prevent serializeJSON from turning zip into number--->
    <cfset zipsStruct["value"] = " " & zip />
    <cfset zipsStruct["city"] = city />

    <cfset ArrayAppend(returnArray,zipsStruct) />
</cfloop>

<cfoutput>
<!---replaced all spaces after quotes with just quotes in JSON to remove leading space applied to zip--->
#Replace(serializeJSON(returnArray),'" ','"',"all")#
</cfoutput>

Very important information below. Please read and understand before expecting the autocomplete to work properly.

Explanation on the ‘label’ and ‘value’ fields from the jQuery UI site:

The local data can be a simple Array of Strings, or it contains Objects for each item in the array, with either a label or value property or both. The label property is displayed in the suggestion menu. The value will be inserted into the input element after the user selected something from the menu. If just one property is specified, it will be used for both, eg. if you provide only value-properties, the value will also be used as the label.”

Recommended:

Demo using PHP

Generating Signatures in ColdFusion with RSA-SHA1 for Secure AuthSub in Google Analytics

To send secure AuthSub requests to Google Analytics, you have to sign the request with a private key that is verified against the certificate you upload to Google. Google has a library where this can be done in Java that is specific to Google Analytics and, provided you can add .jar files to your ColdFusion server or use javaloader, you can run them using ColdFusion. If you need to roll your own or simply want to control the process, this example may help.

Before you implement any code that signs requests, the keys and certificate must be generated and then registered with Google you are attempting to access. Google has instructions on how to generate the keys and certificate using OpenSSL and how to register the certificate with Google. You will need the private key in the PKCS#8 format.

Google also supplies instructions for signing the AuthSub requests which is what we will step through here.

To get a single-use token for secure AuthSub, you send the user to authenticate through Google with a link similar to this:

<a href="https://www.google.com/accounts/AuthSubRequest?next=YOUR_PAGE_HERE?secureAuth=yes&scope=https://www.google.com/analytics/feeds/&secure=1&session=1">Log in using Secure AuthSub through Google</a>

Notice that secure is set to 1 indicating we want to send secure requests. Session is also set to 1 indicating we want a multi-use authorization token for multiple calls to the Google Analytics Data Export API. If you are only making one call to the API, you can set session to 0 (zero).

Google will then the user to your page designated by the next parameter with the token attached as a URL parameter called “token.” After getting this single-use token back from Google, you then need to send it back to Google to exchange for your multi-use token. This is where the signing begins. Every request from this point forward needs to be signed.

Secure AuthSub differs from AuthSub in that it requires several parameters to be added to the Authorization header of the request. They are:

  1. token: single-use token (or multi-use token once you get it) from Google
  2. sigalg: rsa-sha1
  3. data: the http-method, request URL, timestamp, and nonce all separated by a space.
  4. sig: the signature made by the private key generated against the data parameter above.

Generating this only requires a few lines of ColdFusion code:

        <cfset Math = createObject('java','java.lang.Math') />
        <cfset randNum = createObject('java', 'java.security.SecureRandom') />
        <cfset numeric_nonce = Math.abs(JavaCast("long",randNum.nextLong())) />
        <cfset nonce = numeric_nonce.toString() />
        <cfset timestmp = DateDiff("s",DateConvert("utc2Local", "January 1 1970 00:00"), Now()) />

        <cfset appSignature = rsa_sha1(rsaPrivateKey, 'GET https://www.google.com/accounts/AuthSubSessionToken ' & timestmp & ' ' & nonce) />

        <cfset authHeaderValue = 'AuthSub token="' & URL.token & '" data="GET https://www.google.com/accounts/AuthSubSessionToken ' & timestmp & ' ' & nonce & '" sig="' & appSignature & '"  sigalg="rsa-sha1"' />

The rsa_sha1 function creates the signature. It was written by Sharad Gupta and used here with permission.

<cffunction name="rsa_sha1" returntype="string" access="public" descrition="RSA-SHA1 computation based on supplied private key and supplied base signature string.">
    <!---Written by Sharad Gupta sharadg@gmail.com (used with permission)--->
           <cfargument name="signKey" type="string" required="true" hint="base64 formatted PKCS8 private key">
           <cfargument name="signMessage" type="string" required="true" hint="msg to sign">
           <cfargument name="sFormat" type="string" required="false" default="UTF-8">

           <cfset var jKey = JavaCast("string", arguments.signKey)>
           <cfset var jMsg = JavaCast("string",arguments.signMessage).getBytes(arguments.sFormat)>

           <cfset var key = createObject("java", "java.security.PrivateKey")>
           <cfset var keySpec = createObject("java","java.security.spec.PKCS8EncodedKeySpec")>
           <cfset var keyFactory = createObject("java","java.security.KeyFactory")>
           <cfset var b64dec = createObject("java", "sun.misc.BASE64Decoder")>

           <cfset var sig = createObject("java", "java.security.Signature")>

           <cfset var byteClass = createObject("java", "java.lang.Class")>
           <cfset var byteArray = createObject("java","java.lang.reflect.Array")>

           <cfset byteClass = byteClass.forName(JavaCast("string","java.lang.Byte"))>
           <cfset keyBytes = byteArray.newInstance(byteClass, JavaCast("int","1024"))>
           <cfset keyBytes = b64dec.decodeBuffer(jKey)>

           <cfset sig = sig.getInstance("SHA1withRSA", "SunJSSE")>
           <cfset sig.initSign(keyFactory.getInstance("RSA").generatePrivate(keySpec.init(keyBytes)))>
           <cfset sig.update(jMsg)>
           <cfset signBytes = sig.sign()>

           <cfreturn ToBase64(signBytes)>
     </cffunction>

The request for and parsing out of the multi-use token looks like this:

<cfhttp url="https://www.google.com/accounts/AuthSubSessionToken" method="GET">
 <cfhttpparam name="Authorization" type="header" value="#authHeaderValue#">
</cfhttp>

<cfset output = cfhttp.filecontent />

<cfset authSubSessionToken = Mid(output, FindNoCase("Token=",output) + (Len("Token=")), Len(output)) />

Any more requests of the Data Export API have to be made in the same manner except now you will use the multi-use token (authSubSessionToken) as the token in the Authorization header.

Recommended

ColdFusion Session Timeout with Warning and jQuery Session Refresh

There are times when a user needs to sit on a page for a while either to read or fill out a long form. If their visit is controlled by a session timeout, for example a member site, then the session needs to be refreshed without refreshing the page. My previous post on user session warning used a page refresh to renew the session. This example will refresh the session with a jquery .post so the browser maintains state.

Much of what happens here is very similar to the previous page reload session refresh so you will see some of the same explanatory text. Changes to the code mainly affect the jquery/javascript since the variables and timers need to be reset without refreshing the page.

Javascript is needed to keep track of the time the user has been sitting on the page. The server does not know how long they have been sitting there. It only knows whether or not a request comes in during a session or after the session has expired and acts accordingly at that time. Too late for a warning.

Session Defined: Start to Finish

A session is defined as when a user begins and ends using or visiting a web site. It can be unlimited in length or strictly defined by a timeout period. If the site requires a log in or accesses sensitive data, it should time out after a period of inactivity. They can end a session by logging out or closing the browser.

Inactivity means the user has done nothing, made no requests of the web server, during a specified time. Ajax requests usually do not count.

Demo

The session time left is determined by the server, and, if you want to poll the server with an Ajax request, go for it. Javascript is used to keep track of the time left in the session.

The demo uses a simple log in with session timing handled by jquery and javascript. When the session expiration approaches, the user is warned and given an opportunity to restart the session. If the session time limit is reached, the user is prompted to log in again. If they ignore that prompt, the page automatically redirects to the log in form. In the demo this sequence of events takes 40 seconds to complete and is broken down as follows:

  1. Session timeout: 30 seconds
  2. Timeout warning: 20 seconds
  3. Session expired warning: 10 seconds
  4. Redirect to log in page: 10 seconds

Interrupting the User

The user’s attention can be diverted away from other open windows to the eminent session expiration by using a javascript alert in place of the jquery dialog box. Personal preference.

Code Breakdown

The application.cfc controls the session by creating non-persistent cookies for CFID and CFTOKEN so the session expires when the user’s browser closes. It also sets the session variable sessionStartTime. The sessionStartTime variable is used to illustrate the fact that the application.cfc function OnSessionStart only fires once. It does not fire every time a session is renewed or restarted.

RequestStartTime is set in the OnRequestStart function to provide a reference for comparison later. See “Just for Fun” section below.

<cfcomponent
    displayname="Application"
    output="false"
    hint="Handle the application.">

    <!--- Set up the application. --->
    <cfset THIS.Name = "sessionrefreshtest" />
    <cfset THIS.ApplicationTimeout = CreateTimeSpan(0,1,0,0) />
    <!--- CreateTimeSpan(days, hours, minutes, seconds) --->
    <cfset THIS.SessionTimeout = CreateTimeSpan(0,0,0,30) />
    <cfset THIS.SessionManagement = true />
    <cfset THIS.SetClientCookies = false />

    <cffunction
        name="OnSessionStart"
        access="public"
        returntype="void"
        output="false"
        hint="Fires ONLY ONCE when session first created and not when session renewed/restarted.">       

        <!---set cfid/cftoken as non-persistent cookies so session ends on browser close --->
        <cfif not IsDefined("Cookie.CFID")>
            <cflock scope="session" type="readonly" timeout="5">
                <cfcookie name="CFID" value="#session.CFID#">
                <cfcookie name="CFTOKEN" value="#session.CFTOKEN#">
                 <cfset session.SessionStartTime = Now() />
            </cflock>
        </cfif>

        <cfreturn />
    </cffunction>

    <cffunction
        name="OnRequestStart"
        access="public"
        returntype="boolean"
        output="true"
        hint="Fires at first part of page processing.">

        <!--- Define arguments. --->
        <cfargument
            name="TargetPage"
            type="string"
            required="true"
            />

        <cfset session.RequestStartTime = Now() />

        <cfreturn true />

    </cffunction>    

</cfcomponent>

The log in page checks for a query string variable called ‘expired’ and, if present, deletes the session loggedin variable. This is there because the code is going to control the expiration of the session eliminating the need to compensate for browser latency. The actual session start time the time the page loads can differ by several seconds. To avoid having to add time to the session or any other fancy guesswork, when the allotted session time has expired according to the javascript timer on the page, they are done – session over.

If they are logged in, they get bumped to the index page. The rest is the logic that handles the log in form.

Note: I would not recommend handling a log in form this way. This is for demonstration only.

<cfif isDefined("url.expired") AND url.expired>
    <cfset StructDelete(session,"loggedin") />
</cfif>

<cfif isDefined("form.username") AND isDefined("form.pw") AND form.username EQ "session" AND form.pw EQ "test">
    <cfset session.loggedin = true />
</cfif>

<cfif StructKeyExists(session, "loggedin") AND session.loggedin>
    <cflocation url="index.cfm" addToken="no" />
</cfif>

Other than the log in form and a message for the user, that’s all there is to the log in page.

Handling Session Timeout

The index page handles the session timeout code. This could be a separate javascript included in every page. The first block simply determines if they are logged in. If they are not, send them to the login page. If they are, load the index page.

<!---if not logged in, send them to login page, else load the index page--->
<cfif NOT StructKeyExists(session, "loggedin") OR NOT session.loggedin>
    <cflocation url="login.cfm" addToken="no" />
<cfelse>
 <!---Load the page --->
</cfif>

Now the time variables are set and the a javascript timer is set to check the session every 10 seconds.
Javascript uses milliseconds so for clarity the time intervals multiply the number of seconds by 1,000. You could put 10000 in for 10 seconds but I think 10*1000 helps me determine that it is 10 seconds quite a bit faster. Do what is comfortable for you.

Also, a flag is set to determine if the warning dialog box has been opened and the countdown has begun.

//Your timing variables in number of seconds
//total length of session in seconds
var sessionLength = 30;
//time warning shown (10 = warning box shown 10 seconds before session starts)
var warning = 10;
//time redirect forced (10 = redirect forced 10 seconds after session ends)
var forceRedirect = 10; 

$(document).ready(function() {
	//event to check session time left (times 1000 to convert seconds to milliseconds)
    checkSessionTimeEvent = setInterval("checkSessionTime(requestTime)",10*1000);
});

//event to check session time variable declaration
var checkSessionTimeEvent = "";

//time session started
var requestTime = new Date();

//initial set of number of seconds to count down from for countdown ticker (10,9,8,7...you get the idea)
var countdownTime = warning;
//create event to start/stop countdownTicker
var countdownTickerEvent = ""; 

//initially set to false. if true - warning dialog open; countdown underway
var warningStarted = false;

function checkSessionTime(reqTime)
{
	//get time now
	var timeNow = new Date(); 

	//clear any countdownTickerEvents that may be running
	clearInterval(countdownTickerEvent);

	//difference between time now and time session started variable declartion
	var timeDifference = 0;

	//session timeout length
	var timeoutLength = sessionLength*1000;

	//set time for first warning, ten seconds before session expires
	var warningTime = timeoutLength - (warning*1000);

	//force redirect to log in page length (session timeout plus 10 seconds)
	var forceRedirectLength = timeoutLength + (forceRedirect*1000);

	timeDifference = timeNow - reqTime;

     if (timeDifference > warningTime && warningStarted === false)
        {
            //reset number of seconds to count down from for countdown ticker
			countdownTime = warning;

			//call now for initial dialog box text (time left until session timeout)
            countdownTicker(); 

            //set as interval event to countdown seconds to session timeout
            countdownTickerEvent = setInterval("countdownTicker()", 1000);

            $('#dialogWarning').dialog('open');
			warningStarted = true;
        }
    else if (timeDifference > timeoutLength)
    	{
    		//close warning dialog box if open
            if ($('#dialogWarning').dialog('isOpen')) $('#dialogWarning').dialog('close');

            $('#dialogExpired').dialog('open');

        }

     if (timeDifference > forceRedirectLength)
     	{
        	//clear (stop) checksession event
            clearInterval(checkSessionTimeEvent);

            //force relocation
            window.location="login.cfm?expired=true";
        }
}

The countdownTicker function provides a countdown inside the warning dialog box to prompt the user to act now. It uses a timer that fires every second for a 5,4,3,2,1 effect inside the dialog box.

function countdownTicker()
{
	//put countdown time left in dialog box
	$("span#dialogText-warning").html(countdownTime);

	//decrement countdownTime
	countdownTime--;
}

And, the dialog boxes either allow the user to restart the session or, if they did nothing when the warning popped up, it logs them out by redirecting to the log in page with the expired variable in the query string. Also, it redirects to the log in if they hit the close button on the dialog box rather than the Login button on the dialogExpired dialog box.

$(function(){
        // jQuery UI Dialog
        $('#dialogWarning').dialog({
            autoOpen: false,
            width: 400,
            modal: true,
            resizable: false,
            buttons: {
                "Restart Session": function() {
		   //reset session on server
                  $.post("restart_session.cfm");

		   //reset the variables
		   requestTime = new Date();
		   warningStarted = false;
		   countdownTime = warning;

		   //clear current checkSessionTimeEvent and start a new one
		   clearInterval(checkSessionTimeEvent);
		   checkSessionTimeEvent = "";
		   checkSessionTimeEvent = setInterval("checkSessionTime(requestTime)",10*1000);

		    $('#dialogWarning').dialog('close');
                }
            }
        });

        $('#dialogExpired').dialog({
            autoOpen: false,
            width: 400,
            modal: true,
            resizable: false,
            close: function() {
                   window.location="login.cfm?expired=true";
            },
            buttons: {
                "Login": function() {
                    window.location="login.cfm?expired=true";
                }
            }
        });
});

The “Restart Session” button sends a post request to a ColdFusion page that sets a session variable. That act alone refreshes the session.

<!---Setting the give_me_more_time session variable refreshes the session.--->
<cfset session.give_me_more_time = true />
<!--- Below is optional. There just so you can see a response from the server in firebug. --->
<cfoutput>session.RequestStartTime: #session.RequestStartTime# session.loggedin: #session.loggedin#</cfoutput>

The dialog box contents are at the bottom of the page but they could be just about anywhere in the body.

<!--Dialog box contents-->
<div id="dialogExpired" title="Session (Page) Expired!"><p><span class="ui-icon ui-icon-alert" style="float:left; margin:0 7px 0 0;"></span> Your session has expired!<p id="dialogText-expired"></p></div>

<div id="dialogWarning" title="Session (Page) Expiring!"><p><span class="ui-icon ui-icon-alert" style="float:left; margin:0 7px 0 0;"></span> Your session will expire in <span id="dialogText-warning"></span> seconds!</div>

Just for Fun

You can view the response from the restrart_session.cfm in Firebug and compare it to the time on the page from the dumped session vars.
session time compare

Usual recommended jQuery and CF reading:

Download zip of all files