Divyanshu Rawat
Divyanshu Rawat

Reputation: 9

Login With Google using passport-google-oauth2 not working after deployment

On localhost, everything is working fine. After authenticating, I am getting cookies, and the profile picture is displaying on my navbar.

However, after deploying to Vercel, the code does not work. I am not receiving any user data or cookies in the response from the backend, even though the redirection is successful.

URL - https://coding4u-project.vercel.app/

Index.js file (Node.js)

import express from "express";
import morgan from "morgan";
import bodyParser from "body-parser";
import cookieParser from "cookie-parser";
import cors from "cors";
import mongoose from "mongoose";
import blogRoutes from "./routes/blog.js";
import authRoutes from "./routes/auth.js";
import userRoutes from "./routes/user.js";
import categoryRoutes from "./routes/category.js";
import tagRoutes from "./routes/tag.js";
import formRoutes from "./routes/form.js";
import ImageRoutes from "./routes/images.js";
import storyRoutes from "./routes/slides.js";
import "dotenv/config.js";
import session from "express-session";
import passport from "passport";
import { Strategy as GoogleStrategy } from 'passport-google-oauth2';
const clientid = process.env.GOOGLE_CLIENT_ID
const clientsecret = process.env.GOOGLE_CLIENT_SECRET
import User from "./models/user.js";
import jwt from "jsonwebtoken";
import { FRONTEND } from "./config.js";

const app = express();

app.use(cors({
  origin: ["http://localhost:3000", FRONTEND],
  methods: "GET,POST,PUT,DELETE,PATCH",
  credentials: true
}));

mongoose.set("strictQuery", true);
mongoose.connect(process.env.DATABASE, {}).then(() => console.log("DB connected")).catch((err) => console.log("DB Error => ", err));

app.use(morgan('dev'));
app.use(bodyParser.json());
app.use(cookieParser());
app.use('/api', blogRoutes);
app.use('/api', authRoutes);
app.use('/api', userRoutes);
app.use('/api', categoryRoutes);
app.use('/api', tagRoutes);
app.use('/api', formRoutes);
app.use('/api', ImageRoutes);
app.use('/api', storyRoutes);

app.get('/', (req, res) => { res.json("Backend index"); });
const port = process.env.PORT || 8000;
app.listen(port, () => { console.log(`Server is running on port ${port}`); });

app.use(session({
  secret: clientsecret,
  resave: false,
  saveUninitialized: true,
  cookie: {
    secure: true,
    sameSite: 'None',
    httpOnly: true
  },
}))


app.use(passport.initialize());
app.use(passport.session());


passport.use(
  new GoogleStrategy({
    clientID: clientid,
    clientSecret: clientsecret,
    callbackURL: "/auth/google/callback",
    scope: ["profile", "email"]
  },
    async (accessToken, refreshToken, profile, done) => {
      try {
        let user = await User.findOne({ email: profile.emails[0].value }, "email username name profile role");
        return done(null, user)
      } catch (error) {
        return done(error, null)
      }
    }
  )
)

passport.serializeUser((user, done) => { done(null, user); })
passport.deserializeUser((user, done) => { done(null, user); });

app.get("/auth/google", passport.authenticate("google", { scope: ["profile", "email"] }));


app.get("/auth/google/callback", passport.authenticate("google", {
  successRedirect: `${FRONTEND}`,
  failureRedirect: `${FRONTEND}/signin`
}))


app.get("/login/success", async (req, res) => {
  if (req.user) {
    console.log(req.user);
    const token = jwt.sign({ _id: req.user._id }, "Div12@", { expiresIn: '10d' });
    res.status(200).json({ user: req.user, token })
  }
  else { res.status(400).json({ message: "Not Authorized" }) }
})


app.get("/logout", (req, res, next) => {
  req.logout(function (err) {
    if (err) { return next(err) }
    res.redirect(`${FRONTEND}/signin`);
  })
})

Frontend code navbar (Next.js) -

import Link from 'next/link';
import { APP_NAME, BACKEND } from "../config";
import { isAuth } from '../actions/auth';
import styles from "../styles/NavbarFooter.module.css";
import { useState, useEffect } from 'react';
import fetch from 'isomorphic-fetch';
import { googleauthenticate } from '../actions/auth';

const Navbar = () => {

  const [user, setUser] = useState(null);

  const getUser = async () => {
    try {
      const response = await fetch(`${BACKEND}/login/success`, { method: "GET", credentials: "include" });
      if (response.ok) {
        const data = await response.json();
        console.log(data);
        googleauthenticate(data);
        setUser(isAuth());
      }
    } catch (error) { console.log("User is not logged In"); }
  };

  useEffect(() => { getUser(); }, []);

  function disablenavbar2() {
    let x = document.getElementById("disable")
    if (x.style.display === "block") { x.style.display = "none"; }
    else { x.style.display = "block" }
  }

  function disablenavbar() { document.getElementById("disable").style.display = "none"; }

  return (
    <>
      <nav className={styles.nav}>

        <div className={styles.span} onClick={disablenavbar2}>☰</div>

        <Link href="/"><div className={styles.logo}> 📚 {APP_NAME}</div></Link>

        <ul id="disable" onClick={disablenavbar}>
          <li><Link href="/categories/react" >React</Link></li>
          <li><Link href="/categories/javascript">Javascript</Link></li>
          <li><Link href="/categories/django">Django</Link></li>
          <li><Link href="/categories/python">Python</Link></li>
          <li><Link href="/categories/seo">SEO</Link></li>
          <li><Link href="/categories/wordpress">Wordpress</Link></li>


          {!user && (<><li><Link href="/signin">Signin </Link></li><li><Link href="/signup">Signup</Link></li></>)}

          {user && isAuth().role === 1 && (<li><a className={styles.userdash} href="/admin"> {`${isAuth().name} ‒ Admin`}</a></li>)}
          {user && isAuth().role === 0 && (<li><a className={styles.userdash} href="/admin"> {`${isAuth().name} ‒ User`}</a></li>)}


        </ul>
      </nav>

    </>

  )
}


export default Navbar

In localhost the everything is working fine, After authenticating I am getting cookies and profile picture is displaying on my navbar. But after deployment to vercel the code not works. I am not getting any user or cookies in response from backend although redirection is successfull that means it checks whether user (email) is in database or not.

Upvotes: 0

Views: 62

Answers (0)

Related Questions