Asana Javascript Oauth Error no route found - javascript

So I keep Receiving an error when I'm trying to use OAuth with Asana's API. The error I'm receiving is "Error no route found". What am I doing wrong? I know that the request is most likely correct, but I believe it returns a hashed URL and i'm supposed to unhash it. This is sample code I am using from a Facebook OAuth though, so perhaps the code is incorrect and facebook api specific.
Here is my code:
$(function () {
checkHashLogin();
$('#signon').click(function () {
asanaLogin();
});
})
});
var appID = ****************;
function asanaLogin() {
var path = 'https://app.asana.com/-/oauth_authorize';
var queryParams = ['client_id=' + appID,
'redirect_uri=' + window.location,
'response_type=token'];
var query = queryParams.join('&');
var url = path + query;
window.location.replace(url);
}
function checkHashLogin() {
if (window.location.hash.length > 3) {
var hash = window.location.hash.substring(1);
if(hash.split('=')[0] == 'access_token')
{
var path = "https://app.asana.com/-/oauth_authorize";
var queryParams = [hash, 'callback=displayUser'];
var query = queryParams.join('&');
var url = path + query;
//use jsonp to call the graph
var script = document.createElement('script');
script.src = url;
document.body.appendChild(script);
}
}
}
function displayUser(user) {
setTimeout(function () { }, 1000);
if (user.id != null && user.id != "undefined") {
//Do Stuff
}
else {
alert('user error');
}
}
Here is a photo of my app credentials. My redirect location is just local because I am not hosting it on a server yet.

Looks like you're doing url = path + query when you might need to do url = path + "?" + query - the query string isn't separated, which means you end up requesting a path like https://app.asana.com/-/oauth_authorizeclientId=... which isn't recognized: hence, "no route found".
Hope that helps!

Related

How to generate hash512 in pre-request from request that has {{variables}} in uri

So I m working on API when i need to set x-auth header for every request in PRE-REQUEST script.
I have variables in my request url i.e {{baseUrl}}{{basePath}}{{businessID}}/users?name={{userName}}......etc
I need to take whole address and add secretKey variable to the end of address, then get hash512 from it.
I was able to achieve that if i have no variables in my address i.e.: dummy.com/12321-e213-21-3e?name=John
I did this by :
var secret = "1234qwerHr2";
var url = request.url.slice(9); //sliced because I don't need to include baseUrl to hash
var hashedPayload = CryptoJS.enc.Hex.stringify(CryptoJS.SHA512(url+secret));
This will return the desired result.
Here is what I logged when trying the same code with variables
console.log(url); =>>>>>>> asePath}}{{businessID}}/users?name={{userName}}......etc
All variables defined , that`s for sure
Basically question is : how to get url with values of variables using var url = request.url; I need not {{businessID}}/users?name={{userName}} but 12321-e213-21-3e?name=John
I lost source where i found it. Somewhere on postman github issue thread
var secret = pm.globals.get("devSecretKey");
pm.myUtility = {
interpolateVariable: function (str) {
return str.replace(/\{\{([^}]+)\}\}/g, function (match, $1) {
// console.log(match)
let result = match; //default to return the exactly the same matchd variable string
if ($1) {
let realone = pm.variables.get($1);
if (realone) {
result = realone
}
}
return result;
});
},
getUrl: function () {
let url = pm.request.url.getRaw();
url = this.interpolateVariable(url)
let {
Url
} = require('postman-collection')
return new Url(url);
},
getUrlTest: function () {
let url = pm.request.url.getRaw();
url = this.interpolateVariable(url)
// let {
// Url
// } = require('postman-collection')
//return new Url(url);
return pm.request.url.parse(url);
}
}
var requestPath = pm.myUtility.getUrl().getPath();
var requestQuery =pm.myUtility.getUrl().getQueryString();
var hashedPayload = CryptoJS.enc.Hex.stringify(CryptoJS.SHA512(requestPath+"?"+requestQuery+secret)); //I added '?' because when you use getQueryString() i does not have '?' before query
pm.environment.set("tempAuthHash", hashedPayload);// use this in your header
This function he wrote is converting your {{variable}} to 'variableValue'
No need to change anything in his functions if you are not good with coding. Guy who created it has golden hands. Just place in your pre request

I need to pass variables to javascript called from php exec command

I have a php file that calls phantomjs via the exec command. The phantom.js file calls a url that needs to include variables. I need to send these variables from php along with the exec command and have the variables show up in the phantom.js url.
Here is my current hardcoded php:
$response = [];
exec('/usr/bin/phantomjs phantomjstest.js', $response);
$data = $response[19];
and phantom.js
var page = require('webpage').create();
console.log('The default user agent is ' + page.settings.userAgent);
page.settings.userAgent = 'SpecialAgent111';
page.open('https://www.aa.com/travelInformation/flights/status/detail?search=AA|1698|2019,1,23&ref=search', function(status) {
if (status !== 'success') {
console.log('Unable to access network');
} else {
var ua = page.evaluate(function() {
return document.getElementById('aa-content-frame').innerHTML;
});
console.log(ua);
}
phantom.exit();
});
What I would like to do is change the php so that it passes 2 variables (from a form submit) to the javascript. Something like:
PHP:
exec('/usr/bin/phantomjs phantomjstest.js?variable1=$forminput1&variable2=$forminput2', $response);
JS
page.open('https://www.aa.com/travelInformation/flights/status/detail?search=AA|variable1|variable2&ref=search', function(status) {
Or I can construct the entire URL in the php and send it along with the exec command.
Any ideas on either method, or some other way to get from here to there, are most appreciated. Thanks.
Based on suggestions in comments, I have updated my PHP to contain:
exec("/usr/bin/phantomjs phantomjstest.js https://www.aa.com/travelInformation/flights/status/detail?search=AA|1698|2019,1,23&ref=search", $response);
and my JS to:
var page = require('webpage').create();
console.log('The default user agent is ' + page.settings.userAgent);
page.settings.userAgent = 'SpecialAgent111';
var system = require('system');
var args = require('system').args;
var address = system.args[0];
page.open(address, function (status) {
if (status !== 'success') {
console.log('Unable to access network');
} else {
var ua = page.evaluate(function() {
return document.getElementById('aa-content-frame').innerHTML;
});
console.log(ua);
}
phantom.exit();
});
But all I get back is a null response. Any idea why the address is either not getting passed with PHP exec or not getting picked up and run by JS?
Thanks.
****** SOLUTION ********
There were a couple of things that needed fixing, and I want to thank those that commented below, as well as others on SO that offered solutions to similar issues.
First, the JS did not like the & symbol in the URL. I had to use # in the passed argument instead and then replace it on the JS side.
Second, the JS did not like the pipe symbol in the URL so I had to escape them.
The finished PHP looks like:
exec("/usr/bin/phantomjs phantomjstest.js https://www.aa.com/travelInformation/flights/status/detail?search=AA\|$flight\|$date#ref=search", $response);
and the JS like:
var page = require('webpage').create();
console.log('The default user agent is ' + page.settings.userAgent);
page.settings.userAgent = 'SpecialAgent111';
var system = require('system');
var args = require('system').args;
var address = system.args[1];
var address = address.replace(/#/gi,"&");
page.open(address, function (status) {
if (status !== 'success') {
console.log('Unable to access network');
} else {
var ua = page.evaluate(function() {
return document.getElementById('aa-content-frame').innerHTML;
});
console.log(ua);
}
phantom.exit();
});
Again, my thanks to all!!!!
****** SOLUTION ********
There were a couple of things that needed fixing, and I want to thank those that commented below, as well as others on SO that offered solutions to similar issues.
First, the JS did not like the & symbol in the URL. I had to use # in the passed argument instead and then replace it on the JS side.
Second, the JS did not like the pipe symbol in the URL so I had to escape them.
The finished PHP looks like:
exec("/usr/bin/phantomjs phantomjstest.js
https://www.aa.com/travelInformation/flights/status/detail?
search=AA\|$flight\|$date#ref=search", $response);
and the JS like:
var page = require('webpage').create();
console.log('The default user agent is ' + page.settings.userAgent);
page.settings.userAgent = 'SpecialAgent111';
var system = require('system');
var args = require('system').args;
var address = system.args[1];
var address = address.replace(/#/gi,"&");
page.open(address, function (status) {
if (status !== 'success') {
console.log('Unable to access network');
} else {
var ua = page.evaluate(function() {
return document.getElementById('aa-content-frame').innerHTML;
});
console.log(ua);
}
phantom.exit();
});

undefined is not a valid uri or options object. Nodejs

I am currently building a web scraper in NodeJS and I am facing a certain problem. After running my code, I receive this error:
undefined is not a valid uri or options object.
I am not sure how to bypass this error, I've looked at these examples: Example One, Example Two
Here is all my code:
var request = require('request');
var cheerio = require('cheerio');
var URL = require('url-parse');
var START_URL = "http://example.com";
var pagesVisited = {};
var numPagesVisited = 0;
var pagesToVisit = [];
var url = new URL(START_URL);
var baseUrl = url.protocol + "//" + url.hostname;
pagesToVisit.push(START_URL);
setInterval(crawl,5000);
function crawl() {
var nextPage = pagesToVisit.pop();
if (nextPage in pagesVisited) {
// We've already visited this page, so repeat the crawl
setInterval(crawl,5000);
} else {
// New page we haven't visited
visitPage(nextPage, crawl);
}
}
function visitPage(url, callback) {
// Add page to our set
pagesVisited[url] = true;
numPagesVisited++;
// Make the request
console.log("Visiting page " + url);
request(url, function(error, response, body) {
// Check status code (200 is HTTP OK)
console.log("Status code: " + response.statusCode);
if(response.statusCode !== 200) {
console.log(response.statusCode);
callback();
return;
}else{
console.log(error);
}
// Parse the document body
var $ = cheerio.load(body);
collectInternalLinks($);
// In this short program, our callback is just calling crawl()
callback();
});
}
function collectInternalLinks($) {
var relativeLinks = $("a[href^='/']");
console.log("Found " + relativeLinks.length + " relative links on page");
relativeLinks.each(function() {
pagesToVisit.push(baseUrl + $(this).attr('href'));
});
}
Once your pagesToVisit empties, the url will be undefined since calling pop on an empty array returns this value.
I would add a check in visitPage that url is not undefined, e.g.
function visitPage(url, callback) {
if (!url) {
// We're done
return;
}
Or in crawl, check that pagesToVisit has elements, e.g.
function crawl() {
var nextPage = pagesToVisit.pop();
if (!nextPage) {
// We're done!
console.log('Crawl complete!');
} else if (nextPage in pagesVisited) {
// We've already visited this page, so repeat the crawl
setInterval(crawl,5000);
} else {
// New page we haven't visited
visitPage(nextPage, crawl);
}
}
Taking hints from Terry Lennox's answer, I modified the crawl() function slightly:
function crawl() {
var nextPage = pagesToVisit.pop();
if (nextPage in pagesVisited) {
// We've already visited this page, so repeat the crawl
setInterval(crawl, 5000);
} else if(nextPage) {
// New page we haven't visited
visitPage(nextPage, crawl);
}
}
All I am doing is check whether the popped element exists or not before calling visitPage().
I get the following output:
Visiting page http://example.com
Status code: 200
response.statusCode: 200
null
Found 0 relative links on page
^C

Firefox WebExtension, store an array in the browser's storage

Can you store an array using browser.storage.local.set or achieve the same result with a different method?
Details:
My extension currently will redirect a website specified through the options.html form. Currently when you specify a new website the old one will be replaced. Is there a way I can append to an array of websites that will be redirected instead of replacing the website?
options.js: (will process information from form in options.html)
function saveOptions(e) {
e.preventDefault();
browser.storage.local.set({
url: document.querySelector("#url").value
});
}
function restoreOptions() {
function setCurrentChoice(result) {
document.querySelector("#url").value = result.url || "reddit.com";
}
function onError(error) {
console.log(`Error: ${error}`);
}
var getting = browser.storage.local.get("url");
getting.then(setCurrentChoice, onError);
}
document.addEventListener("DOMContentLoaded", restoreOptions);
document.querySelector("form").addEventListener("submit", saveOptions);
redirect.js:
function onError(error) {
console.log(`Error: ${error}`);
}
function onGot(item) {
var url = "reddit.com";
if (item.url) {
url = item.url;
}
var host = window.location.hostname;
if ((host == url) || (host == ("www." + url))) {
window.location = chrome.runtime.getURL("redirect/redirect.html");
}
}
var getting = browser.storage.local.get("url");
getting.then(onGot, onError);
One thought I had was to add a storage location per url, however i would have to also be stored to prevent it getting reset each time options.js is loaded. (Something similar to the below code)
var i = 0;
browser.storage.local.set({
url[i]: document.querySelector("#url").value
});
i++;
A more logical solution would be for the url storage location to be an array.
If there is a way for url to be an array then redirect.html could contain the following:
if ( (url.includes (host) ) || (url.includes ("www." + host) ) ){
window.location = chrome.runtime.getURL("redirect.html");
}
Fresh eyes has solved my problem.
In options.js:
function saveOptions(e) {
e.preventDefault();
var array = (document.querySelector("#url").value).split(",");
browser.storage.local.set({
url: array
});
In redirect.js:
function onGot(item) {
var url = "";
if (item.url) {
url = item.url;
}
var host = window.location.hostname;
if ( (url.includes(host)) || (url.includes("www." + host)) ) {
window.location = chrome.runtime.getURL("redirect/redirect.html");
}
}

Get subdomain and query database for results - Meteor

I am pretty new to Meteor now.
I want to:
get the sub-domain of the url
check if a client exists matching the sub-domain
if client exists query the database and get some results (say client settings) from the database.
I am sure that this would be a piece of cake if we use MongoDB, however, we have to move an existing application (built on PHP) that has MySQL backend.
I have found a package numtel:mysql for meteor and I have added it to the project.
Here is the source code written so far:
if(!Session.get('client_details')) {
var hostnameArray = document.location.hostname.split('.');
if(hostnameArray[1] === "localhost" && hostnameArray[2] === "local") {
var subdomain = hostnameArray[0];
}
if(subdomain) {
currentClientDetails = new MysqlSubscription('getClientDetailsFromUrl', subdomain).reactive();
Tracker.autorun(function() {
if(currentClientDetails.ready()) {
if(currentClientDetails.length > 0) {
var clientDetails = currentClientDetails[0];
Session.setPersistent('client_details', clientDetails);
var clientId = clientDetails.id;
if(!Session.get('client_settings')) {
clientSettings = new MysqlSubscription('clientSettings', clientId).reactive();
Tracker.autorun(function() {
if(clientSettings.ready()) {
if(clientSettings.length > 0)
Session.setPersistent('client_settings', clientSettings[0]);
else
Session.setPersistent('client_settings', {});
}
});
}
}
}
});
}
}
the session.setPersistent comes from u2622:persistent-session to store Sessions on client side
and here is the publish statement:
Meteor.publish("getClientDetailsFromUrl", function(url) {
if(typeof url === undefined) {
return;
}
var clientDetails = Meteor.readLiveDb.select(
'select * from clients where client_url = "'+ url +'"',
[{table: 'clients'}]
);
return clientDetails;
});
Meteor.publish("clientSettings", function(clientId) {
if(typeof clientId === undefined) {
throw new error('ClientId cannot be null');
return;
}
var clientSettings = Meteor.readLiveDb.select(
'select * from client_settings where client_id = ' + clientId, [{
table: 'client_settings'
}]);
return clientSettings;
});
and the database is initiated as
Meteor.readLiveDb = new LiveMysql(<MySQL Settings like host, user, passwords, etc>);
Problem
I get client_details into the session successfully, however, cannot get client_settings into the session. End up with an error:
Exception from Tracker recompute function:
Error: Subscription failed!
at Array.MysqlSubscription (MysqlSubscription.js:40)
at app.js?6d4a99f53112f9f7d8eb52934c5886a2b7693aae:28
at Tracker.Computation._compute (tracker.js:294)
at Tracker.Computation._recompute (tracker.js:313)
at Object.Tracker._runFlush (tracker.js:452)
at onGlobalMessage (setimmediate.js:102)
I know the code is messy and could get a lot better, please suggestions welcome

Categories

Resources