2

I have a /register router for signing up a user. I am using cookie-session (which is similar) instead of express-session for simplicity for now.

I am stuck on the part where I need to authenticate a user on sign up. I am confused about the functionality of req.sessions.save() and req.login(). I know req.login() is provided by passport.js, but I don't understand which one provides the req.session object.

I am new to passport.js and have read numerous articles, videos, and StackOverflow questions extensively to build up my knowledge. Honestly, the passport documentation has been quite a pain so far. I am still confused about how session initiation on signup should work. Many articles skipped the signup part. I thus request help on how to do it.

router.post('/register', (req, res, next) => {
    console.log(req.body)
    User.findOne({email: req.body.email}).then((currentUser) => {
        if(currentUser){ // already exists
            res.render('login')
        } else { // if not, create user in our db
            new User({
                email: req.body.email
            }).save().then((newUser) => {
                passport.authenticate('local')(req, res, () => {
                    
//>>>>              //**This is where I don't know what to do**
                    
                    req.session.save((err) => {
                        if (err) {
                            return next(err)
                        }
                        res.redirect('http://localhost:3000')
                    })
                })
            });
        }
    });
})

2 Answers2

0
passport.authenticate('local')(request, response, () => {
  req.session.save((err) => {
    if (err) {
      return next(err)
    }
    res.redirect('http://localhost:3000')
  })
}
Vega
  • 27,856
  • 27
  • 95
  • 103
Abhijeet Srivastava
  • 303
  • 1
  • 3
  • 10
  • 3
    Although this answer tries to address the problem, it would be much more useful if it had a description on how it addreses the problem so OP and other can learn from it. – Cleptus Jul 16 '20 at 11:28
  • Isn't this the same code as I had posted in the question? I think what this does is take to the redirect link but shows `unauthorized` when you sign up initially. – Anand Goswami Jul 16 '20 at 23:14
0

const express = require("express");
const router = express.Router();
const passport = require("passport");

router.post("/register", (req, res, next) => {
  User.findOne({ email: req.body.email }).then((currentUser) => {
    if (currentUser) { // already exists
      res.render('login')
    } else { // if not, create user in our db
      new User({
        email: req.body.email
      }).save();
    }
  });

  passport.authenticate("local", function (err, user, info) {
    if (err) {
      return res.status(400).json({ errors: err });
    }
    if (!user) {
      return res.status(400).json({errors:"No user found."});
      

      // or save User : new User({email: req.body.email}).save();
    }

    req.login(user, function (err) {
      if (err) {
        return res.status(400).json({ errors: err });
      }

      req.session.save((err) => {
        if (err) {
          return next(err)
        }
        res.redirect('http://localhost:3000')
      });      
      return res.status(400).json({ success: `logged in ${user.id}` });
    });
  })(req, res, next);
});

module.exports = router;