Twitter OAuth1.0A Javascript Error - javascript

I'm currently working on incorporating an authorization feature for Twitter following the approach described here: https://dev.twitter.com/docs/auth/implementing-sign-twitter. I'm using Ajax to send my POST 'http' request, but I've been constantly running into a '401: Unauthorized' error. My code is below:
function getTweets() {
var time = generateTimestamp();
var nonce = generateNonce();
var signature = generateSignature(time, nonce);
var headers = {
"Authorization": 'OAuth oauth_callback="http%3A%2F%2Fwww.google.com%2F", oauth_consumer_key="eEeAAz9fakedtAOlIUhPgQ", oauth_nonce="bbc34b2ca6faabogus6dfc025907fa334", oauth_signature="' + signature + '", oauth_signature_method="HMAC-SHA1", oauth_timestamp="' + time + '", oauth_version="1.0"'
};
$.ajax({
type: "POST",
url: "https://api.twitter.com/oauth/request_token",
dataType: "text",
headers: headers,
success: function(data) {
alert("Success!");
console.log(data);
},
error: function(jq) {
alert("Request Failed.");
console.log(jq.statusText);
}
});
}
function generateTimestamp() {
var currentTime = new Date;
currentTime = Math.floor(currentTime.getTime() / 1000);
return currentTime;
}
function generateNonce() {
var code = "";
for (var i = 0; i < 20; i++) {
code += Math.floor(Math.random() * 9).toString();
}
return code;
}
function generateSignature(timestamp, nonce) {
var http_method = "POST";
var base_url = "https://api.twitter.com/oauth/request_token";
var consumer_key = "eEeAAz9hUKtdjunkeIUhPgQ";
var consumer_secret = "c7wHxnjubxVDcc5hYFqnotactuallymysecretWs2XazUFde0lPRBtBQ";
var signature_method = "HMAC-SHA1";
var token = "609493744-kNPzLKSI4Hg9NWQnopeFPb91eXFUutFm1nZ2hDk2";
var token_secret = "15WOJS9Ji1AXsKRkyAZrxKdsalted5Gj5ZyEAb9aVrJxI";
var version = "1.0";
var parameter_string = "oauth_callback=" + encodeURIComponent(base_url) + "&oauth_consumer_key=" + consumer_key + "&oauth_nonce=" + nonce + "&oauth_consumer_key=" + consumer_key + "&oauth_signature_method=" + signature_method + "&oauth_timestamp=" + timestamp +"&oauth_version=" + version;
var base_string = http_method + "&" + encodeURIComponent(base_url) + "&" + encodeURIComponent(parameter_string);
var signing_key = encodeURIComponent(consumer_secret) + "&";
var signature = encodeURIComponent(window.btoa(CryptoJS.HmacSHA1(base_string, signing_key)));
alert(signature);
return signature;
}
Feel free to post below if there's any other information that would make this error clearer. Thanks.

