Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

216
Vistas
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, Authentication 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 or should I include a middleware strategy or install dependencies such as 'express-session' or 'cookieParser', etc.. ?

Thank you beforehand.

over 4 years ago · Santiago Trujillo
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda