JF0001
JF0001

Reputation: 839

Calling passport.authenticate from Server Side

The following function call (which itself calls the passport.use function) works properly when called from the client side. However, because of how I am authenticating users, I do not need to call this function from the client but I would like to call it from the server side so that it still creates a cookie on the client side:

 app.post("/api/login", (req, res, next) => {
  passport.authenticate("local", (err, user, info) => {
   if (err) {
     return next(err)
   }
   if (!user) {
     return res.status(400).send([user, "Cannot log in", info])
   }
   req.login(user, err => {
     res.send("Logged in")
   })
  })(req, res, next)
 })

How can I modify this function in order to call it from the server side and still creating a cookie on the client?

Upvotes: 0

Views: 217

Answers (2)

JF0001
JF0001

Reputation: 839

One only needs to add the following code in order to generate the cookie.

 req.login(add, err => {
   ...
 }) 

Thank you to Sven.hig for his help within the comments above.

Upvotes: 1

Sven.hig
Sven.hig

Reputation: 4519

With the use of express sessions, passport uses that to serialize and deserialize a user, what it does is add the user id to the already existing session id,to set passport to do that you have to add this 2 functions to your strategy

passport.serializeUser(function(user, done) {
  done(null, user.id);
});

passport.deserializeUser(function(id, done) {
  User.findById(id, function(err, user) {
    done(err, user);
  });
});

Upvotes: 1

Related Questions