User.findOrCreate函数的作用是什么?何时在护照中调用它? [英] What is function User.findOrCreate doing and when is it called in passport?

查看:325
本文介绍了User.findOrCreate函数的作用是什么?何时在护照中调用它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我找不到有关此功能的文档,因此我无法使其正常工作.什么时候调用该函数,它在做什么以及将什么作为第一个参数?我正在尝试从护照获取访问令牌,但是无论如何都无法到达它.

I can't find documentation on this function and therefor I can't make it work right. When is that function being called, what is it doing and what is it taking as first parameters? I'm trying to get access token from passport, but can't reach it anyhow.

passport.use(new FacebookStrategy({
    clientID:   APP_ID,
    clientSecret:   APP_SECRET,
    callbackURL: "http://localhost:3000/",
  },
  function(accessToken, refreshToken, profile, done) {
    User.findOrCreate({// what are these parameters?}, function (err, user) {
        // when is this function called and what is it doing? 
       });

  }
));

如何从护照中获取访问令牌?

How can I get access token from passport?

推荐答案

User.findOrCreate是一个组合函数,表示通过Facebook ID查找用户或创建一个(如果用户没有)的功能.存在.我认为您的第一个问题是回调URL只会进入您的根目录,因此您可能永远都无法使用该功能.

User.findOrCreate is a made-up function that represents whatever function you have to find a user by Facebook ID, or to create one if the user doesn't exist. I think your first problem is that your callback URL is just going to your root, so you probably are never getting to that function.

您的回调URL应该类似于http://localhost:3000/auth/facebook/callback.

Your callback URL should be like http://localhost:3000/auth/facebook/callback.

然后处理该URL:

app.get('/auth/facebook/callback', 
  passport.authenticate('facebook', { failureRedirect: '/login' }),
  function(req, res) {
    res.redirect('/');
  });

此时,身份验证已完成. accessToken返回给您-应用程序每次调用API代表他们读取,修改或写入特定人的Facebook数据时,都需要这样做".您应该将其保存在存储用户访问令牌的某些表中. profile是另一个关键变量,因为这是有关用户的信息(哪些信息取决于服务).

At this point Authentication is complete. accessToken is returned to you -- "this is needed any time the app calls an API to read, modify or write a specific person's Facebook data on their behalf". You should save this off in some table where you store access tokens for a user. profile is the other key variable because that is the info about the user (what info depends on the service).

您可以在该功能内做什么.因此,制作您自己的User.findOrCreate.这是Facebook护照上的代码,并附有一些注释来对其进行解释.假设您使用的是MongoDB之类的东西,并且有一个User表.在这种情况下,User是您声明的可以与User表连接的任何变量.

What you do inside that function is up to you. So, make your own User.findOrCreate. Here is the code from passport for Facebook with some comments to explain it. This assumes you are using something like MongoDB and have a User table. User in this case is whatever variable you declared that can interface with the User table.

//Use facebook strategy
passport.use(new FacebookStrategy({
        clientID: config.facebook.clientID,
        clientSecret: config.facebook.clientSecret,
        callbackURL: config.facebook.callbackURL
    },
    function(accessToken, refreshToken, profile, done) {
        //check user table for anyone with a facebook ID of profile.id
        User.findOne({
            'facebook.id': profile.id 
        }, function(err, user) {
            if (err) {
                return done(err);
            }
            //No user was found... so create a new user with values from Facebook (all the profile. stuff)
            if (!user) {
                user = new User({
                    name: profile.displayName,
                    email: profile.emails[0].value,
                    username: profile.username,
                    provider: 'facebook',
                    //now in the future searching on User.findOne({'facebook.id': profile.id } will match because of this next line
                    facebook: profile._json
                });
                user.save(function(err) {
                    if (err) console.log(err);
                    return done(err, user);
                });
            } else {
                //found user. Return
                return done(err, user);
            }
        });
    }
));

我个人还使用会员"表来跟踪每个用户的多个帐户(以便他们可以通过多个帐户进行身份验证),因为我是通过猫鼬设置的.实际上,这是我存储该访问令牌的位置.我更喜欢在用户表中有一个facebook列....但这取决于您.

Personally I also use a "membership" table to track multiple accounts per user (so they can authenticate with multiple accounts), as I set it up through mongoose. This is actually where I store that access token. I prefer this to having a facebook column in the user table.... but that is up to you.

var mongoose = require('mongoose'),
    Schema = mongoose.Schema,
    ObjectId = Schema.ObjectId;

var membershipSchema = new Schema({
    provider:  String,
    providerUserId:  String,
    accessToken: String,
    userId: {type: ObjectId, ref: 'User'},
    dateAdded: {type: Date, default: Date.now}
});

module.exports = mongoose.model('Membership', membershipSchema);

因此,我的User.findOrCreate版本开始如下:

and as such, my version of User.findOrCreate starts off like this:

function(accessToken, refreshToken, profile, done) {
    Membership.findOne({
        providerUserId: profile.id
    }, function(err,membershipData) {
            //blah blah blah

其中成员资格是上述模型,并且被定义为以下变量:

where membership is that model above, and is defined as a variable as:

var Membership =  require('./models/membership.js')

这篇关于User.findOrCreate函数的作用是什么?何时在护照中调用它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