F4LLCON F4LLCON - 4 months ago 25
Node.js Question

node route passport current user id

the code I'm using gets current user id from cookies, but the user logged in does have another user id. I'm using passport authentication for the user. I want

user_id
to be the current passport user
user_id
.

current code uses cookie user id:

routes.jes


app.get('/portal', isLoggedIn, function (req, res) {
var user_id = req.cookies ?
req.cookies.user_id : undefined;

Box.
find({
user_id: user_id
}).
sort('-updated_at').
exec(function (err, boxes) {
if (err) return next(err);

res.render('portal', {
user: req.user,
boxes: boxes
});
});
});


I've tried changing

var user_id = req.cookies ?
req.cookies.user_id : undefined;


with e.g.
var user_id = req.user.user_id;
, and some other syntaxis but non work. What am I doing wrong?

Answer

Are you using sessions ? ..If yes try req.session.user._id

app.use(session({
    secret: 'MySuperSecret',
    saveUninitialized: true,
    resave: false,
    duration: 30 * 60 * 1000,
    activeDuration: 5 * 60 * 1000
}));

And when u log in with user store user obj in req.session, so you can access it anywhere you like.

req.session.user = user;

UPDATE:

Other solution that works when using passport: change var user_id = req.user.id; to var user_id = req.user.user_id;