node.js - how to set Sessions when log in using Passport and Express in order to req.user._id? -
i have mean app based in tutorial: https://www.youtube.com/watch?v=uonz0lewft0&t=113s (great 1 way).
the functionality includes: register, login, authentication using jwt strategy , sessions.
to handle sessions uses front end (angular2) store user credentials in localstorage of browser.
i think lack of security , want include list belongs user, having 2 models 'users' , 'tasks' (one many). that's why need current user._id reference. example post newtask:
var task = new task({ title: req.body.title, owner : req.user._id }); i read way handle sessions, storing current user @ backend, using passport. after reading documentation i'm little bit confused, perhaps answer questions:
where should include
serializeuser,deserializeusermethods? intuit must when user makes log in, this:router.post('/authenticate', (req, res, next)=> { const username = req.body.username; const password = req.body.password; user.getuserbyusername(username, (err, user)=>{ if(err) throw err; if(!user){ return res.json({success: false, msg: 'user not found'}); } user.comparepassword(password, user.password, (err, ismatch) =>{ if(err) throw err; if(ismatch){ ///------------- here ------------------ passport.serializeuser(function(user, done) { done(null, user.id); }); passport.deserializeuser(function(id, done) { user.findbyid(id, function(err, user) { done(err, user); }); }); const token = jwt.sign(user, config.secret, { expiresin: 604800 //1 week }); res.json({ success: true, token:'jwt '+token, user:{ id: user._id, name: user.name, username: user.username, email: user.email } }); }else{ return res.json({ success: false, msg:"wrong password"}); } }); }); });where session stored? (i'm using mongodb)
is enough make req.user anywhere or should include middleware strategy or install dependencies such 'express-session' or 'cookieparser', etc.. ?
thank beforehand.
Comments
Post a Comment