Friday, 7 April 2017

how to set Sessions when log in using Passport and Express in order to req.user._id?

I have already a MEAN app based in this tutorial: https://www.youtube.com/watch?v=uONz0lEWft0&t=113s (Great one by the way).

The functionality includes: register, login, Authentification using Jwt Strategy and a Sessions.

To handle the Sessions it uses the front end (Angular2) to store the user credentials in the localStorage of the browser.

I personally I think this is a lack of security and as well I want to include a To Do list that belongs to a user, having two models'users' and 'tasks' (one to many). That's why I need the current user._id as a reference. Example POST newTask:

`var task = new Task({
    title: req.body.title,
    owner : req.user._id
});`

I read another way to handle Sessions, storing the current user at the backend, using Passport. But even after reading the documentation I'm a little bit confused, perhaps you could answer my questions:

  • Where should I include the serializeUser and deserializeUser methods? I intuit that it must be when the user makes the log in, something like 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 is this session stored? (I'm using MongoDB)

  • Is this enough to make a req.user from anywhere os should I include a middleware strategy or install dependencies such as 'express-session' or 'cookieParser', etc.. ?

Thank you beforehand.



via Carlos Alvarez

No comments:

Post a Comment