Getting a Unexpected token : after a jsonp cb in Weather underground - javascript

I am trying to do a weather underground query by creating jsonp. In their official documents it says that cb is the callback name (https://www.wunderground.com/weather/api/d/docs?d=autocomplete-api&MR=1#using_results), however, I keep getting an "Uncaught SyntaxError: Unexpected token :" error. I'm trying to do this in pure javascript but I am having no such luck and all of the examples that I have found are jquery methods. Any help would be appreciated.
This is an example of the error: "Uncaught SyntaxError: Unexpected token : aq?query=Sacramento?callback=cb:1"
Here is the javascript code:
var citySearch = document.getElementById("citySearchForm");
var search;
function searchFormFunc(e){
jsonP = "?callback=cb";
cityName = document.getElementById('getCitiesInput').value;
var cityNameJsonP = cityName + jsonP;
var searchCityLink = "http://autocomplete.wunderground.com/aq?query=";
search = searchCityLink.concat(cityNameJsonP);
console.log(search);
var script = document.createElement('script');
script.src = search;
document.getElementsByTagName('head')[0].appendChild(script);
function cb(data){
console.log("fired");
console.log(data);
}
}

Your URL is going to be
http://autocomplete.wunderground.com/aq?query=FOOBAR?callback=cb
a valid url via their api would be
http://autocomplete.wunderground.com/aq?query=20500&cb=cb
You should be encoding the value and you should be using & for multiple querystring parameters.
jsonP = "&cb=cb";
cityName = encodeURICompontent(document.getElementById('getCitiesInput').value);
var cityNameJsonP = cityName + jsonP;

Related

json data extract nested objects from _body - Javascript

I am trying to get value of a token but I get error ERROR TypeError: Cannot read property 'token' of undefined
code
//Below code gives the output shown below with black color text
data.text()
// I am interested in fetching token value which is nested inside success keyword, below code fails to get the token
var abc = data.text();
abc['success'].token
let abc = JSON.parse(data.text());
var abc = (JSON.parse(data._body)).success.token;
Following code is for reading JWT form js
function parseJwt (token) {
var base64Url = token.split('.')[1];
var base64 = base64Url.replace('-', '+').replace('_', '/');
return JSON.parse(window.atob(base64));
};
How to decode jwt token in javascript

How to generate oauth1 signature for access token in javascript?

I am one the final piece of an etrade oauth integration- (i.e. sending the GET request for access token.) This oauth is taking place in the meteor.js environment so all code is written in javascript.
Currently I am getting a 401 error - oauth_problem=signature_invalid response from etrade. After much scientific research, according to the law of large averages, and partially because I am a genius, I have come to the conclusion I have an invalid signature.
Using this wikipedia article https://en.wikipedia.org/wiki/Hash-based_message_authentication_code (node.js section) and this oauth documentation https://dev.twitter.com/oauth/overview/creating-signatures I wrote the following code:
var signature = encodeURI(secretKey)
signature = signature + "&" + encodeURI(contentArr.oauth_token_secret);
hmacSignature = Crypto.createHmac('sha1', signature);
hmacHash = hmacSignature.digest('hex');
hmacHash is the variable I pass as the oauth_signature parameter for my access token get request but no go :/ Still get the signature_invalid error message. Any suggestions ??? Obviously if you give me a good answer, I will mark it as accepted.
Thanks in advance. :)
Just managed to get this to work!
let accountId = "";
let consumerKey = "";
let consumerSecret = "";
let tokenId = "";
let tokenSecret = "";
function generateOAuthHeader(auth, method, port, hostname, path, params){
let signatureParams = [];
for (let key in params){
signatureParams.push((`${key}=${params[key]}`));
}
for (let key in auth){
signatureParams.push((`${key}=${auth[key]}`));
}
signatureParams = signatureParams.sort();
let parameterString = signatureParams.join("&");
console.log("parameterString", parameterString);
let baseUrl = encodeURIComponent(`${port === 80 ? "http://" : "https://"}${hostname}${path}`);
console.log("baseUrl", baseUrl);
let baseString = `${method}&${baseUrl}&${encodeURIComponent(parameterString)}`;
console.log("baseString", baseString);
let encodeKey = `${consumerSecret}&${tokenSecret}`;
console.log("encodeKey", encodeKey);
let signature = crypto.createHmac('sha1', encodeKey).update(baseString).digest('base64');
console.log("signature", signature);
auth.realm = accountId; //Only if required
auth.oauth_signature = (signature);
return `OAuth `+objectToQuotedParams(auth, ",");
}

Fitbit API OAuth 1.0a from Titanium (Appcelerator)

I am using Titanium (Appcelerator) to connect to Fitbit API. (http://www.appcelerator.com)
I have been facing issues of getting "Invalid Signature" when I am trying to request for token.
I'm using HTTPClient from Titanium.Network.HTTPClient class to send the HTTP Request.
I also uses the oauth-1.0a.js library from https://github.com/ddo/oauth-1.0a to assist in getting the nonce and signature value.
Here is the code:
Ti.include('/oauth/ddo/hmac-sha1.js');
Ti.include('/oauth/ddo/enc-base64-min.js');
Ti.include('/oauth/ddo/oauth-1.0a.js');
function FitBitAuth() {
FitBitAuth.signatureMethod = "HMAC-SHA1";
FitBitAuth.clientKey = 'XXXXXXXXXXXXXXXXXXXXXXXXX';
FitBitAuth.clientSecret = 'XXXXXXXXXXXXXXXXXXXXXXXXXX';
FitBitAuth.nonce = "R#nD0m_$tR!nGss";
FitBitAuth.request_token_url = "https://api.fitbit.com/oauth/request_token";
FitBitAuth.callback_url = "http://www.fitbit.com";
}
FitBitAuth.prototype.createConsumerTokenSecretPair = function() {
return OAuth({
consumer : {
public : FitBitAuth.clientKey,
secret : FitBitAuth.clientSecret
},
signature_method : FitBitAuth.signatureMethod
});
};
FitBitAuth.prototype.getRequestTokenRequestData = function() {
return {
url : "https://api.fitbit.com/oauth/request_token",
method : 'POST'
};
};
FitBitAuth.prototype.requestToken = function() {
var oauth = this.createConsumerTokenSecretPair();
var request_data = this.getRequestTokenRequestData();
var authorized_request = oauth.authorize(request_data, '', FitBitAuth.nonce, FitBitAuth.timestamp);
//alert(authorized_request);
return authorized_request;
};
function auth1a() {
var fb = new FitBitAuth();
var rt = fb.requestToken();
var req = Ti.Network.createHTTPClient();
req.open("POST", FitBitAuth.request_token_url);
req.setRequestHeader('Authorization', 'OAuth oauth_consumer_key="'+FitBitAuth.clientKey+'"');
Ti.API.info(rt);
req.send({
oauth_timestamp : rt.oauth_timestamp,
oauth_nonce : rt.oauth_nonce,
oauth_signature : encodeURIComponent(rt.oauth_signature),
oauth_signature_method: rt.oauth_signature_method,
oauth_callback : encodeURIComponent(FitBitAuth.callback_url),
oauth_version : rt.oauth_version
});
req.onload = function() {
var json = this.responseText;
Ti.API.info("HEADER =====================");
Ti.API.info(req.getAllResponseHeaders());
Ti.API.info("END HEADER =================");
Ti.API.info(json);
var response = JSON.parse(json);
//alert(response);
};
}
I have also tried the Fitbit API Debug tool to assist me in getting all the signature right, in fact the signature and base String do match with the one shown by Fitbit API Debug Tool.
However, I keep getting this Invalid Signature, a sample JSON return is shown below:
{"errors":[{"errorType":"oauth","fieldName":"oauth_signature","message":"Invalid signature: rN**ahem**SGJmFwHp6C38%2F3rMKEe6ZM%3D"}],"success":false}
I have also already tested to do the curl way and it works from Terminal, but to no avail it does not give me a success from Titanium.
Any help is appreciated.
I manage to solve it.
I tried to use another way of inserting the parameters through the header.
Such that the setRequestHeader will look like this:
req.setRequestHeader('Authorization', 'OAuth oauth_consumer_key="'+FitBitAuth.clientKey+'", oauth_nonce="'+rt.oauth_nonce+'", oauth_signature="'+rt.oauth_signature+'",...');
Alternatively, we can also use the built in toHeader feature of the oauth library that I'm using:
oauth.toHeader(oauth_data);
The code above will produce the oauth data in key-value pair.
{
'Authorization' : 'OAuth oauth_consumer_key="xxxxxxxxxxxxx"&oauth_nonce="xxxxxx"&...
}
So instead of the long code for setRequestHeader, we can make use of the value of toHeader, code shown below:
req.setRequestHeader('Authorization', oauth.toHeader(oauth_data).Authorization);
Do note that the return result by fitbit is in plaintext.
auth_token=xxxxxxxx&auth_token_secret=xxxxxxxxx&...

using python suds module to send requests/return responses from wsdl soap service

I am trying to use the python suds module to send requests to a soap service and retrieve results, but am unsure of how to enter in the parameters for the method I want to call. I have been successul in accessing the service and retrieving the methods which show the paramaters and data types, but I haven't had luck in getting a response which I try to send a request. I'm new with this so am unsure of what I am doing wrong. I'm getting this error: suds.WebFault: Server raised fault: 'java.rmi.RemoteException' on the line that initiates the response. I suspect I am not inputting the parameters correctly for the method, but it's not clear to me how to revise it. I want to call the getPostmileForPoint method. This is what I have so far:
import suds
from suds.client import Client
url = 'http://geo.dot.ca.gov/services/PostmileWebService?wsdl'
client = Client(url)
response = client.service.getPostmileForPoint(inputPoint=[None,None,-119.509444,36,None],options=None,routeAlignment='R',routeNumber=43,routeSuffixCode=None)
print response
I used this code below to find the methods in the service along with the parameters they require:
for service in client.wsdl.services:
for port in service.ports:
methods = port.methods.values()
for method in methods:
print(method.name)
for part in method.soap.input.body.parts:
part_type = part.type
if(not part_type):
part_type = part.element[0]
print(' ' + str(part.name) + ': ' + str(part_type))
o = client.factory.create(part_type)
print(' ' + str(o))
And I used this code to get more details on the paramters for the method I am trying to call:
method = client.wsdl.services[0].ports[0].methods["getPostmileForPoint"]
params = method.binding.input.param_defs(method)
print params
UPDATE:
I found a javascript function used on a webpage that calls the web service with the input parameters for the method I want to use. I am now wondering how I can translate this into python using suds (I only included the code from the function that I think is needed, the rest of it does stuff with adding the results to the webpage):
function getPostmile()
{
var outputDiv = document.getElementById('latLongResult');
var popupHtml = null;
var req = new revPMRequest();
var pt = new lrspoint();
pt.x = parseFloat(document.InputCoordinates.InputX.value);
pt.y = parseFloat(document.InputCoordinates.InputY.value);
pt.spatialReferenceID=4269;//NAD83
var opt = new revPMOptions();
opt.toleranceDegrees=0.01703; //~1 mile
req.inputPoint = pt;
req.options = opt;
var ws = new GISWebServiceSoapImp();
var res = ws.getPostmileForPoint(req);
var pm = res.outputPostmile;

Including JavaScript/jQuery libraries in .js functions

I'm trying to generate a token (partially random base 64 encoded string with a certain formatting) for use in a video chat application. To accomplish this, I am using Parse Cloud Code on my backend. I basically deploy a .js file that runs my server side scripts. The code I have now is below. I've been getting error code 141: "Uncaught ReferenceError: document is not defined" and another error saying that '$' is not defined. I suspect I am doing something like including jQuery wrong - probably something extremely noobish. Any ideas?
Parse.Cloud.define("generateToken", function(request, response) {
var script1 = document.createElement('script');
script1.src = 'http://code.jquery.com/jquery-1.8.3.min.js';
script1.type = "text/javascript";
document.getElementsByTagName('head')[0].appendChild(script1);
var script2 = document.createElement('script');
script2.src = 'https://raw.github.com/carlo/jquery-base64/master/ jquery.base64.min.js';
script2.type = "text/javascript";
document.getElementsByTagName('head')[0].appendChild(script2);
var script3 = document.createElement('script');
script3.src = 'http://crypto-js.googlecode.com/svn/tags/3.0.2/build/rollups/hmac-sha1.js';
script3.type = "text/javascript";
document.getElementsByTagName('head')[0].appendChild(script3);
var secondsInDay = 86400;
// Credentials - leaving these out for security purposes
var apiKey = <apiKey>;
var secret = <secret>;
var sessionId = request.params.sid;
// Token Params
var timeNow = Math.floor(Date.now()/1000);
var expire = timeNow+secondsInDay;
var role = "publisher";
var data = "whatever";
// Calculation
data = escape(data);
var rand = Math.floor(Math.random()*999999);
var dataString = "session_id="+sessionId+"&create_time="+timeNow+"&expire_time="+expire+"&role="+role+"&connection_data="+data+"&nonce="+rand;
// Encryption
var hmac = CryptoJS.algo.HMAC.create(CryptoJS.algo.SHA1, secret);
hmac.update( dataString );
hash = hmac.finalize();
preCoded = "partner_id="+apiKey+"&sig="+hash+":"+dataString;
token = "T1=="+$.base64.encode( preCoded );
// Token Achieved. The End
response.success(token);
});
"document not defined" is generally a tell tale sign generally running a web worker. If you want to access the document don't use a webworker. This is because there should be only one thread accessing document so as to not cause clashes.

Categories

Resources