简体   繁体   English

如何在Express的NodeJS中将Facebook Graph API与Passport-facebook一起使用

[英]How to use Facebook Graph API with passport-facebook in NodeJS with Express

Before Asking this Question I have referred the below but didn't help me 在问这个问题之前,我已经参考了以下内容,但并没有帮助我

  1. Passport.js & Facebook Graph API Passport.js和Facebook Graph API
  2. Retrieving photo from Facebook using passport-facebook 使用password-facebook从Facebook检索照片
  3. https://www.hitchhq.com/facebook-graph-api/docs/facebook-authentication 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/ 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? 通过Passport.js Facebook策略进行身份验证后,如何使用Facebook Graph API? enter link description here 在此处输入链接说明

And Some posts say to use passport-facebook-token But I don't want to use as I want to extend the existing functionality of my application with passport-facebook only 还有一些帖子说使用“ passport-facebook-token”,但我不想使用,因为我想仅使用“ passport-facebook”来扩展应用程序的现有功能

Problem Statement 问题陈述

Currently, I am using passport-facebook for authentication which works perfectly and Now I want to extend the functionality to use Facebook Graph API to get the photos of the users who log in to my application 当前,我正在使用passport-facebook进行身份验证,它可以完美地工作,现在,我想扩展功能以使用Facebook Graph API来获取登录到我的应用程序的用户的照片

So use the Facebook Graph API to get the user photos I have to make below call using request module in Node JS, The body part will return me the expected result 因此,使用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);
});

But now I wanted to create my custom express GET API when I call that I use should be getting the above body response, 但是,现在我想创建自己的自定义表达GET API,当我调用该函数时,应该获得上述主体响应,

like GET : /graph/photos 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 below challenges 但是我面临以下挑战

  1. Getting the access_token from the passport-facebook and pass that to the request module 从passport-facebook获取access_token并将其传递给请求模块
  2. If the user is not authenticated thrown an error in the API response 如果用户未通过身份验证,则会在API响应中引发错误

But I could able to proceed somewhat with below approach, I have followed the tutorial from 但是我可以采用以下方法进行一些操作,我遵循了

https://github.com/scotch-io/easy-node-authentication/tree/linking 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 I am facing is every time call the API /graph/photos/, It will try to redirect to check whether the user is logged in hence I won't be directly able to use in Angular Service and getting below error 但是我面临的问题是每次调用API / graph / photos /,它将尝试重定向以检查用户是否登录,因此我将无法直接在Angular Service中使用并出现以下错误

Error 错误

Failed to load http://localhost:3000/graph/photos : Redirect from ' http://someurl ' to ' http://someurl ' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. 无法加载http:// localhost:3000 / graph / photos :从' http:// someurl '重定向到' http:// someurl '已被CORS策略阻止:无'Access-Control-Allow-Origin'标头存在于请求的资源上。 Origin ' http://localhost:4200 ' is therefore not allowed access. 因此,不允许访问源' http:// localhost:4200 '。

try this... I wrote the function for my project,you just customize.... 尝试一下...我为我的项目编写了函数,您只需自定义...。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM