简体   繁体   English

passportjs +facebook + 当前用户

[英]passportjs +facebook + current User

Have some issues figuring out how to access the current user through my facebook login.在弄清楚如何通过我的 facebook 登录访问当前用户时遇到了一些问题。 I'm using passportJS, Node, express.我正在使用passportJS、Node、express。 I think that my 'user' is not staying logged in but I have no way to check.我认为我的“用户”没有保持登录状态,但我无法检查。 I'll upload what I have and thank you for anyone looking over it - really appreciate it.我会上传我所拥有的,并感谢任何人查看它 - 非常感谢。

route.js路由.js

 app.get('/auth/facebook', passport.authenticate('facebook', { scope : ['email', 'public_profile', 'user_friends'] }));
// handle the callback after facebook has authenticated the user
app.get('/auth/facebook/callback',
    passport.authenticate('facebook', {
        successRedirect : '/profile',
        failureRedirect : '/'
    }));
// route for logging out
app.get('/logout', function(req, res) {
    req.logout();
    res.redirect('/');
});
};
function isLoggedIn(req, res, next) {
// if user is authenticated in the session, carry on 
if (req.isAuthenticated())
    return next();
// if they aren't redirect them to the home page
res.redirect('/');
}

passport.js护照.js

    passport.use(new FacebookStrategy({
    // pull in our app id and secret from our auth.js file
    clientID        : configAuth.facebookAuth.clientID,
    clientSecret    : configAuth.facebookAuth.clientSecret,
    callbackURL     : configAuth.facebookAuth.callbackURL,
    // profileFields: ['id', 'name','picture.type(large)', 'emails', 'username', 'displayName', 'about', 'gender']
},
// facebook will send back the token and profile
function(token, refreshToken, profile, done) {
    // asynchronous
    process.nextTick(function() {
        // find the user in the database based on their facebook id
        User.findOne({ 'facebook.id' : profile.id }, function(err, user) {
            // if there is an error, stop everything and return that
            // ie an error connecting to the database
            if (err)
                return done(err);
            // if the user is found, then log them in
            if (user) {
                return done(null, user); // user found, return that user
            } else {
                // if there is no user found with that facebook id, create them
                var newUser            = new User();
                // set all of the facebook information in our user model
                newUser.facebook.id    = profile.id; // set the users facebook id                   
                newUser.facebook.token = token; // we will save the token that facebook provides to the user                    
                newUser.facebook.name  = profile.name.givenName + ' ' + profile.name.familyName; // look at the passport user profile to see how names are returned
                newUser.facebook.email = profile.emails[0].value; // facebook can return multiple emails so we'll take the first
                console.log(profile);
                console.log(user);
                console.log('it is working');
                // save our user to the database
                newUser.save(function(err) {
                    if (err)
                        throw err;
                    // if successful, return the new user
                    return done(null, newUser);
                });
            }
        });
    });
})); // end of FacebookStrategy
};

server.js服务器.js

require('./config/passport')(passport); // pass passport for configuration

// // required for passport
app.use(session({ secret: 'ilovescotchscotchyscotchscotch' })); // session secret
app.use(passport.initialize());
app.use(passport.session()); // persistent login sessions
app.use(flash()); // use connect-flash for flash messages stored in session

This is my first stackoverflow post so apologies in advanced if I have insulted anyone with the format.这是我的第一篇 stackoverflow 帖子,如果我用这种格式侮辱了任何人,请提前道歉。

Your user should be serialized some how.您的用户应该以某种方式进行序列化。 For example:例如:

// set up cookie parser and session
var cookieParser = require('cookie-parser');
var session = require('express-session');

app.use(cookieParser());
app.use(session({
    secret: 'mysecret',
    resave: true,
    saveUninitialized: false
}));

// passport init
app.use(passport.initialize());
app.use(passport.session());

// Lets user information be stored and retrieved from session
passport.serializeUser(function(user, done) {
    done(null, user.facebook.id);
});

passport.deserializeUser(function(id, done) {
User.findById(id, function(err,user){
     if(err) done(err);
         done(null,user);
     });
});

Then you can access the user object via req.user .然后你可以通过req.user访问用户对象。 For example a test route could be:例如,测试路线可以是:

app.get('/user', function(req, res, next) {

    res.send(req.user);
});

Good luck!祝你好运!

You can also do it in another way :你也可以用另一种方式:

router.get('/auth/facebook', function(req, res, next) {
    passport.authenticate('facebook', { scope : ['email', 'public_profile', 'user_friends'] } , function(err, user, info) {
        if(err)   return res.status(400).send(err); 
        if(user._id){
           req.logIn(user, function(err) {
                if (err) { return next(err); }
                //redirect where you want
                return res.redirect("");
            });
        }
     })(req, res, next);
}) 

req.logIn is a function which is required with user obj to create session and maintain . req.logIn是用户 obj 创建会话和维护所需的函数。 Otherwise passport will never able to maintain session of user.否则护照将永远无法维持用户的会话。

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

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