I created a node.js library to mess around with the Twitter OAuth dance and API. Code is here, tweeter.js
You're welcome to walk through the logic for creating the header and signature (starting at line 348 )
One thing I don't see in the code you've posted and which will make a huge difference is that the signature string must be generated to include the original header, then the header must be rebuilt with the generated string. It's a huge pain and it took me a while to figure it out.
Although the code I wrote is geared toward node.js, you should be able to reuse a lot of the logic to meet your needs.
EDIT
I found a site called hueniverse documented OAuth very well. In fact, there is a utility here to build your own headers for validating your logic (select the 'Create your own' radio button).
EDIT 2
To better explain including the oauth_signature value in the header, suppose you have all of the data up to this point:
var headerObj = {
oauth_consumer_key="123456789",
oauth_token="11111",
oauth_nonce="asdfghjkl%3B",
oauth_timestamp="1341852000",
oauth_signature_method="HMAC-SHA1",
oauth_version="1.0"
};
You create the HMAC-SHA1 signature and receive: "jBpoONisOt5kFYOrQ5fHCSZBGkI%3D"
You would then add that return value to headerObj, giving you:
headerObj = {
oauth_consumer_key="123456789",
oauth_token="11111",
oauth_nonce="asdfghjkl%3B",
oauth_timestamp="1341852000",
oauth_signature_method="HMAC-SHA1",
oauth_version="1.0",
oauth_signature="jBpoONisOt5kFYOrQ5fHCSZBGkI%3D"
};
And this modified version of headerObj is what you build your HTTP headers from.
GET / HTTP/1.1
Host: api.twitter.com:443
Authorization: OAuth realm="https://api.twitter.com/",
oauth_consumer_key="123456789",
oauth_token="11111",
oauth_nonce="asdfghjkl%3B",
oauth_timestamp="1341852000",
oauth_signature_method="HMAC-SHA1",
oauth_version="1.0",
oauth_signature="jBpoONisOt5kFYOrQ5fHCSZBGkI%3D"
NOTE: I didn't verify the host/realm/port, so these are probably wrong. Check the API for those.
The reason this is done is that on Twitter's side (this is an OAuth implementation detail), the oauth_signature value is removed and the rest of the header is hashed and its return value is compared to the value sent in oauth_signature. It's sort of like a wax seal on an envelope... if the hash of the rest of the header doesn't match the hash value you sent in oauth_signature, Twitter knows not to trust the sender or the contents.
EDIT 2.5
I'm moving this from the comment to the answer.
If you check out this line in tweeter.js, you'll see the logic.
var signature = self.oauthSignature(method, path, headerObj, query);
headerObj.oauth_signature = qs.escape(signature);
// concat the header object into a csv string
var header = 'OAuth realm="Twitter API",';
var oauthParts = [];
for (var h in headerObj) {
oauthParts.push(h + '="'+headerObj[h]+'"');
}
header+= oauthParts.join(',');
//...
return header;
This bit of code does as I've explained in EDIT 2, by converting a JSON object into key="value" strings stored in oauthParts[], then joins each element in that array into a single comma-separated string which begins with OAuth realm="Twitter API",

Related

Asana Events API always returning invalid sync token in Apps Script

I am trying to call the Asana Events API - https://developers.asana.com/reference/getevents
This endpoint uses a 'Sync' token to track when you last called it, each call returns a new sync token which can then be stored and used for the next call to only retrieve events since the last call.
If you do not provide a sync token the API will return an 'invalid token' response and give you a new token to get started with.
However, I cannot seem to get it beyond the initial 'invalid token' call, when I used the token in the following call it still returns 'invalid token'
This is using Google's Apps Script, which is basically just JavaScript with some built-in Google functions
Here is my code:
This function makes a call without the ‘sync’ parameter, uses muteHttpExceptions to get the full response text, and sets the sync token as a property in Apps Script (just a key/value pair)
var asanaBaseUrl = 'https://app.asana.com/api/1.0'
function getSyncToken() {
var url = asanaBaseUrl + '/projects/' + asanaProject + '/events'
var headers = {
'Authorization': 'Bearer ' + asanaPAT
}
var options = {
'method': 'GET',
'headers': headers,
'muteHttpExceptions': true
}
var r = UrlFetchApp.fetch(url, options)
var data = JSON.parse(r.getContentText())
var newSyncToken = data.sync
userProps.setProperty('syncToken', newSyncToken)
}
This function uses the properties service to pull the sync token set in the previous call and makes a new call with the sync parameter
function asanaEventCall() {
var url = asanaBaseUrl + '/projects/' + asanaProject + '/events'
var syncToken = userProps.getProperty('syncToken')
var headers = {
'Authorization': 'Bearer ' + asanaPAT
}
var options = {
'method': 'GET',
'headers': headers,
'sync': syncToken,
'muteHttpExceptions': true
}
var r = UrlFetchApp.fetch(url, options)
var data = JSON.parse(r.getContentText())
return data
}
The second function always returns the following
{sync=[SYNC TOKEN HERE], errors=[{message=Sync token invalid or too old. If you are attempting to keep resources in sync, you must fetch the full dataset for this query now and use the new sync token for the next sync.}]}
I’ve confirmed that the token is being set, retrieved, and sent correctly using the logs.
I’ve confirmed the flow above works by manually using the URL, like this:
Go to https://app.asana.com/api/1.0/projects/[PROJECT GID]/events
Copy sync token
Go to https://app.asana.com/api/1.0/projects/[PROJECT GID]/events?sync=[SYNC TOKEN]
Events show properly
I've looked for other answers but haven't found anything specific that helped, and I asked on the Asana forum but haven't got an answer in a few days.
I'm sure I'm missing something painfully obvious here but just can't see it!
From Go to https://app.asana.com/api/1.0/projects/[PROJECT GID]/events?sync=[SYNC TOKEN] of I’ve confirmed the flow above works by manually using the URL, like this:, in your script, it seems that it is required to add 'sync': syncToken, as the query parameter. So, how about modifying your asanaEventCall() as follows?
Modified script:
function asanaEventCall() {
var syncToken = userProps.getProperty('syncToken')
var url = asanaBaseUrl + '/projects/' + asanaProject + '/events' + '?sync=' + syncToken;
var headers = {
'Authorization': 'Bearer ' + asanaPAT
}
var options = {
'method': 'GET',
'headers': headers,
'muteHttpExceptions': true
}
var r = UrlFetchApp.fetch(url, options)
var data = JSON.parse(r.getContentText())
return data
}
Note:
In this modification, it supposes that your values of asanaProject, asanaPAT and syncToken are valid values. Please be careful about this.

Connecting to Bitfinex API from Google Sheets

I'm trying to connect my google sheet to Bitfinex through the 'authenticated' section of the API so I can access my account information. Here is the API link.
I haven't been able to get the 'request' or 'crypto' libraries to work so I've been trying to use other available functions in google sheets, but am having trouble.
Following is the code snippet I'm using:
var completeURL = "https://api.bitfinex.com/v1/account_infos";
var nonce = Math.floor(new Date().getTime()/1000);
var body = {
'request' : completeURL,
'nonce' : nonce
};
var payload = JSON.stringify(body).toString('base64');
var signature = Utilities.computeHmacSignature(Utilities.MacAlgorithm.HMAC_SHA_384,
payload,
secret);
signature = signature.map(function(byte) {
return ('0' + (byte & 0xFF).toString(16)).slice(-2);
}).join('');
var params = {
headers: {
'X-BFX-APIKEY': key,
'X-BFX-PAYLOAD': payload,
'X-BFX-SIGNATURE': signature
},
}
Logger.log(completeURL);
Logger.log(params);
var response = UrlFetchApp.fetch(completeURL, params);
var json = JSON.parse(response.getContentText());
I get the following error from the API:
Request failed for https://api.bitfinex.com/v1/account_infos returned code 400. Truncated server response: {"message":"Invalid json."} (use muteHttpExceptions option to examine full response). (line 209, file "Code")
And the following are the values from the Logger.log calls:
[17-09-24 16:22:28:170 AEST] https://api.bitfinex.com/v1/account_infos
[17-09-24 16:22:28:171 AEST] {headers={X-BFX-PAYLOAD={"request":"https://api.bitfinex.com/v1/account_infos","nonce":1506234148}, X-BFX-SIGNATURE=06d88a85098aefbf2b56af53721506863978f9350b1b18386c23f446254789dbbfc1eeb520bdfc7761b30f98ea0c21a2, X-BFX-APIKEY=ak6UoPiwaLjwt2UqDzZzZGjpb9P2opvdPCAIqLy0eVq}}
I'm stuck and not sure what else to try?
Can anyone spot what I'm doing wrong?
How about this modification? Since I have no secret, I couldn't debug this sample. So I don't know whether this modified sample works. I'm sorry.
Modification points :
secret is not defined.
When POST method is used, it requires to include method: "post" to UrlFetchApp.fetch().
When it reads Javascript sample of the document, signature has to be modified.
When it reads Javascript sample of the document, body: JSON.stringify(body) is included in the request parameters.
There is an error message of {"message":"Invalid json."}.
The script which was reflected above modifications is as follows.
Modified script :
var secret = "#####"; // Please input this.
var completeURL = "https://api.bitfinex.com/v1/account_infos";
var nonce = Math.floor(new Date().getTime()/1000);
var body = {
'request' : completeURL, // I don't know whether this is the correct value.
'nonce' : nonce
};
var payload = Utilities.base64Encode(Utilities.newBlob(JSON.stringify(body)).getDataAsString());
var signature = Utilities.computeHmacSignature(Utilities.MacAlgorithm.HMAC_SHA_384, payload, secret);
signature = signature.map(function(byte) {
return ('0' + (byte & 0xFF).toString(16)).slice(-2);
}).join('');
var params = {
method: "post",
headers: {
'X-BFX-APIKEY': key,
'X-BFX-PAYLOAD': payload,
'X-BFX-SIGNATURE': signature
},
payload: JSON.stringify(body),
contentType: "application/json",
muteHttpExceptions: true
}
var response = UrlFetchApp.fetch(completeURL, params);
var json = JSON.parse(response.getContentText());
If this was not useful for you, I'm sorry.
I am not sure if I am understanding your code, but if I do, there is at least one oddity at first sight:
In computeHmacSignature(...), you are using the variable secret which has not been initialized or even declared anywhere.
That's how it works
var body = {
'request' : "/v1/balances",
'nonce' : nonce,
'options':{}
};

