As mentioned in the previous article passport by default uses serializeUser and deserializeUser methods
SerializeUser method
It is used to store user data in the session storage. It also decides which part of user object will be stored in the session.
When we the auth process runs in passport.js before handling the success redirect it always looks for a serializer method to put the user information in the session.
User.create(profileData, (err, newUser) => {
if (err) {
return done(err);
}
return done(null, newUser);
});
This is the reason why it is recommended to pass a second truthy value to the done
callback of the strategy after we have created and stored the user in the database. The second argument of the done callback will be the user object and the serializeUser method will have access to it so we can save the user info by passing a key in the done
callback of serializeUser method. The key passed is useful in desearilizing the user as mentioned below.
DeserializeUser method
We also have deserializeUser method which can be used to get access to the user data. It has two arguments with the first argument being the key that we passed to the done
method in our serializeUser method. We can access the entire user object by using only the key i.e., the first argument of the deserializeUser method.
We will add both of these methods now to our passport.js
module file and it will look like this.
We can disable the serializeUser method as well if don't want to use it by default. We just need to pass sessions: false
in our index.js
file /auth/github/callback
route.
router.get(
"/auth/github/callback",
passport.authenticate("github", { failureRedirect: "/failure", session: false }),
(req, res) => {
res.redirect("/success");
}
);
That's it we have completed our Github OAuth application.
Thanks for reading the article.
Top comments (0)