Transfer user information in routes from passport strategies

I am trying to authenticate a user using passport files using express.

The .js passport is as follows.

var USER_INFO = {}; var FB_CALLBACK = 'http://localhost:3000/auth/facebook/callback'; module.exports = function(passport) { passport.use(new FacebookStrategy({ clientID: FB_CLIENT_ID, clientSecret: FB_CLIENT_SECRET, callbackURL: FB_CALLBACK }, function(accessToken, refreshToken, profile, done) { process.nextTick(function() { USER_INFO.id = profile.id; }); })); } 
 var express = require('express'); // call express var app = express(); // define our app using express var router = express.Router(); // get an instance of the express Route var passport = require('passport'); USER_INFO = {}; require('./config/passport')(passport); app.get('/auth/facebook', passport.authenticate('facebook')); app.get('/auth/facebook/callback', passport.authenticate('facebook', { successRedirect : '/fb', failureRedirect : '/error' })); app.get('/fb', function (req, res) { res.json(USER_INFO); }); 

I want all the information to be extracted in res.json (user_info). But it becomes empty. What I miss here. What is the best way to save user basic user information so that he is logged in.

+5
source share
2 answers

First, you should not keep USER_INFO = {} outside the scope of your current request. If two separate users make a request, they will receive the same object.

You should at least store them so that they can be found separately

 var USERS = {}; ... module.exports... passport.use... ... function(accessToken, refreshToken, profile, done) { USERS[profile.id] = profile; done(null, profile); })); 

Now, if two separate users make a request, they will have their information separately in USERS

 { 1234: {id: 1234, name: FOO}, 6789: {id: 6789, name: BAR}, } 

And done(null, profile) will serialize this user. If you have not defined serialization / deserialization functions, you should do it as follows:

 passport.serializeUser(function (user, done) { done(null, user.id); }); passport.deserializeUser(function (id, done) { var user = USERS[id]; done(null, user); }); 

Your users will now be available in their query contexts as req.user

So you just need to do:

 app.get('/fb', function (req, res) { res.json(req.user); }); 
+4
source

You forgot the done () call in process.nextTick ().

 var FB_CALLBACK = 'http://localhost:3000/auth/facebook/callback'; module.exports = function(passport) { passport.use(new FacebookStrategy({ clientID: FB_CLIENT_ID, clientSecret: FB_CLIENT_SECRET, callbackURL: FB_CALLBACK }, function(accessToken, refreshToken, profile, done) { process.nextTick(function() { var USER_INFO = {}; USER_INFO.id = profile.id; done(USER_INFO) }); })); } 

You can pass any object to done () , it will become req.user later on your route. In your case, the USER_INFO you want to answer is req.user

 app.get('/fb', function (req, res) { res.json(req.user); }); 
+2
source

All Articles