Search code examples
passport.jspassport-local

PassportJS throwing an error when asked to save a 'remember_me' token to db


I'm attempting to set up a Passport Local strategy with the remember me feature. The idea, as recommended by PassportJS docs, is to detect if the Remember me option is checked and if so, generate a unique token and store it to a **tokens* collection in the db.

My route is currently set up like this:

router.post('/',
    passport.authenticate('local', { failureRedirect: '/' }),
    async (req, res, next) => {
      const {body: {remember_me, username}} = req;
      // issue a remember me cookie if the option was checked
      if (!remember_me) { return next(); }

      const token = uuidv4();
      Token.save(token, { userId: req.user.id }, function(err) {
        console.log('ERROR', err);
        if (err) { return done(err); }
        res.cookie(process.env.USER_REMEMBER_COOKIE, token, { path: '/', httpOnly: true, maxAge: 604800000 }); // 7 days
        return next();
      });
    },
    (req, res) => {
      res.cookie(process.env.USER_DATA_COOKIE, signedUserData(req), {
        httpOnly: true,
        secure: true,
      });
      res.json({ success: true });
    });

However, when I enter the username and password with the checkbox checked, instead of adding a token to the db and returning the cookie, Passport is throwing the following error on Token.save():

TypeError: _token.default.save is not a function

Where am I going wrong? The collection exists and so does the model. The latter looks like this:

import mongoose from 'mongoose';

const { Schema } = mongoose;

const tokenSchema = new Schema({
  token: String,
  userId: String,
});

const Token = mongoose.model('token', tokenSchema);

module.exports = Token;


Solution

  • You have mongoose syntax error. replace:

    Token.save(token, { userId: req.user.id }, function(err) {...}
    

    with:

    (new Token({token, userId: req.user.id})).save(function(err) {...})
    

    Detailed:

    1. A mongoose model like Token has no method called save. you should create an instance of it, and then that instance has a method called save to save it into database.

    2. you used token, { userId: req.user.id } wich should be {token, userId: req.user.id }