How to use Facebook API with passport-facebook in NodeJS using Express

Before asking this question, I referred to below, but it did not help me

  1. Passport.js and Facebook Graph API
  2. Retrieving photos from Facebook using passport-facebook
  3. https://www.hitchhq.com/facebook-graph-api/docs/facebook-authentication
  4. http://tech.bigstylist.com/index.php/2017/08/12/search-facebook-graph-api-nodejs/
  5. How to use Graph Graph API after authentication with Facebook Passport.js strategy? enter link description here

And some posts say to use passport-facebook-token But I do not want to use, because I want to expand the existing functionality of my application only with passport-facebook

Formulation of the problem

I am currently using Passport-Facebook for authentication, which works fine, and now I want to expand the functionality to use the Facebook Graph API to get photos of users who are logged into my application

So use the Facebook Graph API to get custom photos, which I have to take below using the request module in Node JS. Part of the body will return to me the expected result.

var request = require("request"); var options = { method: 'GET', url: 'https://graph.facebook.com/me/photos/', qs: { access_token: 'EBBCEdEose0cBADwb5mOEGISFzPwrsUCrXwRWhO87aXB9KsVJlgSLc19IdX9D9AKU7OD5SdFOqPXW3eLm8J3HltZC14VexdMsEDW35LDWASdVDNGp5brFERBETsIvxXJIFXo7QSum5apHXeRyQk7c2PQljmf5WHObZAwXVzYjqPd4lziKTUK48Wfrw5HPwZD' }, headers: { 'content-type': 'application/json' } }; request(options, function (error, response, body) { if (error) throw new Error(error); console.log(body); }); 

But now I wanted to create my special express GET API, when I call what I use, I should get the body response above,

like GET : /graph/photos

 app.get('/graph/photos', function (req, res) { res.send(body)//Here I wanted to get the same response as of the request module above }); 

But I have the following problems

  1. Getting access_token from passport-facebook and transferring it to the request module
  2. If the user is not authenticated, an error is returned in the API response

But I could continue a little with the following approach, I followed the tutorial from

https://github.com/scotch-io/easy-node-authentication/tree/linking

 app.get('/graph/photos', isLoggedIn, function (req, res) { var hsResponse = request({ url: 'https://graph.facebook.com/me/photos', method: 'GET', qs: { "access_token": req.user.facebook.token }, }, function (error, response, body) { res.setHeader('Content-Type', 'application/json'); res.send(body); }); }); 

But the problem that I am facing is to call the API / graph / photos / every time. It will try to redirect to check if the user is logged in, so I cannot use Angular Service directly and get the error below

error

Failed to load http: // localhost: 3000 / graph / photos : Redirect from " http: // someurl " to " http: // someurl " blocked by CORS policy: header "Access-Control-Allow-Origin" is missing. present on the requested resource. The source ' http: // localhost: 4200 ', therefore, does not have access.

+7
source share
1 answer

try this ... I wrote a function for my project, you just configure ....

 // facebook login exports.facebookLogin = function(req, res) { var fields = config.loginFaceBook.fbFields; var accessTokenUrl = config.loginFaceBook.fbAccessTokenUrl; var graphApiUrl = config.loginFaceBook.fbGraphApiUrl + fields.join(','); var params = { code: req.body.code, client_id: req.body.clientId, client_secret: config.loginFaceBook.fbClientSecret, redirect_uri: req.body.redirectUri }; // Step 1. Exchange authorization code for access token. request.get({ url: accessTokenUrl, qs: params, json: true }, function(err, response, accessToken) { console.log('Exchange authorization code err::', err); console.log('Exchange authorization code accessToken::', accessToken); if (response.statusCode !== 200) { return res.status(500).send({ message: accessToken.error.message }); } // Step 2. Retrieve profile information about the current user. request.get({ url: graphApiUrl, qs: { access_token: accessToken.access_token, fields: fields.join(',') }, json: true }, function(err, response, profile) { console.log('Retrieve profile information err::', err); console.log('Retrieve profile information::', profile); if (response.statusCode !== 200) { return res.status(500).send({ message: profile.error.message }); } if (req.header('Authorization')) { console.log('req header Authorization', req.header('Authorization')); } else { var socialEmail; if (profile.email) { socialEmail = profile.email; } else { socialEmail = profile.id + '@facebook.com'; } // Step 3. Create a new user account or return an existing one. UserModel.findOne({ email: socialEmail }, function(err, existingUser) { if (existingUser) { AppClientModel.findOne({ _id: config.auth.clientId }, function(err, client) { if (!err) { var refreshToken = generateToken(existingUser, client, config.secrets.refreshToken); var rspTokens = {}; rspTokens.access_token = generateToken(existingUser, client, config.secrets.accessToken, config.token.expiresInMinutes); var encryptedRefToken = cryptography.encrypt(refreshToken); var token = { clientId: client._id, refreshToken: refreshToken }; UserModel.update({ _id: existingUser._id }, { $push: { 'tokens': token } }, function(err, numAffected) { if (err) { console.log(err); sendRsp(res, 400, err); } res.cookie("staffing_refresh_token", encryptedRefToken); sendRsp(res, 200, 'Success', rspTokens); }); } }); } if (!existingUser) { var userName = profile.first_name + ' ' + profile.last_name; var newUser = new UserModel({ name: userName, img_url: 'https://graph.facebook.com/' + profile.id + '/picture?type=large', provider: 2, //2: 'FB' fb_id: profile.id, email_verified_token_generated: Date.now() }); log.info("newUser", newUser); newUser.save(function(err, user) { if (!err) { var refreshToken = generateToken(user, client, config.secrets.refreshToken); var rspTokens = {}; rspTokens.access_token = generateToken(user, client, config.secrets.accessToken, config.token.expiresInMinutes); var encryptedRefToken = cryptography.encrypt(refreshToken); var token = { clientId: client._id, refreshToken: refreshToken }; UserModel.update({ _id: user._id }, { $push: { 'tokens': token } }, function(err, numAffected) { if (err) { console.log(err); sendRsp(res, 400, err); } res.cookie("staffing_refresh_token", encryptedRefToken); sendRsp(res, 200, 'Success', rspTokens); }); } else { if (err.code == 11000) { return sendRsp(res, 409, "User already exists"); } else { return sendRsp(res, 500, "User create error"); } } }); } }); } }); }); }; 
0
source

Source: https://habr.com/ru/post/1274971/


All Articles