Facebook Graph API Long-Lived Token - javascript

I am working with Facebook Graph API and I have followed the instruction on the official documentation page to obtain a Long-Lived Token using a previously extracted access token by running the below code
//Get long-lived access token
var longLiveToken = "https://graph.facebook.com/v8.0/oauth/" +
req.authInfo + "?grant_type=fb_exchange_token&client_id=" + process.env.FACEBOOK_CLIENT_ID +
"&client_secret=" + process.env.FACEBOOK_CLIENT_SECRET + "&fb_exchange_token=" + req.authInfo +
"&redirect_uri=http://localhost:4000/";
https.get(longLiveToken, (res) => {
console.log('statusCode:', res.statusCode);
console.log('headers:', res.headers);
res.on('data', (d) => {
console.log(d);
});
}).on('error', (e) => {
console.error(e);
});
However I am getting the below error message
'www-authenticate': 'OAuth "Facebook Platform" "invalid_request" "client_secret should not be passed to /oauth
My query is in line with the official documentation, not sure why I am getting this error message or how to go about resolving it

I figured out what is wrong with the code, I passed in wrong params. Below is the correct query
var longLiveToken = "https://graph.facebook.com/v8.0/oauth/" +
"access_token" + "?grant_type=fb_exchange_token&client_id=" + process.env.FACEBOOK_CLIENT_ID +
"&client_secret=" + process.env.FACEBOOK_CLIENT_SECRET + "&fb_exchange_token=" + req.authInfo;

You should not provide client_secret value. Try to not provide client parameters. Maybe you're providing wrong uri, or not passing required parameters. It works if you would take a look again.

Related

My valid SendGrid API key not working in via NodeJS

I'm attempting you Send Grid's NodeJS code in a CSHTML web page to use their mail send service. For some reason the setApiKey command is not working and does not even exist according to the error in the console. Any idea what I'm doing wrong here?
const sgMail = require(['##sendgrid/mail']);
sgMail.setApiKey('MYAPIKEY');
const msg = {
to: email_id.value,
from: send_email.value,
subject: 'Subject',
html: '<div>From: ' + send_first_name.value + ' ' + send_last_name.value + '</div><div>Email: ' + send_email.value + '</div><div>Message: ' + message + '</div>',
};
sgMail.send(msg).then((sent) => {
console.log('email sent');
})
And here are two of the error messages - Mismatched anonymous define() module and TypeError: sgMail.setApiKey is not a function

No 'Access-Control-Allow-Origin' header is present when creating BlobServiceWithSas

This is the first time I use Azure Storage JS API. I have followed instruction on this Microsoft tutorial.
I generate the SAS key on the node server with successful results but I still get the authentication failed error. I'm using the libraries provided by Microsoft Azure. How may I fix this?
function test() {
Restangular.all('cdn/sas').post({container: 'photos'}).then(function (sas) {
var blobUri = 'https://hamsar.blob.core.windows.net';
var blobService = AzureStorage.createBlobServiceWithSas(blobUri, sas.token);
blobService.listContainersSegmented(null, function (error, results) {
if (error) {
// List container error
} else {
// Deal with container object
}
});
}, function (error) {
console.log("Error generating SAS: ", error);
});
}
Error messages:
According to your error message, I found you create a Service SAS token. But if you want to list all the container name in your storage account. You need use account SAS token.
Notice: You could also use the blobService.listBlobsSegmented, you should make sure your service sas token has the permission to list the blob file and set the container name.
Like this:
blobService.listBlobsSegmented('mycontainer', null, function (error, results)
If you want to list all the container, I suggest you could follow these codes to generate the Account SAS.
Code like this :
var getPolicyWithFullPermissions = function(){
var startDate = new Date();
var expiryDate = new Date();
startDate.setTime(startDate.getTime() - 1000);
expiryDate.setTime(expiryDate.getTime() + 24*60*60*1000);
var sharedAccessPolicy = {
AccessPolicy: {
Services: AccountSasConstants.Services.BLOB +
AccountSasConstants.Services.FILE +
AccountSasConstants.Services.QUEUE +
AccountSasConstants.Services.TABLE,
ResourceTypes: AccountSasConstants.Resources.SERVICE +
AccountSasConstants.Resources.CONTAINER +
AccountSasConstants.Resources.OBJECT,
Permissions: AccountSasConstants.Permissions.READ +
AccountSasConstants.Permissions.ADD +
AccountSasConstants.Permissions.CREATE +
AccountSasConstants.Permissions.UPDATE +
AccountSasConstants.Permissions.PROCESS +
AccountSasConstants.Permissions.WRITE +
AccountSasConstants.Permissions.DELETE +
AccountSasConstants.Permissions.LIST,
Protocols: AccountSasConstants.Protocols.HTTPSORHTTP,
Start: startDate,
Expiry: expiryDate
}
};
return sharedAccessPolicy;
};
var sharedAccessSignature = azure.generateAccountSharedAccessSignature(environmentAzureStorageAccount, environmentAzureStorageAccessKey, getPolicyWithFullPermissions );
Then you could use the account SAS to list the account's container.
Result:
More details about the difference between service sas and account sas, you could refer to this article.

Node JS and Coinbase

I am trying to integrate Coinbase with Node Js, but I am unable to execute the code given on the tutorial page. My code is
`var coinbase = require('coinbase');
var client = new coinbase.Client({'apiKey': mykey, 'apiSecret': mysecret});
client.getAccounts({}, function(err, accounts) {
accounts.forEach(function(acct) {
console.log('my bal: ' + acct.balance.amount + ' for ' + acct.name);
});
});`
I get t the following error:
accounts.forEach(account => {
^
typeError: Cannot read property 'forEach' of null
Looking forward to your answer! Thanks!
The error is clear: accounts is equal to null. You should check what's in err before working with accounts
hello you can use like this
client.getAccounts({}, function(err, accounts) {
accounts.forEach(function(acct) {
console.log(acct.name + ': ' + acct.balance.amount + ' ' + acct.id );
});
});
You could try with a different API keys and check if the keys are enabled.
var Client = require('coinbase').Client;
var client = new Client({
'apiKey': 'API KEY',
'apiSecret': 'API SECRET'
});
client.getAccounts({}, function (err, accounts) {
accounts.data.forEach(function (acct) {
console.log(acct.name + ': ' + acct.balance.amount + ' ' + acct.id);
});
});
Also accounts returns a lot of information but we are looking at the data block. Please refer the Coinbase API v2 documentation for complete sample response of the getAccounts() call - https://developers.coinbase.com/api/v2?javascript#account-resource
Let us know if this works. Good luck!

Node.js https.get() not returning Facebook access token

I'm trying to set up a Facebook login flow in my node.js app but for some reason I cant get the access token to return from the Facebook API when I use node's https.get(). I can get the access token when I use curl though, so I'm not sure what node is doing differently. Relevant code:
var express = require("express");
var https = require("https");
var app = express();
app.route("/")
.all(function(req, res, next)
{
res.sendfile("index.html");
});
app.route("/login")
.get(function(req, res, next)
{
res.redirect("https://www.facebook.com/dialog/oauth?" +
"client_id={my_client_id}&" +
"redirect_uri=http://localhost:3000/auth");
});
app.route("/auth")
.get(function(req, res, next)
{
var code = req.query.code;
https.get("https://graph.facebook.com/oauth/access_token?" +
"client_id={my_client_id}" +
"&redirect_uri=http://localhost:3000/auth" +
"&client_secret={my_client_secret}" +
"&code=" + code,
function(token_response)
{
// token_response doesn't contain token...
res.sendfile("logged_in.html");
}
).on("error", function(e) {
console.log("error: " + e.message);
});
});
var server = app.listen("3000", function()
{
console.log("listening on port %d...", server.address().port);
});
token_response ends up being a huge object that seems to have nothing relevant to the access token. The Facebook developer docs say I'm supposed to get back: access_token={access-token}&expires={seconds-til-expiration} which is exactly what I get when I use curl, but not node.
A bit late. But did you ever solve this?
It seems that you were incorrectly handling the HTTPS response.
http://nodejs.org/api/https.html
https.get("https://graph.facebook.com/oauth/access_token?" +
"client_id={my_client_id}" +
"&redirect_uri=http://localhost:3000/auth" +
"&client_secret={my_client_secret}" +
"&code=" + code,
function(res)
{
res.on('data', function(chunk) {
console.log(chunk);
});
}
)

Finally handler when using 'all' aggregation function on an array of promises

I have some code that opens and reads a SQL script file and opens a connection to the database in parallel, when they are done it executes the contents of the file on the connection. However, the connection result needs to be 'closed'. I need to be able to handle the case where the database connection succeeds and reading the file fails (wrong filename perhaps) and still close the connection in either case.
Here is the code I am currently using, it has a finally() handler to close the client if the query succeeds or fails, but if the file read fails the client will not be closed.
function execFile(db, file) {
console.log('Connecting to ' + db);
return Promise.all([
connect('postgres://' + credentials + host + '/' + db),
fs.readFileAsync(file, 'utf8')
]).spread(function(client, initSql) {
console.log('Connected to ' + db);
console.log('Running init script ' + file);
return client.queryAsync(initSql).finally(client.end);
});
}
I played a little with the bind() function to pass the client into the finally block but I'm not very happy with the complexity that it introduces. I have a feeling that settle() could be useful here and I'm playing with that now.
What is the best way to handle this?
function execFile(db, file) {
console.log('Connecting to ' + db);
var client = connect('postgres://' + credentials + host + '/' + db);
var initSql = fs.readFileAsync(file, 'utf8');
return Promise.all([client, initSql]).spread(function(client, initSql) {
console.log('Connected to ' + db);
console.log('Running init script ' + file);
return client.queryAsync(initSql);
}).finally(function() {
if (client.isFulfilled()) client.inspect().value().end();
});
}

Categories