Not able to understand passport's serializeUser, DeserializeUser and GoogleStategy

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

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

passport.use(new GoogleStrategy({
 
  clientID:process.env.CLIENT_ID,
  clientSecret:process.env.CLIENT_SECRET,
  callbackURL:"http://localhost:3000/auth/google/secrets",
  userProfileURL:"https://www.googleapis.com/oauth2/v3/userinfo"
  },
  
  function(accessToken, refreshToken, profile, done){
    console.log(profile);
    User.findOrCreate({googleId: profile.id}, function(err, user){
      return done(err, user);
    });

}));

Hi, I am learning web dev authetication and this code snippet is driving me crazy. two questions.

  1. why is "return" introduced at the end of the code(line 22) and why isn't it there in serialize and deserializeUser?

  2. what is the difference between null and err, can they be used interchangeably?

1 Answers

Callback doesn't replace return statement, for example, if your code would be as follows:

passport.use(new GoogleStrategy({
 
  clientID:process.env.CLIENT_ID,
  clientSecret:process.env.CLIENT_SECRET,
  callbackURL:"http://localhost:3000/auth/google/secrets",
  userProfileURL:"https://www.googleapis.com/oauth2/v3/userinfo"
  },
  
  function(accessToken, refreshToken, profile, done){
    console.log(profile);
    User.findOrCreate({googleId: profile.id}, function(err, user){
    if(err){
      done(err, user); // it works
      }
    done(null,user) // it also works  
    });

}));

If we wouldn't use return in the if condition both error and success operations will work. Therefore, we use a return statement to terminate the current execution of the function and go on next step.

err is set to null because there is no possibility of error in the serializeUser function. Because this function works after passport authentication. If there is a problem with authentication, this function will not work without it.

Your deserializeUser function logic can be better as follows:

passport.deserializeUser(function(id, done){
    User.findById(id, function(err, user){
    if(err){  return done(err) }; // when an error occur during the databese interaction
        if(!user){return done(null,false)} //there is no error but user wasn't found
        return done(null,user);//when user is found and there no error
  });
});

there is a possibility of error in the deserialization function. Any error can occur from a database, for which we must pass the error back.

Summary:

  1. We always have to use return and terminate function execution if we want to return something when some condition happened
  2. null indicates that no error occurred here done(), if the error is likely to occur, you must return the error.
Related