passport / discuss

A forum for discussing topics related to the usage of Passport.js.
1 stars 0 forks source link

passport.serializeUser never gets called #77

Open faisalsayed10 opened 1 year ago

faisalsayed10 commented 1 year ago

this is my server code:

Even though I am successfully logging in every time, the serializeUser never gets called at all and the /success route always shows unauthorized. I'm not sure what's wrong. Everything seems to be set up correctly.

import cors from "cors";
import dotenv from "dotenv";
import express, { NextFunction, Request, Response } from "express";
import session from "express-session";
import mongoose from "mongoose";
import passport from "passport";
import { Strategy as GoogleStrategy } from "passport-google-oauth20";
import User from "./User";
import { IMongoDBUser } from "./types";

dotenv.config();
const app = express();

mongoose.connect(
  `mongodb+srv://faisal:<password>@tmdr.p5m3x7x.mongodb.net/?retryWrites=true&w=majority`
);

// Middleware
app.use(express.json());
app.use(cors({ origin: "http://localhost:5173", credentials: true }));

app.set("trust proxy", 1);

app.use(
  session({
    name: "google-auth-session",
    secret: "secretcode",
    resave: false,
    saveUninitialized: true,
    cookie: {
      sameSite: "none",
      httpOnly: false,
      secure: false,
    },
  })
);
app.use(passport.initialize());
app.use(passport.session());

passport.serializeUser((user: any, done) => {
  console.log("serializeUser", user);
  done(null, user);
});

passport.deserializeUser((user: any, done) => {
  console.log("deserializeUser", user);
  done(null, user);
});

passport.use(
  new GoogleStrategy(
    {
      clientID: "feafeafeafea.apps.googleusercontent.com",
      clientSecret: "f-Aokfeafeafeafea",
      callbackURL: "/auth/google/callback",
    },
    async (accessToken, refreshToken, profile, cb) => {
      const user: IMongoDBUser = {
        id: profile.id,
        email: profile.emails![0].value,
        name: profile.displayName!,
        picture: profile.photos![0].value,
        access_token: accessToken,
        refresh_token: refreshToken,
      };

      let currentUser = await User.findOne({ email: profile.emails![0].value });

      if (currentUser) {
        return cb(null, currentUser);
      } else {
        currentUser = await User.create(user);
        return cb(null, currentUser);
      }
    }
  )
);

const isLoggedIn = (req: Request, res: Response, next: NextFunction) => {
  if (req.user) {
    next();
  } else {
    res.sendStatus(401);
  }
};

app.get("/", (req, res) => {
  res.json({ message: "You are not logged in" });
});

app.get("/failed", (req, res) => {
  res.send("Failed");
});

app.get("/success", isLoggedIn, (req, res) => {
  res.send(`Welcome ${(req.user as any)?.email}`);
});

app.get(
  "/auth/google",
  passport.authorize("google", {
    scope: ["email", "profile", "https://www.googleapis.com/auth/gmail.modify"],
    accessType: "offline",
    prompt: "consent",
  })
);

app.get("/auth/google/callback", passport.authorize("google"), (req, res) => {
  return res.redirect("/success");
});

app.get("/auth/logout", (req, res, next) => {
  req.logout(next);
  res.send("done");
});

app.listen(process.env.PORT || 5000, () => {
  console.log("Server started on port", process.env.PORT || 5000);
});