Can't modify Passport user object

Hi, folks. I’m trying to learn how to manage login sessions and protected routes with React and Passport. I’m going through a tutorial on the subject, and I’ve run into a snag. When I’m logging in and serializing the user, I’m trying to add an “isAuthenicated” property to the user object. It works just fine in the tutorial, but not for me. Here’s my login route:

router.post("/signin", (req, res, next) => {
  // Custom passport callback, (as normal way is structured on server routing)
  passport.authenticate("local-signin", (err, user) => {
    if (err) {
      return res.status(500).json({
        error: err
      });
    }

    // start session, serialize user with passport serialize
    req.logIn(user, err => {
      if (err) {
        return res.status(500).json({ error: err });
      }
      user.isAuthenticated = true;
      return res.json({ user: user });
    });
  })(req, res, next);
  // not sure where this closing (req, res, next) is going...
});

The response that is sent back to the client does not have the isAuthenticated property. BUT, if I return res.json({ user: user, isAuthenticated: user.isAuthenticated });, my response has isAuthenticated: true in it.
Any ideas what I might be missing here? I thought maybe this property was just hidden somehow, but I created a route to show me the deserialized user data, and it has no “isAuthenticated” property in there, so that’s not it. The rest of the relevant code:
Serialize and deserialize user:

passport.serializeUser(function(user, done) {
  console.log("Serializing user...");
  done(null, user._id);
});

passport.deserializeUser(function(_id, done) {
  User.findById(_id, function(err, user) {
    console.log(`Deserialize: ${user}`);
    done(err, user);
  });
});

Strategy:

const SigninStrategy = new LocalStrategy(
  { passReqToCallback: true },
  (req, username, password, done) => {
    User.findOne({ username: username }, function(err, user) {
      console.log("User " + username + " attempted to log in.");
      if (err) {
        return done(err, null);
      } else if (!user) {
        return done("Invalid username or password. (username)", null);
      }
      if (!bcrypt.compareSync(password, user.password)) {
        return done("Invalid username or password. (password)", null);
      }
      console.log("Login successful.");
      return done(null, user);
    });
  }
);

Thanks in advance for any advice. Also, if you know of any good resources on the subject, that’d be appreciated as well.

Turns out it wasn’t necessary to add this property at all! There is a user.isAuthenticated() function that does the same thing. This is used in the freeCodeCamp Passport lessons, but I had forgotten about it.

1 Like