如何在带有Express的NodeJS中使用带有passport-facebook的Facebook Graph API

时间:2018-01-26 17:50:01

标签: node.js facebook facebook-graph-api passport.js passport-facebook

在提出这个问题之前,我已经提到了以下但没有帮助我

  1. Passport.js & Facebook Graph API
  2. Retrieving photo 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 Facebook Graph API after authenticating with Passport.js facebook strategy? enter link description here
  6. 有些帖子说使用passport-facebook-token但是我不想使用,因为我想用passport-facebook扩展我的应用程序的现有功能

    问题陈述

    目前,我使用passport-facebook进行身份验证,效果很好。现在我想扩展功能,使用Facebook Graph API来获取登录我应用程序的用户的照片

    所以使用Facebook Graph API使用Node JS中的请求模块获取我必须在下面调用的用户照片,正文部分将返回预期结果

    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);
    });
    

    但是现在我想创建我的自定义快速GET API,当我打电话给我使用时应该得到上面的身体响应,

    喜欢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
    });
    

    但我有以下挑战

    1. 从passport-facebook获取access_token并将其传递给请求模块
    2. 如果用户未经过身份验证,则会在API响应中抛出错误
    3. 但我可以通过以下方法继续进行,我已经按照

      中的教程进行了操作

      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);
          });
      });
      

      但我遇到的问题是每次调用API / graph / photos /,它会尝试重定向以检查用户是否已登录因此我将不能直接在Angular Service中使用并低于错误

      错误

      无法加载http://localhost:3000/graph/photos:CORS政策阻止了从“http://someurl”到“http://someurl”的重定向:没有“Access-Control-Allow-Origin”标题存在于请求的资源上。因此,不允许原点“http://localhost:4200”访问。

1 个答案:

答案 0 :(得分:1)

尝试一下... 我为我的项目编写了函数,您只需自定义即可。...

// 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");
                                }
                            }
                        });
                    }
                });
            }
        });
    });
};