Posting to group using facebook nodejs sdk : OAuthException - node.js

I am trying to post to facebook group wall using nodejs sdk ( https://github.com/node-facebook/facebook-node-sdk )
This is a piece of code I am using :
Access token ( works fine ) :
FB.api('oauth/access_token', {
client_id: appId,
client_secret: appSecret,
grant_type: 'client_credentials'
}, function (res) {
if (!res || res.error) {
var errorMessage = !res ? 'Unkown error' : res.error;
log.error(site + " Failed to get fb access token " + errorMessage);
}
var accessToken = res.access_token;
FB.setAccessToken(accessToken);
});
Attempt to post :
var message = 'Hi from facebook-node-js';
FB.api( facebookGroupId + '/feed', 'POST', {
// access_token: appToken,
message: message
}, function (res) {
if (!res || res.error) {
console.error(!res ? 'error occurred' : res.error);
return;
}
console.log('Post Id: ' + res.id);
});
Which fails with :
{ message: '(#200) The user hasn\'t authorized the application to perform this action',
type: 'OAuthException',
code: 200,
fbtrace_id: 'xxxxx' }
Now , this being a server side app, I can not pop something up to request the permission . Can someone point me where I can assign the needed permission to the app ?

You have to have access-token to get this done, It is obvious no user would like any app to save her facebook credentials. So right approach is to first pop-up that yields access token and make use of it for posting.

You need the user to grant user_managed_groups and publish_actions permission to do so. Keep in mind that both permissions need to be reviewed by Facebook.

Related

AWS Cognito Node.JS User Authentication returns unknown problem

I'm using AWS Cognito with Node.JS.
I'm successfully registering and verifying users, but the Authentication is returning "unknown error, the response body from fetch is undefined."
I'm using node-fetch module along with amazon-cognito-identity-js (set as var AWSCognito on code below). User is not in a state of requiring password change and verified.
Have others experienced this and how did you resolve the issue?
Appreciate any guidance in advance....
Here's my code, my complete module is on npm as iditawsutils :
exports.authCognitoUser = function(theUserPoolID, theClientID, userName, userPassword) {
var authenticationData = {
Username : userName,
Password : userPassword
};
var authenticationDetails = new AWSCognito.AuthenticationDetails(authenticationData);
var poolData = { UserPoolId : theUserPoolID,
ClientId : theClientID
};
var userPool = new AWSCognito.CognitoUserPool(poolData);
var userData = {
Username : userName,
Pool : userPool
};
console.log('authentication details: ',authenticationDetails);
var cognitoUser = new AWSCognito.CognitoUser(userData);
cognitoUser.authenticateUser(authenticationDetails, {
onSuccess: function (result) {
console.log('access token + ' + result.getAccessToken().getJwtToken());
console.log('id token + ' + result.getIdToken().getJwtToken());
console.log('refresh token + ' + result.getRefreshToken().getToken());
return result;
},
onFailure: function(err) {
console.log(err.message || JSON.stringify(err));
return err;
},
});
}
//from the console log:
authentication details: AuthenticationDetails {
validationData: {},
authParameters: {},
username: 'thesmarterstuff',
password: 'passW0rd!’ }
Unknown error, the response body from fetch is: undefined
Use the following in your onFailure block to find more details about the error.
onFailure: function(err) {
console.log(new Error().stack);
console.log(err.message || JSON.stringify(err));
},
If you find the error occurring in your fetch line in Client.js, then this could be because currently NodeJS SDK, and most other SDKs do not support the default USER_SRP_AUTH.
You could check by adding a console.log in the Client.js
console.log(this.endpoint);
console.log(options);
Login to your AWS account, and make sure you have checked the option - Enable username-password (non-SRP) flow for app-based authentication (USER_PASSWORD_AUTH)
Then, in your code update it with the following setting.
cognitoUser.setAuthenticationFlowType('USER_PASSWORD_AUTH');

Azure BotBuilder - How to get the user information of the OAuth Connection Settings

I've created a Azure Web App Bot and added a OAuth Connection Setting which takes the user to Salesforce. Everything works well, I'm able to authenticate the user through my bot and also, I can get the access token from Salesforce.
Problem
Can someone help me to get the user information from Salesforce? Because, I am able to get the access token alone and not sure, how to get the user id from Salesforce.
I've written the below code,
var salesforce = {};
salesforce.signin = (connector, session, callback) => {
builder.OAuthCard.create(connector,
session,
connectionName,
"Sign in to your Salesforce account",
"Sign in",
(createSignInErr, createSignInRes) => {
if (createSignInErr) {
callback({
status: 'failure',
data: createSignInErr.message
});
return;
}
callback({
status: 'success',
data: createSignInRes
});
});
};
salesforce.getUserToken = (connector, session, callback) => {
connector.getUserToken(session.message.address,
connectionName,
undefined,
(userTokenErr, userTokenResponse) => {
if (userTokenErr) {
callback({
status: 'failure',
data: userTokenErr.message
});
return;
}
callback({
status: 'success',
data: userTokenResponse
});
});
};
salesforce.accessToken = (connector, session, callback) => {
salesforce.getUserToken(connector, session, (userTokenResponse) => {
if (userTokenResponse.status == 'failure') {
// If the user token is failed, then trigger the sign in card to the user.
salesforce.signin(connector, session, (signinResponse) => {
// If the sign in is failed, then let the user know about it.
if (signinResponse.status == 'failure') {
session.send('Something went wrong, ', signinResponse.message);
return;
}
// If the sign in is success then get the user token and send it to the user.
salesforce.getUserToken(connector, session, (newUserTokenResponse) => {
if (newUserTokenResponse.status == 'failure') {
session.send('Something went wrong, ', newUserTokenResponse.message);
return;
}
callback(newUserTokenResponse);
return;
});
});
}
callback(userTokenResponse);
});
};
I can get the userTokenResponse here. But I need Salesforce user id so that I can start interacting with Salesforce behalf of the user.
If you have only OAuth access token you may query details about the user by invoking http GET against:
https://login.salesforce.com/services/oauth2/userinfo for PROD or
https://test.salesforce.com/services/oauth2/userinfo for sandbox
Add only Authorization: Bearer Y0UR0AUTHTOKEN to the header of the http GET request.
Based on my recent test the result returned from the server looks like:
{
"sub": "https://test.salesforce.com/id/[organizationid]/[userId]",
"user_id": "000",
"organization_id": "000",
"preferred_username": "me#mycompany.com",
"nickname": "myNick",
"name": "name lastname",
"urls": {
...
},
"active": true,
"user_type": "STANDARD",
...
}
You don't need a userId to get the user information where an accessToken is enough. I've installed jsforce and used the below code to get the identity information.
Solved by doing,
const jsforce = require('jsforce');
var connection = new jsforce.Connection({
instanceUrl: instanceUrl,
sessionId: accessToken
});
connection.identity((error, response) => {
if(error) {
callback({
status: 'failure',
message: error.message
});
return;
}
callback({
staus: 'success',
data: response
});
});

Twitter API Email not getting

I am using the following code to get email after twitter login
var requestTokenUrl = 'https://api.twitter.com/oauth/request_token';
var accessTokenUrl = 'https://api.twitter.com/oauth/access_token';
var profileUrl = 'https://api.twitter.com/1.1/account/verify_credentials.json?include_email=true';
var accessTokenOauth = {
consumer_key: authConf.TWITTER_KEY,
consumer_secret: authConf.TWITTER_SECRET,
token: req.body.oauth_token,
verifier: req.body.oauth_verifier
};
// Step 3. Exchange oauth token and oauth verifier for access token.
request.post({ url: accessTokenUrl, oauth: accessTokenOauth }, function(err, response, accessToken) {
if (err) {
return res.status(500).json(err);
}
accessToken = qs.parse(accessToken);
var profileOauth = {
consumer_key: authConf.TWITTER_KEY,
consumer_secret: authConf.TWITTER_SECRET,
oauth_token: accessToken.oauth_token
};
// Step 4. Retrieve profile information about the current user.
request.get({
url: profileUrl,
oauth: profileOauth,
json: true
}, function(err, response, profile) {
if (err) {
console.log("..........." + err)
return res.status(500).json(err);
}
if (profile) {
//Succes : Do something
}
I am getting the access token. But in the step 4, I am getting an error as follows
{"errors":[{"message":"Your credentials do not allow access to this
resource","code":220}]}
I have tried refreshing the access tokens but of no use.
When you open your app setting # apps.twitter.com, under the Permisions tab, make sure that the Request email addresses from users checkbox is ticked as shown in the image, then update setting. You will need to regenerate access token for this new permission update to work.
Twitter Dev

Integrating Facebook Login into Mobile Application using Node.JS Web Service as back-end

I have been coding an RESTful Web Service with Express.JS for our mobile game. I am trying to integrate our mobile game's auth service with Facebook. But I have some questions I don't have an answer.
Following is my code in web service (snippet from app.js);
app.post('/login/facebook', function(req, res) {
var username = req.body.username;
fb.api('oauth/authorize', {
client_id: 'My Facebook App ID',
redirect_uri: 'http://localhost:8080/login/facebook/callback'
}, function (res) {
if(!res || res.error) {
console.log(!res ? 'error occurred' : res.error);
return;
}
var accessToken = res.access_token;
var expires = res.expires ? res.expires : 0;
console("/login/facebook ||| " + accessToken + " ||| " + expires);
});
});
app.post('/login/facebook/callback', function(req, res) {
console.log("Facebook Callback Executed!");
fb.api('oauth/access_token', {
client_id: 'APP ID',
client_secret: 'SECRET',
code: req.params.code,
redirect_uri: 'http://localhost:8080/login/facebook/callback'
}, function (res) {
if(!res || res.error) {
console.log(!res ? 'error occurred' : res.error);
return;
}
var accessToken = res.access_token;
var expires = res.expires ? res.expires : 0;
console("/login/facebook ||| " + accessToken + " ||| " + expires);
});
});
What I am trying to do is connecting username with Facebook account.
When I deliver username with POST method to localhost:8080/login/facebook and try to invoke https://graph.facebook.com/oauth/authorize, it should redirect to Facebook Login Page, then redirect it to redirect_uri.But as this is web service, I don't want it to. I want to show Facebook Login/Auth in my mobile application.Am I using wrong API functions?I can't seem to achieve this or find some readings on topic.
I need step by step instructions, because I can't understand.

braintree + NodeJS gives an "authentication Error "

I'm trying to build a payment gateway library using braintree's NodeJS library, I'm making an ajax call from front end with the card data.
Client-Side
var card_data = {
type: "AmEx",
number: "3XXXXXXXXXXXXXX",
expire_month: "XX",
expire_year: "201X",
cvv2: "XXX",
name: "sandeep",
price : "200",
currency : "USD"
};
Ajax call,
$.ajax({
method: "GET",
url: "http://localhost:3000/paymentPath_braintree",
data: card_data
}).done(function(message){
console.log(message);
}).fail(function(data, message){
console.log(message);
});
Server-Side
var braintreePay = require('braintree');
app.get("/payment_braintree", function(request, response){
var data = request.query;
var gateway = braintreePay.connect({
environment: braintreePay.Environment.Sandbox,
merchantId: "MymerchentID",
publicKey: "MypublicKey",
privateKey: "MyprivateKey",
});
var saleRequest = {
amount: data.price,
creditCard: {
number: data.number,
cvv: data.cvv2,
expirationMonth: data.expire_month,
expirationYear: data.expire_year.slice(2),
cardHolder: data.name
},
options: {
submitForSettlement: true
}
};
gateway.transaction.sale(saleRequest, function(error, result){
if(error){
console.log(error.name);
throw error;
}
if(result.success){
response.send(result.transaction.id);
} else {
response.send(result.message);
}
});
});
I have cross checked everything, from keys and card data everything is in order but i am getting an error in callback after making gateway.transaction.sale(...); called Authentication Error . Which i tried to figure out for hours but could not get through.
error object is
authenticationError: Authentication Error
arguments: undefined
message: "Authentication Error"
name: "authenticationError"
stack: undefined
type: "authenticationError"
Where am i going wrong?
I have created an account sandbox.braintreegateway those key credentials are from the account that i have created, i din't create an app like how its done in paypal.
I am going through lack of understanding in Braintree integration.
Are their any proper documented resource.

Resources