Firebase setWithPriority results in Firebase.update failed

I'm trying to write data to the Firebase Database with a given Priority, in order to then retrieve the childs in reversed order than they are currently in. The following I got from the answer of another question regarding this issue:
var postData = {
url: urlvar
};
// Get a key for a new Post.
var newPostKey = firebase.database().ref().push();//.key;
newPostKey.setWithPriority(postData, 0 - Date.now());
var updates = {};
updates['/user-posts/' + uid + '/' + '/urls/' + newPostKey] = postData;
return firebase.database().ref().update(updates);
However, when trying to trigger this, I'm getting (from the extensions popup console):
Error: Firebase.update failed: First argument contains an invalid key
Which argument is meant by that, what exactly is wrong here?
What did work, before I tried to set a priority, was simply the code above but newPostKey was attached a key:
var newPostKey = firebase.database().ref().push().key;
After trying around different approaches I have found a solution where I can just add the priority to the postData, and then write it to the DB:
var postData = {
url: urlvar,
".priority": 0 - Date.now()
};
var newPostKey = firebase.database().ref().push().key;

Override cached image in ajax response

I have an ajax response that is returning images that are cached. I can bust this cache with a random number generator, but having an issue applying it correctly to the returned URI.
The cached image has a URI coming from the response represented by "obj.entity.entries[property].uri" that looks like this:
http://xx.domain.com/api/v2/img/5550fdfe60b27c50d1def72d?location=SQUARE
The newly uploaded image needs to have the random number applied to it, so that it is appended to the end of the URI, right before the ?, like so:
http://xx.domain.com/api/v2/img/5550fdfe60b27c50d1def72d+6?location=SQUARE, where +6 is the randomly generated number.
I believe the best approach is to use a regex to look for the end of the URI before the ? and apply the var storing the random number, then reapply this new URI to the response. I have the following worked out, but not sure how to apply the regex correctly:
$('.image-search').on('click', function () {
var root = "http://localhost:7777/proxy/staging/rest/v1/cms/story/id/";
var encodeID = $("#imageid").val();
var bearerToken = localStorage.getItem('Authorization');
var imageCacheBust = Math.floor((Math.random() * 10) + 1);
//IF TESTING ON LOCALHOST
if (document.domain == 'localhost') {
url = root + encodeID + "/images";
} else {
//IF IN PRODUCTION
url = "/cropper/admin/cropv2/rest/v1/cms/story/id/" + encodeID + "/images";
//GRAB REFERRER URL FOR VIMOND ASSET
//SET VALUE SUCCEEDING ASSETS AS ASSET ID
var regexp = /assets\/(\d+)/;
var assetid = regexp.exec(window.document.referrer);
$("#imageid").val(assetid[1]);
};
$.ajax({
url: url,
method: 'GET',
headers: {
"Authorization": bearerToken
},
}).then(function (response) {
var obj = response;
var regexp = "REGEX HERE";
var imageURI = regexp.exec(obj.entity.entries[property].uri);
$("#imageid").css("border-color", "#ccc");
$(".search-results").empty();
for (var property in obj.entity.entries) {
if (obj.entity.entries.hasOwnProperty(property)) {
$(".search-results").append($("<li><a href='" + imageURI + "' target='_blank'><div class='thumbnail'><img width='30' height='30' src='" + imageURI + "' target='_blank'/></img><div class='caption'><p>" + obj.entity.entries[property].orientation + "</p></div></a></li>"));
}
}
}).fail(function (data) {
$(".search-results").empty();
$(".search-results").append("<p class='alert alert-danger'>Invalid ID</p>");
$("#imageid").css("border-color", "red");
});
});
You don't need to add your random digits to the file path part of the URL, just append to the URL parameters instead, that is enough to prevent caching.
For example use:
img/5550fdfe60b27c50d1def72d?location=SQUARE&6
Where the 6 is your randomly generated value.
Also, be aware that a randomly generated number might not be the best choice here, since it might be undesirably duplicated. Consider using a hash or timestamp instead of a purely random number.
The solution ended up being fairly simple:
I set var imageCacheBust = Math.random(); and then used it in the returned URI like so: var imageURI = obj.entity.entries[property].uri + "?" + imageCacheBust;

