I am trying to implement the OAuth with Dropbox from a ColdFusion application, and I managed how to call the Dropbox method to generate the access token, but... I don't know how to get the generated TOKEN from the response URI. I am getting something like this from Dropbox:
http://localhost/dropbox/generate_token.cfm#access_token=AAAAAAAAYVM_XdCYlbTz0gQOwQkWlg6TDXf84_5h4giikg6J-7Man&token_type=bearer&uid=267693&account_id=dbid%3AAABeDMm-BN0n1DofLZz9kPZAipnQ
How to I retrieve the URL variables in this case? I mean if I do a
<cfdump var="#URL#">
I am getting an empty struct. If I do a
<cfdump var="#CGI#">
I still don't see any of the URL retrieved parameters in the structure. How do I get the variables and their values from the Dropbox response?
UPDATED
At some point I thought I found a way to read the URL but now - for no reason - this doesn't work anymore! I didn't change anything but the solution below doesn't work anymore.
I can read the full URL with JavaScript using document.location but this means to do an extra submit to a ColdFusion page and I don't want to do this. I want to get the Dropbox token from the URL and save it to the database directly in this page...
Any new ideas please?
SOLUTION THAT SEEMED TO WORK AT SOME POINT ...
I found a way to get the URI string using this:
<cfset objRequest = GetPageContext().GetRequest().getParameterMap() />
<cfdump var="#objRequest#">
<cfoutput>
<cfloop collection="#objRequest#" item="i">
<p>
#i# - #objRequest[i][1]#
</p>
</cfloop>
</cfoutput>
From now on, I know how to get the values returned by Dropbox.
I found a way to get the returned parameters by reading the browser URL with JavaScript, so in two steps: first, parse and extract the full URL including the part after the # sign (I found this has a name and it is called the "URL fragment") and second, create a JavaScript form with parsed parameters and resubmitted to the server. Here is the code:
<cfparam name="FORM.action" default="">
<cfif FORM.action IS "save_token">
<cfdump var="#FORM#">
<cfelse>
<form name="main" id="main" method="post">
<input type="hidden" name="action" id="action" value="save_token">
</form>
<script type="text/javascript" language="javascript">
<!--
var parameters = window.location.hash.substr(1).split("&");
function addHidden(theForm, key, value) {
// Create a hidden input element, and append it to the form:
var input = document.createElement("input");
input.type = "hidden";
input.name = key;
input.value = value;
theForm.appendChild(input);
}
// Form reference:
var theForm = document.forms["main"];
for (var i=0; i<parameters.length; i++) {
// Add data:
addHidden(theForm, parameters[i].split("=")[0], parameters[i].split("=")[1]);
}
theForm.submit();
//-->
</script>
</cfif>
Related
I recently started learning coldfusion. I am getting a bit confused, reading through numerous websites regarding the function cfhttp.filecontent.
Can any of you help me understand and provide me with an example of how I would format the following code I am writing? I am already grabbing name and email from a form on the index page and trying to initiate an API request and get the password back, formatted correctly.
<cfset passwordcomplexity = 4>
<cfinclude template='header.cfm'>
<cfhttp method="GET" url="https://hardest.pw/api/#passwordlenght#/#passwordcomplexity#">
<cfset returnString = cfhttp.filecontent>
<cfdump var="#returnString#">
<!---<cfmail to="#form.email#"
from="no-reply#training-pavel.com"
subject="New random password"
type="text">
Hey there, #form.name#!
We've just generated a new password for you! You can see it below:
</cfmail>--->
<cfinclude template='footer.cfm'>
At the end I just get something like this:
{"code":200,"desc":"Command completed successfully","password":"[&Vo4%T#l8","hardestlink":"https:\/\/hardest.pw\/0758828a-a6f6-4f9b-9bd7-c0dc778de0b7"}
I am new to coldfusion ,
please check my code below
<cfif isDefined("form.submit")>
<cfoutput>
<h3>hi</h3>
</cfoutput>
</cfif>
<cfform action="#CGI.SCRIPT_NAME#">
User Name:<cfinput type="Text" name="usr_nm"><br>
<cfinput type="Radio" name="access_flg" value="0">Admin
<cfinput type="Radio" name="access_flg" value="1">User</br>
<cfinput type="submit" name="submit" value="submit"><br>
</cfform>
But ,When I am clicking submit button ,I am expecting result as hi
I haven't see hi message, Is there any thing wrong in my code ,Any one please help me
Since you're new to ColdFusion, I'll give you some advice straight away:
1. Do not submit a form to the same page.
Submit the form to a separate page for processing. Reason being, as you get into more advanced applications, you'll need to restrict pages/URLs to only respond to an appropriate HTML Verb.
Your form page should respond to HTTP GET.
Your form processing page should only respond to HTTP POST.
2. Do not use CFFORM.
The function of CFFORM is to create JavaScript validation and server-side interactions. This can easily be done with modern JavaScript libraries like
https://jquery.com/
http://jqueryvalidation.org/
3. Give your form elements an ID, as well as a NAME.
This allows easier reference to the form elements when using JavaScript.
4. Do not name your submit button "submit".
If you ever want to use JavaScript to submit a form, the function is submit().
For example: $('#myForm').submit();
Having a form element named the same as a function will cause errors.
Here's my_form.cfm:
<form id="myForm" name="myForm" action="my_form_action.cfm" method="post">
User Name:<input type="Text" id="usr_nm" name="usr_nm"><br>
<input type="Radio" id="access_flg_0" name="access_flg" value="0">Admin
<input type="Radio" id="access_flg_1" name="access_flg" value="1">User</br>
<input type="submit" id="my_form_submit" name="my_form_submit" value="Submit"><br>
</form>
5. You don't need to use CFOUTPUT unless you are rendering data from the server.
Here's my_form_action.cfm:
<cfif structKeyExists(form, "my_form_submit")>
<h3>Hi!<lt>
</cfif>
Even better:
<cfif (cgi.request_method IS "post") AND (structKeyExists(form, "my_form_submit"))>
<h3>Hi!<lt>
</cfif>
This is an elaboration of this part of Adrian's answer:
<cfif (cgi.request_method IS "post") AND (structKeyExists form, "my_form_submit"))>
<h3>Hi!</h3>
</cfif>
This is a candidate for code re-use. In one of our applications, I wrote a custom tag that does something like this:
if (StructKeyExists(attributes, 'ScopeToCheck') is false)
attributes.ScopeToCheck = "form";
if (StructKeyExists(caller, attributes.ScopeToCheck) is false)
Redirect = true;
else if (StructIsEmpty(caller[attributes.ScopeToCheck]) is true)
Redirect = true;
else
Redirect = false;
if (Redirect == true)
location(somewhere, false);
The custom tag approach was appropriate for my situation. For other situations, the same logic can be put into a udf that returns either true or false. Then the calling page can decide what to do with that information.
I know how to upload an image file to a server and show the image file to a page.
But what if I want a preview on a confirmation page?
I can probably generate a temp file that isn't saved in the database but is a file in a physical location, but what if I decided to hit the "no" button. How would this temp file be deleted?
The code below shrinks the image and shows it on the page. But it also creates an image within the directory, that will stay there after I hit OK or NO. The NO is button, while the OK naturally is a submit.
<!--- Make Temp Image as Preview --->
<cfset mediapath = expandpath('../images/about')>
<cfif structKeyExists(form,"image") and len(form.image)>
<cffile action="upload"
filefield="image"
destination="#MediaPath#"
nameconflict="makeunique">
<cfimage name="uploadedImage"
source="#MediaPath#/#file.serverFile#" >
<cfset imagesize = 320>
<cfif uploadedImage.width gt uploadedImage.height>
<cfset percentage = (imagesize / uploadedImage.width)>
<cfelse>
<cfset percentage = (imagesize / uploadedImage.height)>
</cfif>
<cfset newWidth = round(uploadedImage.width * percentage)>
<cfset newHeight = round(uploadedImage.height * percentage)>
<!--- Show Image --->
<cfoutput>
<img src="../images/about/#file.serverFile#" style="height:#newHeight#; width:#newWidth#;">
I assume I may have to do URL Passing or do some sort of CFScript. On the Return buttons Onclick event.
Here is my approach take it for what you will.
Ok this is probably more than you need but this should get you somewhere on this image delete problem thing.
Here is your code. But I broke it into two pages. Of course I cannot see what else is going on this page and your form handling stuff so we will start with what you are giving us.
<cfset mediapath = expandpath('../images/about')>
nice use of structKeyExists() :)
<cfif structKeyExists(form,"image") and len(form.image)>
Here I would pause and suggest you limit
your uploads to just .gif, .jpeg, .jpg, .png
(your main image types) to prevent uploading any
and everyfile type. I added an accept parameter below.
<cffile action="upload"
filefield="image"
destination="#MediaPath#"
nameconflict="makeunique"
accept="image/*">
<cfimage name="uploadedImage"
source="#MediaPath#/#file.serverFile#" >
Ok the file is uploaded lets seperate concerns
At this point I would ask them if they want to preview the file. If they click 'preview' take them to a preview.cfm page.
Then you have a file name you need to pass if you have nothing else (like an ID or some primary key).
So I pulled this handy-dandy script out of the Adobe Coldfusion docs on their website and I am going to use this to turn your filename into 'something else' ;)
<cfscript>
theKey="123abc";
theKey=generateSecretKey("AES")
superDuperSecretSoDontTell=encrypt(file.serverFile, theKey, "AES", "hex");
</cfscript>
Let's send this piggy!
and off you go to the preview page...
<cfoutput>
(pointing up) This is pageA.cfm
(pointing down) This is pageB.cfm
Now I have the rest of your code below and lets pull your file based on the pass through querystring variable/value pairs.
<cfscript>
IWannaKnowTheSecret=decrypt(url.fileName, url.theKey, "AES", "hex");
</cfscript>
Here I would pause and suggest you limit
your uploads to just .gif, .jpeg, .jpg, .png
(your main image types) to prevent uploading any
and everyfile type. I added an accept parameter below.
<cffile action="read" file="#MediaPath##IWannaKnowTheSecret#" variable="uploadedImage">
<cfset imagesize = 320>
Interesting handle here. So you are taking the
larger of the two values and using that
to percentage down the size. Neat.
<cfif uploadedImage.width GT uploadedImage.height>
<cfset percentage = (imagesize / uploadedImage.width)>
<cfelse>
<cfset percentage = (imagesize / uploadedImage.height)>
</cfif>
<cfset newWidth = round(uploadedImage.width * percentage)>
<cfset newHeight = round(uploadedImage.height * percentage)>
Then do a form like this:
<form action="" method="post" enctype="multipart/form-data">
Your current Image:
<cfoutput>
Name: #uploadedImage#<br>
<img src="../images/about/#uploadedImage#" style="height:#newHeight#; width:#newWidth#;">
</cfoutput>
Do you want to remove this?<br>
<input type="checkbox"
name="removeImage"
value="1" />: Remove the logo image</cfif><br />
Wnat to replace your image?<br>
<input type="file" name="replacementImage"> (
<input type="hidden"
name="uploadedImage"
value="<cfoutput>#uploadedImage#</cfoutput>">
<input type="submit" value="submit" name="submit"
</form>
Cancel and go back
If they continue and want to fix the image or replace it. Submit then you can use something like this.
Then we delete...
And if the replacementImage file filed is populated then we add that file.
And there you have it...
You are seperating some concerns.
You are giving improved options.
You are allowing a change or no change.
You are giving them an out to go back to where ever you want.
Edit: Here is proof for the encoding and decoding stuff (if you wanted to play with it:
<cfscript>
theKey="123abc";
theKey=generateSecretKey("AES");
superDuperSecretSoDontTell=encrypt("monkeytoots", theKey, "AES", "hex");
</cfscript>
<cfoutput>Let's send this piggy!</cfoutput>
<cfif isdefined("url.fileName") and isdefined("url.theKey")>
<cfscript>
IWannaKnowTheSecret=decrypt(url.fileName, url.theKey, "AES", "hex");
</cfscript>
<cfoutput>
#IWannaKnowTheSecret#
</cfoutput>
</cfif>
This answer is in response to Adam Cameron's comment. It illustrates some potentially unexpected results that can occur with two submit buttons. Start with this code.
<cfdump var="#form#">
<form action="abc.cfm" method="post">
<input type="text" name="text1" />
<input type="submit" name="submit1" value="no" />
<input type="submit" name="submit2" value="yes" />
</form>
The default behaviour of most, if not all browsers is that there are occasions whereby a form will be submitted when the user presses the enter key. What would you expect to see with this form if you had your curser in the text box and pressed Enter? Try it and see if you were right.
I am working with a very old login system that my company used before on a website that used frames.
Before, when someone tried a wrong user/pass combination the frame would load a simple cfinclude file with the login form and an error message on top of it.
Now I am using a form in a popup window that calls the application.cfc but instead of getting the error message back on my popup window the page load the cfinclude file from the application component to a new page.
So I need a few things to happen for this application. First, I need the initial popup window to stay up and the page should not submit if the combination of user/pass is wrong, and finally I need the error message to appear somewhere on the popup.
If anyone did something like this before I would really appreciate your feedback.
This is a partial of my code:
Login Form:
<!--- loginErrMsg display - to tell why login is denied --->
<cfif isdefined("loginErrMsg")><span style="color:red">#loginErrMsg#</span><br /></cfif>
<form name="LoginForm" id="LoginForm" action="<cfif test is false>https://secure.example.com</cfif>#loginFormAction#" method="post" target="_top">
</cfoutput>
<input type="hidden" name="loginPost" value="true">
<p>
Login below to take advantage of the great services we offer:
</p>
E-mail:<input name="j_username" class="loginform" type="text" size="30" maxlength="50" id="j_username">
Password: <input name="j_password" type="password" size="30" maxlength="16" class="loginform">
<br />
<input type="submit" name="btn" value="Submit" class="bluebuttonnormal">
</form>
Application.cfc Code:
<cflogin applicationtoken="swmadmin">
<cfif NOT IsDefined("cflogin")>
<cfinclude template="login.cfm">
<cfabort>
<cfelse>
<cfquery name="userlookup" datasource="#ds#">
SELECT clientadminID, roles, isFaxOnly, acctEnabled FROM clientadmin
WHERE
username=<cfqueryparam value="#cflogin.name#" CFSQLTYPE="CF_SQL_VARCHAR" maxlength="50">
and password=<cfqueryparam value="#cflogin.password#" CFSQLTYPE="CF_SQL_VARCHAR" maxlength="16">
</cfquery>
<cfif userlookup.recordcount eq 0>
<cfset loginErrMsg = "Invalid login.">
<cfinclude template="login.cfm">
<cfabort>
</cflogin>
I am working with a very old login system that my company used before
on a website that used frames.
If this is a new website, don't use it. Login forms are a dime a dozen and can be done in your sleep. Start fresh and do it right.
So I need a few things to happen for this application. First, I need
the initial popup window to stay up and the page should not submit if
the combination of user/pass is wrong, and finally I need the error
message to appear somewhere on the popup.
You're going to want to use an AJAX solution here, either write your own or use a good library like jQuery. Once you check the login values you can use jQuery or simple javascript to unhide or update the innerHTML of an empty element to display your error message.
<cflogin ...>
...
</cflogin>
CFLogin makes me sad. Another one of ColdFusion's tags meant to simplify something commonly done that doesn't really help much and sacrifices flexibility. You can get far more control over your application without it. instead of CFLogin, try something like this pseudo code
<cfcomponent>
<cffunction name = "onRequest" ...>
<cfargument name="targetPage" type="String" required = "true" />
<cfif !structKeyExists(session, "roles") and !findNoCase("loginHandler.cfm",cgi.script_name)>
<!--- notice I prevent the redirect on the form handler, otherwise the ajax will get redirected to the login.cfm page --->
<cfinclude template = "login.cfm">
<cfelse>
<cfinclude template = "#arguments.targetPage#">
</cfif>
</cffunction>
</cfcomponent>
Your login.cfm would then contain your form but your button would fire something like jQuery.post() to "loginHandler.cfm", then depending on the result of the login, your callback function may use jQuery.html() to display the error or window.location.replace / window.location.href if the login was successful. Of course, in the event of a successful login, your ColdFusion page would have to create their session variables and do whatever else you want it to do before sending the result back to your AJAX call.
So, I'm using jsoup and when I display the content returned I Get:
{{#ifcond="" pagetitle="" this.name}}
I'm doing this like local.htmlObj.Body().Html()
When I need it to be return like:
{{#ifCond PAGETITLE this.NAME}}
Here what I'm doing
<cfset paths = [] />
<cfset paths[1] = expandPath("/javaloader/lib/jsoup-1.7.1.jar") />
<cfset loader = createObject("component", "javaloader.JavaLoader").init( paths ) />
<cfset obj = loader.create( "org.jsoup.Jsoup" ) />
<cfset local.htmlObj = local.jsoupObj.parse( local.template ) />
<cfloop array="#local.htmlObj.select('.sidebar_left')#" index="element">
<cfif element.attr('section') EQ "test">
<cfset element.append('HTML HERE') />
</cfif>
</cfloop>
local.template is my template that is made up of a ton of different handlebar files That im pulling for different places. I'm constructing one handlebar file that gets returned.
The problem is that JSoup is trying to parse invalid HTML before it lets you access it. A slight easier to understand example of this behavior can be seen if you fetch the following HTML (seen in this question):
<p>
<table>[...]</table>
</p>
It will return:
<p></p>
<table>[...]</table>
In your case the Handelbars code is seen as attributes which in valid html always have a value (think checked="checked"). As far as I can tell there is no way to disable this behavior. It's really the wrong tool for the job you are trying to do. A cleaner approach would be to just fetch the document as a stream and save it to a string.