Facebook example not working in Connect-auth/Express - node.js

I am following the example at facebook Connect-auth exemple. I don't understand how to get this example working.
In this snippet of code taken from the previous link:
// Method to handle a sign-in with a specified method type, and a url to go back to ...
app.get('/signin', function(req,res) {
req.authenticate([req.param('method')], function(error, authenticated) {
if(authenticated ) {
res.end("<html><h1>Hello Facebook user:" + JSON.stringify( req.getAuthDetails() ) + ".</h1></html>");
}
else {
res.end("<html><h1>Facebook authentication failed: " + error + " </h1></html>");
}
});
});
I do not understand what this does [req.param('method')] mean? It it hard to understand how connect-auth and facebook work together. I keep getting authentication failed.

The first argument to authenticate is an array of authentication strategies to try, in this example the req.param['method'] is set in the URL (var sign_in_link further down in the code) to "facebook" which matches the one and only authentication strategy initialized in the use.

Related

Node / React Authentication API callback STUMPER

I've been developing for a year and change and this maybe a novice question but I've tried EVERYTHING (~150 hours worth of tries, YIKES) I will post my React Frontend and my Nodejs backend to hopefully get some clarity.
Key notes:
-I am using Auth0 authentication to build an api with a nodeJs server
-Auth0 says to use an https:// call which my localhost:3000 is not. However, everything about AUTH0 works except the API call invoked when a user logs in to redirect them and display their information on their profile. I have only found one solution to this which is a reverse proxy https:// server to make calls (I can stop here if this is the issue lol unless another easier method is out there). Also why would AUTH0 require production https servers to test???
-I have the correct CORS enabled on AUTH0's site and 99% sure NodeJs (I can get a console.log response from my API) and have tried many ways on the front end and backend
to solve.
Help would greatly, greatly, be appreciated.
Code:
function URLChecker() {
// setTimeout(function(){
// console.log("Executed immediately");
if (location.pathname.indexOf('/profile/') === 0) {
//setToken(true);
return true;
}
}
function tokenChanger() {
setToken(true);
console.log("Your token is presented as...", token)
}
useEffect(()=> {
//console.log("url checker is:" + URLChecker());
if(URLChecker() == true){
tokenChanger();
console.log(location)
if (token) {
console.log("token exists");
axios.defaults.headers.get['Access-Control-Allow-Origin'] = 'http://localhost:3000';
axios.get('http://localhost:8080/profile')
.then(res => {
//console.log(res);
console.log(res.data);
}).catch(error => {
console.log(error);
console.log("API for user FAILED")
})
}
app.get('/profile', requiresAuth(), (req, res, next ) => {
console.log(req.oidc.user);
res.header("Access-Control-Allow-Origin", "*");
res.redirect(http://localhost:3000/profile/${((req.oidc.user.nickname))})
});
(res(req.oidc.user) returns a localhost:8080/profile page that is blank with the JSON of the user's information displayed. My next step is to obviously make my frontend call a different API instead of /profile to hit an authentication required api that will return user data, however no matter what I've tried I always get stuck with the same error message. I am so close and don't know whether to stick with AUTH0 to solve this error or going with Google authentication which I hear is nice.
Thank you,
imgur link to error message on my frontend

Facebook API Nodejs

I'm trying post a message as admin of a facebook page, but my code keeps posting as my personal account to the "wall" of the page, not as the page itself.
When authorizing my application I ask for the right permissionscopes, and accept them. Although, when I check my permissions with /{USER-ID}/permissions, it says that I've denied the application to manage my pages. Any ideas why?
Here's my code for posting:
var parameters = {};
parameters.message = "Hello world, this is dog.";
parameters.access_token = req.session.access_token;
FB.api('{PAGE-ID}/feed', 'post', parameters, function (result) {
if (!result) {
return res.send(500, 'error');
} else if (result.error) {
if (result.error.type == 'OAuthException') {
result.redirectUri = FB.getLoginUrl({ scope: 'publish_actions,manage_pages,publish_pages', state: encodeURIComponent(JSON.stringify(parameters)) });
}
console.log(result);
return res.send(500, result);
}
res.send(result);
});
And yes, of course I use my page id instead of the placeholder in my code above.
*Update: It seems like the permissions aren't even asked for when authorizing the application. I added the email scope to the list and it appears when I re-authorize the application.
Could this have anything to do with my application not beeing approved?
"Submit for Login Review
Some of the permissions below have not been approved for use by Facebook.
Submit for review now or read more."

Google+ insert moment with nodejs client

Has anyone been able to get the google-api-nodejs-client to successfully insert a moment?
Whatever I try, I get a generic 400 "Invalid value" error but am unable to narrow down the invalid value because the API Explorer doesn't work either.
Would it be because of the missing data-requestvisibleactions parameter? I'm using passport.js's require('passport-google-oauth').OAuth2Strategy for handling oauth access, and that part is working fine, but I have no idea how to incorporate requestvisibleactions into the oauth request flow since this is definitely not originating from a clientside form.
Here's a snippet of what I'm trying to do (using the latest version of googleapis, v1.0.2):
var google = require('googleapis')
var auth = new google.auth.OAuth2()
auth.setCredentials({
'access_token': user.token
})
google.plus('v1').moments.insert({
collection: 'vault',
userId: 'me',
debug: true,
resource: {
type: "http://schemas.google.com/AddActivity",
target: {
type: "http://schema.org/CreativeWork",
url: "...omitted...",
image: "...omitted...",
description: "test",
name: "test"
}
},
auth: auth
}, function (err, response) {
if (err) {
console.error(err)
res.send(err.code, err)
} else {
console.log(response)
res.send(200)
}
})
ref 1 (out-of-date w.r.t. an older version of googleapis)
ref 2 (client-side, where the use of data-requestvisibleactions is more obvious)
As you speculated, you need the request_visible_actions parameter as part of the URL calling the oauth endpoint.
It looks like the current version of passport-google-oauth doesn't support this parameter. Judging by several of the open issues and pull requests, it isn't clear that the author will respond to requests to add it either. You have two possible options:
Switch to using the OAuth support that is included in google-api-nodejs-client
Patch the passport-google-oauth code. (And possibly submit a pull request in the hopes it will be useful to someone else.)
I don't use passport.js or the passport module in question, so I can't test this, but based on the github repository, I think you can insert the following in lib/passport-google-oauth/oauth2.js after line 136 and before the return statement:
if (options.requestVisibleActions) {
// Space separated list of allowed app actions
// as documented at:
// https://developers.google.com/+/web/app-activities/#writing_an_app_activity_using_the_google_apis_client_libraries
// https://developers.google.com/+/api/moment-types/
params['request_visible_actions'] = options.requestVisibleActions;
}

Why can't I use credentials to make followup oauth call

I am using passport-freshbooks to authenticate and retrieve a token and tokenSecret. However, when I try to use those with a separate OAuth object, I get a 401 authentication failed error.
The strategy used by passport-freshbooks uses the same oauth library, and the call to "post" is identical to the followup call (at least it looks the same to me, but maybe I'm missing something obvious).
Here's some of the pertinent code from the passport strategy:
OAuth = require('oauth').OAuth //This is called from within require('passport-oauth').OAuthStrategy
...
this._oauth = new OAuth('https://' + options.subdomain + '.freshbooks.com/oauth/oauth_request.php',
'https://' + options.subdomain + '.freshbooks.com/oauth/oauth_access.php',
freshbookDao.config.apiSubdomain,
freshbookDao.config.oauthSecret,
"1.0",
null,
"PLAINTEXT",
null,
options.customHeaders);
...
log.info("Calling userProfile with " + token + " and " + tokenSecret);
...
this._oauth.post(url, token, tokenSecret, post_body, post_content_type, function (err, body, res) {...}
I try to use that same token and tokenSecret later. I'm creating a new OAuth object, but setting it with the identical settings passed to the passport strategy. Here's some code from that:
OAuth = require('oauth')
...
oauth = new OAuth.OAuth(
'https://' + options.subdomain + '.freshbooks.com/oauth/oauth_request.php',
'https://' + options.subdomain + '.freshbooks.com/oauth/oauth_access.php',
exports.config.apiToken,
exports.config.oauthSecret,
'1.0',
null,
'PLAINTEXT');
...
log.info("Calling listInvoices with " + token + " and " + tokenSecret);
...
oauth.post(url, token, tokenSecret, body, 'application/xml', function(err, data, res) {...}
These look the same to me. However, the first one passes, and the second fails with this response:
{"statusCode":401,"data":"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<response xmlns=\"http://www.freshbooks.com/api/\" status=\"fail\">\n <error>Authentication failed.</error>\n <code>20010</code>\n</response>\n"} <code>20010</code>\n</response>\n"}
What is it that I'm doing wrong? I've included to "log.info" lines to show that I've compared the token and tokenSecret, and they are indeed the same. What is it I'm missing?
glad you're getting use out of passport-freshbooks!
I didn't write the OAuth code in it. I copied this from Jared Hanson's passport-linkedin module, then tweaked it to work with Freshbooks
If you're getting different outputs, then one of two things is happening:
1) Either you're sending different inputs, or
2) there is a different internal state.
For 1) try logging requests to a file and see what happens: Logging in express js to a output file?
is your app sending different requests?
For 2) I don't know the OAuth protocol well enough to debug it. Just enough to use it. It may be that you can't reuse the tokens on a different connection? I can't say for sure.
Hope that helps Todd!

Facebook access token not accepted to Open Graph using Node.js facebook-node-sdk

Posting an Open Graph action using the Node.js facebook-node-sdk module gives me {"error": "An active access token must be used to query information about the current user."}.
var FB = require( 'fb' )
var path = '/me?' + namespace + ':' + action_type_name
var body = {
access_token: myAccessToken,
myAction : myCustomObjectURL
}
FB.api( path, 'post', body, function( res )
{
if( res.error ) {
console.log( 'the call to open graph failed: ' + res.error.message );
}
else {
console.log( 'success' )
}
})
If I print this access token and use it with cURL (curl https://graph.facebook.com/me?access_token=myAccessToken), it returns correctly, no error. Facebook also shows that the app has permission to post as this user. So what am I doing wrong here?
D'oh, stupid question. It turns out I needed a slash instead of a question mark in the URL path: path = '/me/' + ...
Actually this is a bug of the node facebook api.
When you use a '?' in your api-calls the accesstoken gets appended with another '?'
https://github.com/Thuzi/facebook-node-sdk/blob/master/fb.js#L268
This leads to a api-call like this one: https://graph.facebook.com/me/friends?limit=10?access_token=vSAEFfionhaWFwai...
You see multible '?' in the request and Facebook can not find the accesstoken anymore because of this.

Resources