node.js - Passport.js: how to access user object after authentication? -



node.js - Passport.js: how to access user object after authentication? -

i'm using passport.js login user username , password. i'm using sample code passport site. here relevant parts (i think) of code:

app.use(passport.initialize()); app.use(passport.session()); passport.serializeuser(function(user, done) { done(null, user); }); passport.deserializeuser(function(obj, done) { done(null, obj); }); passport.use(new localstrategy(function(username, password, done) { user.findone({ username: username }, function(err, user) { if (err) { homecoming done(err); } if (!user) { homecoming done(null, false, { message: 'incorrect username.' }); } if (!user.validpassword(password)) { homecoming done(null, false, { message: 'incorrect password.' }); } homecoming done(null, user); }); } )); app.post('/login', passport.authenticate('local', { failureredirect: '/login/fail', failureflash: false }), function(req, res) { // successful login //console.log("login successful."); // can access req.user here });

this seems login correctly. however, able access login user's info in other parts of code, such as:

app.get('/test', function(req, res){ // how can user's login info here? console.log(req.user); // <------ outputs undefined });

i have checked other questions on so, i'm not sure i'm doing wrong here. give thanks you!

you'll need create sure register middleware populates req.session before registering passport middlewares.

for illustration next uses express cookiesession middleware

app.configure(function() { // code ... app.use(express.cookieparser()); app.use(express.bodyparser()); app.use(express.cookiesession()); // express cookie session middleware app.use(passport.initialize()); // passport initialize middleware app.use(passport.session()); // passport session middleware // more code ... });

node.js express

Comments

Popular posts from this blog

web services - java.lang.NoClassDefFoundError: Could not initialize class net.sf.cglib.proxy.Enhancer -

Accessing MATLAB's unicode strings from C -

javascript - mongodb won't find my schema method in nested container -