Twilio Synch token in ColdFusion - json

ColdFusion being as obscure as it is, Twilio doesn't have any SDKs for it. I'm trying to give Synch a go; I'm not getting the JSON request for the access token correct. Trying to mimic what is done by their node.js example here, I thought I could just output the JSON to the page on token.cfm:
{
"identity":"#Username#",
"token":["#AccountSID#","#APPSID#","#SECRET#"]
}
This is called from index.cfm:
<script src="js/jquery.js" ></script>
<script src="https://media.twiliocdn.com/sdk/js/sync/releases/0.5.7/twilio-sync.min.js"></script>
<script>
function fetchAccessToken(handler) {
// We use jQuery to make an Ajax request to our server to retrieve our
// Access Token
$.getJSON('token.cfm', function(data) {
// The data sent back from the server should contain a long string, which
// is the token you'll need to initialize the SDK. This string is in a format
// called JWT (JSON Web Token) - more at http://jwt.io
console.log(data.token);
// Since the starter app doesn't implement authentication, the server sends
// back a randomly generated username for the current client, which is how
// they will be identified while sending messages. If your app has a login
// system, you should use the e-mail address or username that uniquely identifies
// a user instead.
console.log(data.identity);
handler(data);
});
}
$(document).ready(function()
{
fetchAccessToken(initializeSync);
function initializeSync(tokenResponse) {
var syncClient = new Twilio.Sync.Client(tokenResponse.token);
// Use syncClient here
}
});
</script>
The response I receive is
{code: 400, message: "Unable to process JSON"}
code:
400
message:
"Unable to process JSON"
Can I accomplish this? Or, alternately, can the token be built by JavaScript alone?

Your JS is a very roundabout way of writing this:
$(function() {
$.get('token.cfm').done(function (response) {
var syncClient = new Twilio.Sync.Client(response.token);
// ... use syncClient here
});
});
but this still requires that the response is actually parseable as JSON.
If your CFM page just contains this:
<cfoutput>
{
"identity":"#Username#",
"token":["#AccountSID#","#APPSID#","#SECRET#"]
}
</cfoutput>
then this almost certainly produces syntactically wrong JSON. Don't do that.
JSON is to be produced from a data structure and a serialization function, that's no different in ColdFusion than in any other language.
<cfset AccountSID = "...">
<cfset APPSID = "...">
<cfset SECRET = "...">
<cfset tokenData = {
"identity" = Username,
"token" = [AccountSID, APPSID, SECRET]
}>
<cfcontent type="application/json"><cfoutput>#SerializeJSON(tokenData)#</cfoutput>
There are other, nicer ways of creating JSON responses, most prominently CF components with functions annotated with the "json" returnformat, but doing it manually like above is enough for a one-off.

Related

Transferring a text file's contents over socket.io results in a ArrayBuffer object