How could I remake FetchUtil.js for CRM 2011 UR 12

I have to remake FetchUtil.js for using it in CRM 2011 UR 12. I'm not very good in javascript, so I need some help.
This is the native code
var sFetchResult = xmlhttp.responseXML.selectSingleNode("//a:Entities").xml;
var resultDoc = new ActiveXObject("Microsoft.XMLDOM");
resultDoc.async = false;
resultDoc.loadXML(sFetchResult);
It doesn't work even in IE now, because of .selectSingleNode("//a:Entities").xml
I did it like this, but there is no xml field there.
sFetchResult = xmlhttp.responseXML.getElementsByTagName('a:Entities')[0].xml;
var resultDoc = new ActiveXObject("Microsoft.XMLDOM");
resultDoc.async = false;
resultDoc.loadXML(sFetchResult);
Help me to remake this for IE and Chrome.
Thanks a lot!
Here is my calling module (include as webresource)
(function (module, undefined) {
module.buildFetchRequest = function (fetch) {
/// <summary>
/// builds a properly formatted FetchXML request
/// based on Paul Way's blog post "Execute Fetch from JavaScript in CRM 2011"
/// http://blog.customereffective.com/blog/2011/05/execute-fetch-from-javascript-in-crm-2011.html
/// </summary>
var request = "<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\">";
request += "<s:Body>";
request += '<Execute xmlns="http://schemas.microsoft.com/xrm/2011/Contracts/Services">' +
'<request i:type="b:RetrieveMultipleRequest" ' +
' xmlns:b="http://schemas.microsoft.com/xrm/2011/Contracts" ' +
' xmlns:i="http://www.w3.org/2001/XMLSchema-instance">' +
'<b:Parameters xmlns:c="http://schemas.datacontract.org/2004/07/System.Collections.Generic">' +
'<b:KeyValuePairOfstringanyType>' +
'<c:key>Query</c:key>' +
'<c:value i:type="b:FetchExpression">' +
'<b:Query>';
request += CrmEncodeDecode.CrmXmlEncode(fetch);
request += '</b:Query>' +
'</c:value>' +
'</b:KeyValuePairOfstringanyType>' +
'</b:Parameters>' +
'<b:RequestId i:nil="true"/>' +
'<b:RequestName>RetrieveMultiple</b:RequestName>' +
'</request>' +
'</Execute>';
request += '</s:Body></s:Envelope>';
return request;
};
module.sendFetchQuery = function (fetchRequest, doneCallback, failCallback) {
//path to CRM root
var server = window.location.protocol + "//" + window.location.host;
//full path to CRM organization service - you may need to modify this depending on your particular situation
var path = server + "/XRMServices/2011/Organization.svc/web";
$.ajax({
type: "POST",
dataType: 'xml',
async: false,
contentType: "text/xml; charset=utf-8",
processData: false,
url: path,
data: fetchRequest,
beforeSend: function (xhr) {
xhr.setRequestHeader(
"SOAPAction",
"http://schemas.microsoft.com/xrm/2011/Contracts/Services/IOrganizationService/Execute"
); //without the SOAPAction header, CRM will return a 500 error
}
}).done(doneCallback)
.fail(failCallback);
};
}(window.xFetch = window.xFetch || {}));
Usage
(the parser requires jQuery ... I am doing most of my fetch calls in web resourced html pages so this isn't a problem) this works in IE and Chrome haven't checked firefox but I can't see why it wouldn't work.
var fetchXml =
xFetch.buildFetchRequest("<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>" +
" <entity name='ENTITYNAME'>" +
" <attribute name='ATTRIBUTE' />" +
" </entity>" +
"</fetch>");
var entityList = new Array();
xFetch.sendFetchQuery(fetchXml,
function (fetchResponse) {
// chrome doesn't like the namespaces because of
// selectSingleNode implementations (which make sense btw)
// I'll never understand why Microsoft have to pepper their xml
// with namespace dross
$(fetchResponse).find("a\\:Entity, Entity").each(function () {
var entityData = {};
$(this).find("a\\:KeyValuePairOfstringanyType, KeyValuePairOfstringanyType").each(function () {
var xmlElement = $(this);
var key = xmlElement.find("b\\:key, key").text();
var value = xmlElement.find("b\\:value, value").text();
entityData[key] = value;
});
//inner loop
$(this).find("a\\:KeyValuePairOfstringstring, KeyValuePairOfstringstring").each(function () {
var xmlElement = $(this);
var key = xmlElement.find("b\\:key, key").text();
var value = xmlElement.find("b\\:value, value").text();
entityData[key] = value;
});
entityList.push(entityData);
});
}, function (jqXhr, textStatus, errorThrown) {
// if unsuccessful, generate an error alert message
});
for (var i = 0; i < entityList.length; i++) {
if (entityList[i].ATTRIBUTE === "Yes" ){
// DO WHATEVER
}
}
I only needed attributes with KeyValuePairOfstringstring and KeyValuePairOfstringanyType but you could parse out any attribute with the right combination of selectors
each item in retrieved
I was facing the similar issue and I resolved it by using below workaround.
var sFetchResult = xmlhttp.response;
var tempresultDoc = new ActiveXObject("Microsoft.XMLDOM");
tempresultDoc.async = false;
tempresultDoc.loadXML(sFetchResult);
// Now at this point we will have the XML file. Get the singleNode from the XML by using below code.
var resultDoc = new ActiveXObject("Microsoft.XMLDOM");
resultDoc.async = false;
resultDoc.loadXML(tempresultDoc.childNodes[0].selectSingleNode("//a:Entities").xml);
Regards,
Krutika Suchak
If you're looking for a version that doesn't require JQuery, and one that parses the results, check this out. It not only wraps the FetchXML, but also parses the response XML into JavaScript objects for easy retrieval.

Categories

Resources