I am implementing a login feature for my ToDoList app using Google Auth 2.
However, I am having trouble with req.isAuthenticated
always returning false. After some debugging, I realized that my deserializeUser
function is not getting hit because I am not seeing the console log statement inside it.
Here is my code:
const express = require("express");
const mongoose = require("mongoose");
const session = require("express-session");
const passport = require("passport");
const GoogleStrategy = require("passport-google-oauth2").Strategy;
const app = express();
app.set("view engine", "ejs");
// Connect to MongoDB database
mongoose.connect("mongodb://localhost:27017/todoListDB", {
useNewUrlParser: true,
useUnifiedTopology: true,
});
// Create a list schema
const itemSchema = new mongoose.Schema({
name: String,
});
const ListSchema = mongoose.Schema({
listName: String,
googleId: String,
nameUser: String,
items: [itemSchema],
});
const List = mongoose.model("List", ListSchema);
// Configure session middleware
app.use(
session({
secret: "keyboard cat",
resave: false,
saveUninitialized: true,
cookie: { secure: true },
})
);
// Configure passport middleware
app.use(passport.initialize());
app.use(passport.session());
// Configure passport to use Google OAuth2 strategy
passport.use(
new GoogleStrategy(
{
clientID: "myClientID",
clientSecret: "myClientSecret",
callbackURL: "http://localhost:3000/auth/google/ToDoList",
passReqToCallback: true,
},
function (request, accessToken, refreshToken, profile, done) {
return done(null, profile);
}
)
);
// Serialize user
passport.serializeUser(function (user, done) {
done(null, user.id);
});
// Deserialize user
passport.deserializeUser(function (id, done) {
console.log("CHECKED"); // THIS CONSOLE LOG NEVER GETS DISPLAYED
List.findOne({ googleId: id })
.then((list) => {
done(null, list);
})
.catch((err) => {
done(err);
});
});
// Authenticate user with Google OAuth2
app.get("/auth/google", passport.authenticate("google", { scope: ["profile"] }));
app.get(
"/auth/google/ToDoList",
passport.authenticate("google", { failureRedirect: "/" }),
(req, res) => {
List.findOne({ googleId: req.user.id })
.then((result) => {
if (result === null) {
const id = new List({
googleId: req.user.id,
nameUser: req.user.displayName,
}).save();
res.redirect("/new/" + req.user.displayName);
} else {
res.redirect("/new/" + req.user.displayName);
}
})
.catch((err) => {
console.log(err);
});
}
);
// Route that always returns false for req.isAuthenticated()
app.get("/new/:newWeb", function (req, res) {
console.log(req.isAuthenticated());
});
// Other routes
app.listen(3000, function () {
console.log("Server started on port 3000");
});
Can you help me understand why my deserializeUser function is not getting called, even though the user is successfully authenticated?