With Passport, what is the purpose of serializing a user if i'm authenticating with tokens?
Solution 1:
serializeUser and deserializerUser functions are used for setting cookie and reading that cookie.
In google oauth when a user first sign in with google account, you reach its profile and find a uniquely identifying property to save in the database. That identifying property should be the profile.id. So you store the user's profile.id in the database.
Next time, when user logs in, you need to identify the user, otherwise you will be saving the same profile.id over and over again. In order to remember user, you create cookies. When user logs in, you grab that profile.id and query if that profile.id is saved in the database. this operation done in the passport callback function and if user exists, passport will have access to that user.
passport.use(new GoogleStrategy({
clientID:keys.googleClientID,
clientSecret:keys.googleClientSecret,
callbackURL:"/auth/google/callback"}, (accessToken,refreshToken, profile,done)=>{
User.findOne({googleId:profile.Id}).then((user)=>{
if(user){ //it checks if the user is saved in the database
done(null,user)
}else {
new User({googleId:profile.id}).save().then((user)=>done(null,user))
}
})
}))
As soon as passport.js has access to the user, it automatically calls the serializeUser function, gets a uniquely identifying property for the user, which is user.id, and injects it into the cookie, and that cookie is sent to the client in the response header.
passport.serializeUser((user,done)=>{
//user.id is not profile id. it is id that created by the database
done(null,user.id)
})
once the browser receives the response, it saves the cookie in a file and when it makes follow up requests to the same server, it will automatically appends that cookie in the request. Passport.js is going to pull that uniquely identifying info which is user.id and pass it to the database and database will identify the client.
passport.deserializeUser((id,done)=>{
User.findById(id).then((user)=>{
done(null,user)
})
})