Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

passport.serializeUser never gets called #77

Open
faisalsayed10 opened this issue Aug 17, 2023 · 0 comments
Open

passport.serializeUser never gets called #77

faisalsayed10 opened this issue Aug 17, 2023 · 0 comments

Comments

@faisalsayed10
Copy link

faisalsayed10 commented Aug 17, 2023

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);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant