LinkedIn Access_token request getting error using jsoauth library - javascript

hi i am try to integrate LinkedIn with my mobile application which is developing in phonegap with Xcode.
Now i have get the authorization using javascript library from github(https://github.com/bytespider/jsOAuth/blob/daa8823a02fa570b285ac26f66ff6c5d8be9d4ec/src/OAuth/Consumer.js)
jsoauth but i do not know how to set header for "https://api.linkedin.com/uas/oauth/accessToken" any one please give example for it.Now i got oauth_token,verifier,oath_token_secret.how can i use it? i get the problem send like
code is:
var options={
consumerKey:'XXXXXXXXXX',
consumerSecret:'XXXXXXXX',
verifier: verifier,
signatureMethod:'HMAC-SHA1'
};
oauth = OAuth(options);
oauth.post('https://api.linkedin.com/uas/oauth/accessToken', null,
function(data) {alert('acess');
window.plugins.childBrowser.close();
},
function(data) {
alert('no access');
console.log(data.error);
}
);
here the error function called and Xcode error shows like:
* WebKit discarded an uncaught exception in the webView:decidePolicyForNavigationAction:request:frame:decisionListener: delegate: * -[JKArray objectAtIndex:]: index (1) beyond bounds (1)
any one help me how get the AccessToken of LinkeIn.

I don't think you can set the verifier as an option.
Try using the function
oauth.setVerifier('verifier')
&
oauth.setAccessToken('MY-ACCESS-KEY', 'MY-ACCESS-SECRET');
http://bytespider.github.io/jsOAuth/api-reference/
After that, the jsOAuth will set the headers for you.
I also just had a problem fetching the access token using this library and it turned out that it was including the callback parameter unnecessarily, which made the request fail.

Related

Getting deviceId from Azure IotHub / EventHub

I am trying to read device Id from Event Hub (on the back of IoTHub) but my syntax in JS seems wrong.
module.exports = function (context, IoTHubMessages) {
context.log(`JavaScript eventhub trigger function called for message array: ${IoTHubMessages}`);
var deviceId = IoTHubMessages.SystemProperties["iothub-connection-device-id"];
The function returns an error: Exception: TypeError: Cannot read property 'iothub-connection-device-id' of undefined
I'm not entirely sure if "iothub-connection-device-id" is the correct name of the attribute on Event Hub but the problem seems to be with SystemProperties.
Appreciate any help.
iothub-connection-device-id is the right key to use, you just have to use it on the right property bag. An unrelated GitHub issue https://github.com/Azure/azure-sdk-for-js/issues/7801 shows how this key is indeed available on each message.
Depending on the cardinality in your functions.json file, IotHubMessages will either be an array of messages or a single message. See IOTHubMessage.forEach is not a function? for more details.
If it is an array of messages, accessing SystemProperties directly on it will not work. You will need to loop through to access each message separately.
Do you see systemProperties on the individual messages? If yes, then message.systemProperties["iothub-connection-device-id"] should work.
You should be reading messages this way. Read this for more about regarding the topic - https://learn.microsoft.com/en-us/samples/azure-samples/functions-js-iot-hub-processing/processing-data-from-iot-hub-with-azure-functions/
IoTHubMessages.forEach(message => {
context.log(`Processed message: ${message}`);
count++;
totalTemperature += message.temperature;
totalHumidity += message.humidity;
deviceId = message.deviceId;
});
First, use the JSON.stringify to print you the payload received. Secondly i believe you should be able to access your device id by doing the following: message.annotations["iothub-connection-device-id"]. For more info, please reference to the Quickstart examples you have available in the Microsoft's Github repos. Navigate to the iot-hub\Quickstarts\read-d2c-messages folder and you should find the example of processing the message payload and printing the output.
I landed on this question when looking for the deviceId when a deviceTwinChange happens on on Azure Iot hub and the message it routed through event hub to my Azure function. In IotHubMessage I wave only getting reported or desired information. I was looking for the deviceId so i knew what device it came from
properties: {
reported: {
//everything in my reported section
}
}
But i found out this:
module.exports = function (context, IoTHubMessages) {
The device Id is in the context variable. I just did not on Azure Iot hub using an Azure function.
var deviceId = context.bindingData.systemProperties["iothub-connection-device-id"];
A bit annoying that the metadata is kept in context and there is no documentation about this.
Extra points: There is no application properties in the context. Does anyone know how to get application properties in the information send to the azure function? This is for when you enrich the data from azure iot hub
This is the information in azure iot hub when doing the routing. Just havent seen the information in my azure function come through.
Add up to 10 message enrichments per IoT Hub. These are added as application properties to messages sent to chosen endpoint(s).

Fetching ical url

I'm trying to retrieve a content from the specific ical url using ical npm.
I'm testing this code on the client side. There are a few icals that I've managed to fetch. But this one and several others I didn't.
It works great on POSTMAN.
My code is:
const ical = require('ical');
ical.fromURL('https://admin.vrbo.com/icalendar/5d19afbfbf144218a3c76eacf76267c6.ics', {mode: 'cors'}, (err, data) => {
console.log(err)
});
The error I get:
Error: Invalid value for opts.mode
at new push../node_modules/stream-http/lib/request.js.module.exports (request.js:58)
at Object.push../node_modules/stream-http/index.js.http.request (index.js:30)
at Object.push../node_modules/https-browserify/index.js.https.request (index.js:13)
at Request.push../node_modules/request/request.js.Request.start (request.js:829)
at Request.push../node_modules/request/request.js.Request.end (request.js:1639)
at end (request.js:628)
at request.js:644
at run (setImmediate.js:48)
at runIfPresent (setImmediate.js:83)
at onGlobalMessage (setImmediate.js:125)
Pleas tell me what I'm doing wrong and how to make this code work.
I think the issue here is, that you are trying to pass an invalid option ({mode: 'cors'}). ical.fromURL(...) will pass the options argument as it is to request (See Line 8). I've checked the source of request, but did not find any option with the name mode (Maybe you are mixing it up with the Fetch API, because there is an option called mode), so in my opinion, that is also the reason, why you are getting the error (But I'm not sure why it worked out for you, to fetch some other calendars). You can check the full list of possible options by yourself.

Authorizing xAPI interactions through Javascript triggers against my LRS

I've constructed a course in Storyline2, and defined several triggers via javascript as xAPI (tincan) activities.
I have an LRS endpoint link and authorization token, but I'm yet to understand where these credentials should be embedded in order for the whole thing to function properly.
I was given this at another message board:
var tincan = new TinCan({url: window.location.href});
Which of these needs to be replaced by one of the above mentioned? I'm guessing another should be added via "+" after "href".
That example code (which I guess you got from the article I wrote here: http://tincanapi.com/share-statements-between-courses/ ) is envisaging that you will launch the Storyline content from something like an LMS. In that case you will enter the endpoint and authorization details in the LMS settings, and the LMS will pass those to Storyline.
See: http://tincanapi.com/share-statements-between-courses/
If you want to put the details directly in the package, see the example code here: http://rusticisoftware.github.io/TinCanJS/
(included below for convenience)
var lrs;
try {
lrs = new TinCan.LRS(
{
endpoint: "https://cloud.scorm.com/tc/public/",
username: "<Test User>",
password: "<Test Password>",
allowFail: false
}
);
}
catch (ex) {
console.log("Failed to setup LRS object: " + ex);
// TODO: do something with error, can't communicate with LRS
}

XMLHttpRequest error calling Parse.com app from Trigger.io app

I've got a Trigger.io app that queries a Parse.com app for some content in a Parse class called "Event". When I run the query (after the page loads), I receive the following error in the Trigger.io Toolkit console (generated from my javascript below):
Error: 100 XMLHttpRequest failed: {"readyState":4,"onloadstart":null,"withCredentials":false,"onerror":null,"onabort":null,"status":0,"responseXML":null,"onload":null,"onprogress":null,"upload":{"onloadstart":null,"onabort":null,"onerror":null,"onload":null,"onprogress":null},"statusText":"","responseText":""}'
Here is the javascript (in js/index.js):
// Set up for query
var Event = Parse.Object.extend("Event");
var query = new Parse.Query(Event);
query.limit(3);
// Make the query
query.find({
success: function(results) {
forge.logging.log("[getEvents] Successfully retrieved " + results.length + " events.");
// Do something with the returned Parse.Object values
},
error: function(error) {
forge.logging.log("[getEvents] Error: " + error.code + " " + error.message);
}
});
And here is the markup that calls the javascript (placed at the end of the page):
<script>
Parse.initialize("MyParseComApplicationID", "MyParseComJavascriptAPIKey");
</script>
<script type="text/javascript" src="js/index.js"></script>
I've tried lots of variations on this, but I've not been able to get past this (and I haven't seen this error here on stackoverflow or in lots of google searching).
Any thoughts are appreciated. Thanks
UPDATE: Just to clarify, the problem occurs when trying to run the app from Forge on an Android device. When I run from Forge on Web (e.g. just in a browser), I do not receive the error and I do receive data back from Parse.com.
I've tried with both the Javascript Key and the Client Key.
After receiving some guidance from Antoine and re-reading the photo demo (https://github.com/blueski/Forge-Parse-Demo/blob/master/js/parse-demo.js), I realized that I did not need to call Parse.initialize at all and instead I could use forge.request.ajax to get around the cross domain limitation.
One important item that eluded me was to use the Parse.com REST Key, not the Javascript Key when calling with forge.request.ajax
Also (really embarrassed here), it's always a good idea to confirm that wifi is actually enabled! :)

How to set access token on analytics API?

i was wondering, the documentation has tutorials for implementing use of the Analytics API in several languages.
Now in PHP they show how to store the access token and maintain it , now i assume the JS somehow mentains it in some sort of local storage but i don't wish the user to authenticate each time he visitis so my plan is to save the access & refresh token in my database and simply applying it to the client-side instead of going through the all pop up procress.
According to tutorial this :
gapi.auth.authorize({client_id: clientId, scope: scopes, immediate: false}, result);
Fires the popup which returns the access token but i'll say again i'm intrested in submiting token from database.
How can that be done?
is there some gapi.auth.setToken(token) method which after i could make calls to Core Reporting API?
I arrived here looking for a solution using this after having already written PHP to do the auth using google's PHP client libraries. I wanted to share the stored token as you mentioned, and be able to use javascript without re-authenticating, and/or triggering the popup (there may be a solution to this using the .init(callback) method, see docs/links at end).
Is there some gapi.auth.setToken(token) method
It turns out you can, there is the exact setToken(token) function you mention, and, you can even share the auth token generated earlier in PHP. What I'm not sure about yet, is if we should do it :)
I'm using PHP to do the initial auth, but presumeably in the javascript client you'd be able to call setToken() on something that you'd stored with getToken() in the same manner as this example. There may also be better approaches to this, like CORS (see links at end) mentioned in the API Authentication docs that I haven't had a chance to investigate any of these yet, but, I can give an example to answer the question, and might be useful to others needing the same behaviour
I first found Google developer Dan Holevoet's blog post with some sample JS code.
http://googleappsdeveloper.blogspot.com.au/2011/12/using-new-js-library-to-unlock-power-of.html
It's great to be able to query the API directly with javascript, and dynamically load lists etc, but the thing that worried me about this of course was storing clientid etc in js..
// Snippet from Dan's post
var clientId = 'YOUR_CLIENT_ID';
var apiKey = 'YOUR_API_KEY';
var scopes = 'https://www.googleapis.com/auth/calendar';
function handleClientLoad() {
gapi.client.setApiKey(apiKey);
window.setTimeout(checkAuth,1);
checkAuth();
}
But, according to Dan in an answer to the same question:
The apiKey is used in conjunction with designated referrers, which you
must declare in the APIs Console. If the key is sent from an
unauthorized referrer, it will not work. You should make your accepted
referrer list as limited as possible to ensure that others do not use
your apiKey for their own requests.
Now, my example is for the calendar API, but it all seems pretty consistent with the other APIs as well.
Note: This snippet was for proof-of-concept purposes only, and probably shouldn't be used in production. I assume the referrer protection mentioned makes something like this OK to do, but more thought needs to be given. It could be done by hidden input, AJAX call etc.. But in the end, they're all going to be visible in the javascript.
What I did to test the concept was to:
Authenticate via PHP client libs, using the same script/URL as callback (see [API console][2] for these callbacks)
On sucessful auth, in callback, set a global javascript variable in the page to the stored PHP auth token
Once page is loaded, on your first click event to use the javascript (or even in document ready), call authMe() to set the token
Then proceed as normal, calling any javascript API methods that you have given scope to in the initial PHP authentication process (in this case makeApiCall())
Like so:
In the php callback routine, regardless of whether authenticated yet (assuming that your callback URL is the same script), make this var global
<script type="text/javascript">
// A place to stick PHP's auth token once the auth dance is done
var dodgey_global_access_token = {};
</script>
Now, in php callback routine once we've checked that we're authenticated, and $_SESSION['token'] = $client->getAccessToken(); has been called (IE storing the auth token somewhere for later), or at least $client->getAccessToken() has something meaningful:
<script type="text/javascript">
// Set the js var via PHP here.. Yeck... Note json encode in php and parse in jquery
dodgey_global_access_token = $.parseJSON (<?php echo json_encode ($client->getAccessToken() ); ?>);
// dodgey_global_access_token now contains the auth token structure
// Removed auth-related functions in Dan's code - we'll already have a token
// Dan's orig function to list events in 'primary' calendar
function makeApiCall() {
gapi.client.load('calendar', 'v3', function() {
var request = gapi.client.calendar.events.list({
'calendarId': 'primary'
});
request.execute(function(resp) {
for (var i = 0; i < resp.items.length; i++) {
var li = document.createElement('li');
li.appendChild(document.createTextNode(resp.items[i].summary));
document.getElementById('events').appendChild(li);
}
});
});
}
// My function to setToken with the token injected from PHP authentication
function authMe () {
// Stuff the token into the gapi object
gapi.auth.setToken( dodgey_global_access_token );
// Now call the original 'makeAPICall' function now that we're 'authenticated'
makeApiCall();
}
</script>
Note: I used jquery in my example to quickly parse the JSON, we're already using it in the project, but if not, you'll have to find another library to do so
Relevant/useful docs:
// Sorry, as a new poster I can only post 2 hyperlinks,
// so embedding this in code snippet
//
// http://code.google.com/p/google-api-javascript-client/wiki/ReferenceDocs#gapi
// http://code.google.com/p/google-api-javascript-client/wiki/Authentication
// http://code.google.com/p/google-api-javascript-client/issues/detail?id=22
// http://code.google.com/p/google-api-javascript-client/wiki/CORS
// https://code.google.com/apis/console
Let me know if anything's unclear, and can post a working sample to demo.
Google API documentation has changed a bit from when this answer was first provided. google-api-javascript-client is no longer the recommended library for accessing google api libraries and Google suggests using discovery documents to load specific libraries.
As a result, the workflow that you are looking for in order to load all the libraries and set the access token would look like this:
var token = 'someaccesstokenfromoauth2'
gapi.load('client:auth2', function(){
gapi.client.load(
'https://analyticsreporting.googleapis.com/$discovery/rest',
'v4'
).then(function(){
gapi.auth.setToken({ access_token: token })
// business logic with gapi.client.analyticsreporting()
})
})
Load gapi with:
<script src="https://apis.google.com/js/api.js"></script>

Categories

Resources