I am a newbie with socket.io and have very little exposure to node.js as well
So I started from the simple chat app and built my way up
I can get text messages to be sent from a server to a client when the message comes from another client, like the chat demo app does
But when trying to have the server read a local file and send this contents over using io.emit, what the client side receives seems to be an instance of ArrayBuffer, which in any case confuses the JSON parser
More specifically, server side does
fs.watch('status.json',
function(event, filename){
fs.readFile('status.json',
function(err, data){
if (err) throw err;
io.emit("r2lab status", data);
});
});
and client side does
socket.on('r2lab status', function(json){
console.log("received JSON nodes_info " + json);
var nodes_info = JSON.parse(json);
/* etc.. */
which at run-time triggers this in Console
received JSON nodes_info [object ArrayBuffer]
r2lab.html:1 Uncaught SyntaxError: Unexpected token o
...
As the logic works when I am getting my input by another source than a file, this all strongly suggests that the data I am getting out of readFile is not a plain string but some kind of instance that somehow makes it to the client side; like if I had opened my input file in binary or something.
Could anyone suggest a means to get JSON.parse() to be happy with this scenario ? server-side or client-side, either way would be just fine with me.
Many thanks
You can use Uint8Array view to access that ArrayBuffer and then convert it to string:
socket.on('r2lab status', function(data){
var buffer = new Uint8Array(data)
var fileString= String.fromCharCode.apply(null, buffer)
var obj = JSON.parse(fileString)
});

Connect Parse with external database?

I am working on project where it is build using traditional technologies like PHP, mysql and it is a web application.
Now we want to build an app for mobile users on platform like Andoid, iOS.
So we are thinking to connect MySql with Parse.com database.
I know parse uses NoSql kind of database for storing objects.
So my question is can we connect parse database to any other SQL database ?
If yes then how we can do that ?
EDIT
#Luca laco I just created a new cloud function like you. which is below.
Parse.Cloud.define("get_parse4j_object",
function(request,response){
// Parameters from client (iOS/Android app)
//var requestedObjectId = request.params.objectId;
// Calling beckend service for getting user information
Parse.Cloud.httpRequest({
method: "GET",
headers: {
'Content-Type': 'application/json'
},
url: "https://api.parse.com/1/parse4j/MLiOgxncUM", /* This could be your url for the proper php module */
//body: { "objectId":requestedObjectId }, /* Here you compose the body request for the http call, passing the php parameters and their values */
success: function(httpResponse) {
/* We expect that the php response is a Json string, using the header('application/json'), so: */
var jsonResponse = JSON.parse(httpResponse.text);
/* sample structure in jsonResponse: { "name":"Joe", "surname":"Banana", "birth_date":"01-02-1999" } */
/* Do any additional stuff you need... */
/* return the result to your iOS/Android client */
return response.success( { "myRequestedUserInfo" : jsonResponse } );
alert(jsonResponse);
},
error: function(httpResponse) {
return response.error({ "msg":"Unable to fetch this user", "code":123456 }); // sample error response
}
});
});
I followed the same way which Luca Laco explained me.
But I am getting error when I am calling function from client JS.
This is my client JS
<script type="text/javascript">
Parse.initialize("APP_ID", "JAVASCRIPT_KEY");
Parse.Cloud.run('get_parse4j_object', {}, {
success: function(result) {
alert(result);
},
error: function(error) {
alert(JSON.stringify(error));
}
});
</script>
In the network tab I can see
POST https://api.parse.com/1/functions/get_parse4j_object 400 (Bad Request)
and error is: {"code":141, "message":"function not found"}
Where I am missing and doing wrong ?
If you mean something like a common mysql connector, then the response is no, you can't. At now, The only way to make parse and something else in relation, is to query from and to Parse. To be clear:
If you want to get a value from Parse, that is stored in mysql, you have to use a http request to a specific php module stored on your php website ( and implemented by you ) that expect some paramenter, and return the result in a specific way, normally in json format, using also the http header application/json.
If you want to get a value from php, that is stored on the parse db, you can run a REST call from php following the spec on the parse website ( https://parse.com/docs/rest/guide/ ), or simply using the php sdk ( https://github.com/ParsePlatform/parse-php-sdk ). Take a look also to the Parse Webhooks.
From what i understood, you already have a working web service, so doing this, you would just proxy the resources stored on your server on mysql to your clients through Parse. In other words you should create a Parse Cloud function for each type of information you want to retrieve on the clients using the Parse SDK (for iOS or Android) and another Parse Colud function for each action you perform on your devices and you want to save on your mysql db, always through Parse system.
My personal opinion, is to stay on Mysql, especially because on Parse we still have a lot of limitation on the queries ( no group by, no distinct, query timeout, etc. ), while seems to be a really good service for the push notification. Anyway all this depends by the complexity of your software and as i said, is just my opinion.
[Edit]
Here an example:
In Parse cloud code, let's make a cloud function called 'get_user_info'
Parse.Cloud.define("get_user_info",
function(request,response){
// Parameters from client (iOS/Android app)
var requestedUserId = request.params.user_id;
// Calling beckend service for getting user information
Parse.Cloud.httpRequest({
method: "POST",
url: "https://www.yourPhpWebsite.com/getUser.php", /* This could be your url for the proper php module */
body: { "php_param_user_id":requestedUserId }, /* Here you compose the body request for the http call, passing the php parameters and their values */
success: function(httpResponse) {
/* We expect that the php response is a Json string, using the header('application/json'), so: */
var jsonResponse = JSON.parse(httpResponse.text);
/* sample structure in jsonResponse: { "name":"Joe", "surname":"Banana", "birth_date":"01-02-1999" } */
/* Do any additional stuff you need... */
/* return the result to your iOS/Android client */
return response.success( { "myRequestedUserInfo" : jsonResponse } );
},
error: function(httpResponse) {
return response.error({ "msg":"Unable to fetch this user", "code":123456 }); // sample error response
}
});
});
The sample 'getUser.php' module could be
<?php
$expectedUserId = $_POST['php_param_user_id'];
// query your MySql db using passed user id
$query = "SELECT name,surname,birth_date FROM MyUserTable Where id = ".$expectedUserId;
// perform your query (the above one is just an example, would be better to use PDO and any other check, just to avoid SQL Injection)
// ...
// ..
// .
$resultQuery = row[0];
// sample json structure
$jsonResponseToParse = '{ "name":'.resultQuery["name"].', "surname":'.resultQuery["surname"].', "birth_date":'.resultQuery["birth_date"].' }';
header('application/json');
echo jsonResponseToParse;
exit();
?>
Hope it helps

Parse JSON returned from NODE.js

I’m using jQuery to make an AJAX call to Node.js to get some JSON. The JSON is actually “built” in a Python child_process called by Node. I see that the JSON is being passed back to the browser, but I can’t seem to parse it—-although I can parse JSONP from YQL queries.
The web page making the call is on the same server as Node, so I don’t believe I need JSONP in this case.
Here is the code:
index.html (snippet)
function getData() {
$.ajax({
url: 'http://127.0.0.1:3000',
dataType: 'json',
success: function(data) {
$("#results").html(data);
alert(data.engineURL); // alerts: undefined
}
});
}
server.js
function run(callBack) {
var spawn = require('child_process').spawn,
child = spawn('python',['test.py']);
var resp = '';
child.stdout.on('data', function(data) {
resp = data.toString();
});
child.on('close', function() {
callBack(resp);
});
}
http.createServer(function(request, response) {
run(function(data) {
response.writeHead(200, {
'Content-Type':
'application/json',
'Access-Control-Allow-Origin' : '*' });
response.write(JSON.stringify(data));
response.end();
});
}).listen(PORT, HOST);
test.py
import json
print json.dumps({'engineName' : 'Google', 'engineURL' : 'http://www.google.com'})
After the AJAX call comes back, I execute the following:
$("#results").html(data);
and it prints the following on the web page:
{“engineURL": "http://www.google.com", "engineName": "Google"}
However, when I try and parse the JSON as follows:
alert(data.engineURL);
I get undefined. I’m almost thinking that I’m not actually passing a JSON Object back, but I’m not sure.
Could anyone advise if I’m doing something wrong building the JSON in Python, passing the JSON back from Node, or simply not parsing the JSON correctly on the web page?
Thanks.
I’m almost thinking that I’m not actually passing a JSON Object back, but I’m not sure.
Yes, the ajax response is a string. To get an object, you have to parse that JSON string into an object. There are two ways to do that:
data = $.parseJSON(data);
Or, the recommended approach, specify dataType: 'json' in your $.ajax call. This way jQuery will implicitly call $.parseJSON on the response before passing it to the callback. Also, if you're using $.get, you can replace it with $.getJSON.
Also:
child.stdout.on('data', function(data) {
resp = data.toString();
// ^ should be +=
});
The data event's callback receives chunks of data, you should concatenate it with what you've already received. You probably haven't had problems with that yet because your JSON is small and comes in a single chunk most of the time, but do not rely on it, do the proper concatenation to be sure that your data contains all the chunks and not just the last one.

Sending data from Dart to PHP using POST method

I am trying to send some data from Dart to PHP...
This is the code i am using to send the data from Dart:
button.onClick.listen((e) {
var req = new HttpRequest();
req.onReadyStateChange.listen((HttpRequestProgressEvent e) {
if (req.readyState == HttpRequest.DONE) {
print('Data submitted!');
}
});
req.open('POST', form.action);
req.send('hello from dart');
});
In my PHP file I am trying to use the string i have send from dart, but count($_POST) returns 0. $_POST seems to be empty...
Dart code DOES trigger the php script and 'Data submitted' is printed...
This is actually related to your PHP configuration. You can access the POST'd data with PHP's reserved variable: $HTTP_RAW_POST_DATA However the preferred method is to use php://input
I am very new to Dart, but you can use FormData in the send. So a quick and dirty way could be.
var data_form = new FormData(query('#My_form'));
button.onClick.listen((e){
var request = new HttpRequest():
request.open('POST', 'http://Localhost/form_data.php');
request.send(data_form);

How do I get the cookie values in a backbone.js model?

I have a simple Backbone.js/Bootstrap front end in HTML5 with a Node.js/Restify backend. I am setting cookies in a header response from the server as below:
res.setHeader("Set-Cookie", ["token=ninja", "language=javascript"]);
On the client side, I am making a REST call as
var response = this.model.fetch().success(function(data){
//success
}).error(function(data){
//error
}).complete(function(data){
//complete
});
that callsback a parse method in the model.
How can I read the cookie value in the model?
Include Cookie.js.
You can then reference individual cookies like this:
var token = Cookie.get('token')
# token == 'ninja'
Here is what I figured out. My application has two components - the HTML/js from one domain that talks to a REST sevice on another domain (and therefore is cross-domain.) Because the cookie is set from REST, it appears is not readable across domains. So the web page will not store the cookie even though the server is sending it. One alternative is to use local cookies or use the technique illustrated by http://backbonetutorials.com/cross-domain-sessions/.
Assuming you are using jQuery with Backbone, you can get the headers by defining the parse function in your model by calling getAllResponseHeaders or getResponseHeader:
var model = Backbone.Model.extend({
// the rest of your model
parse: function(resp, xhr) {
var allHeaders = xhr. getAllResponseHeaders();
var cookieHeader = xhr. getResponseHeader("Set-Cookie");
// do something with the headers
return resp;
}
});