Search code examples
node.jsreactjspassport.jspassport-google-oauth

Cannot GET /auth/google/callback | PassportJs


Why I'm getting this error! Cannot GET /auth/google/callback after choosing an account from the google login page I got redirected to a white page with the above error, its been a week working on this google login thing!

This is index.js file:

const mongoose = require("mongoose");
const authRoute = require("./routes/auth");
const cors = require("cors");
const app = express();

const cookieSession = require("cookie-session");
const passportSetup = require("./passport");
const passport = require ("passport");

app.use(cookieSession({name: "session", keys: ["mokhtarah"], 
maxAge: 24 * 60 * 60 * 100 })
);

// Passport middleware
app.use(passport.initialize());
app.use(passport.session());

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

app.use(express.json());
app.use(express.urlencoded({extended: true}));

app.use("/api/auth", authRoute);
app.use("/api/users", userRoute);

app.listen("4000", () => {
    console.log("Backend is running.");
});

This is the passport.js file:

const User = require("./models/User");
const mongoose = require("mongoose");
const passport = require("passport");

const GoogleStrategy = require("passport-google-oauth20").Strategy;

passport.use(
 new GoogleStrategy(
        {
 clientID: "",
 clientSecret: "",
 callbackURL: "/auth/google/callback",
        },
 function (accessToken, refreshToken, profile, done)  {
 done(null, profile);
 console.log(profile)
        }
      )
    )
 
 passport.serializeUser((user, done) => {
 done(null, user);
    });
 
 passport.deserializeUser((user, done) => {
 done(null, user);
    });

This is the auth.js file:

const router = require("express").Router();
const User = require("../models/User");
const passport = require("passport");
router.get("/google", passport.authenticate("google", { scope: ["profile"] }))
router.get(
  "/google/callback",
  passport.authenticate("google", {
    successRedirect: 'http://localhost:3000/',
    failureRedirect: 'http://localhost:4000/auth/google'
})
)

//LOGIN WITHOUT PASSPORTJS
router.post("/login", async (req, res) => {
    try {
      const user = await User.findOne({ email: req.body.email });
      // if(!user) return res.status(400).json("Wrong credentials!");
      !user && res.status(400).json("Wrong credentials!");
  
      const validated = await bcrypt.compare(req.body.password, user.password);
      // if(!validated) return res.status(400).json("Wrong credentials!");
      !validated && res.status(400).json("Wrong credentials!");
  
      const { password, ...others } = user._doc;
      return res.status(200).json(others);
    } catch (err) {
      return res.status(500).json(err);
    }
  });

Login without passportjs works fine no issues only the google login, I just want the profile data to appear on my console log!

The Google Cloud Console: enter image description here


Solution

  • In the auth.js file add /auth as a prefix in /google/callback route and in the index.js file remove /api/auth.

    auth.js

    router.get('/auth/google/callback', // add **/auth**
      (req,res,next)=>{
        passport.authenticate('google', { failureRedirect: '/auth/google/error' }, async (error, user , info) => {
          if (error){
            return res.send({ message:error.message });
          }
          if (user){
            try {
              // your success code
              return res.send({
                data: result.data,
                message:'Login Successful' 
              });
            } catch (error) {
              // error msg 
              return res.send({ message: error.message });
            }
          }
        })(req,res,next);
      }); 
    

    index.js

    const mongoose = require("mongoose");
    const authRoute = require("./routes/auth");
    const cors = require("cors");
    const app = express();
    
    const cookieSession = require("cookie-session");
    const passportSetup = require("./passport");
    const passport = require ("passport");
    
    app.use(cookieSession({name: "session", keys: ["mokhtarah"], 
    maxAge: 24 * 60 * 60 * 100 })
    );
    
    // Passport middleware
    app.use(passport.initialize());
    app.use(passport.session());
    
    app.use(cors({origin: "http://localhost:3000",
    methods: "GET,POST,PUT,DELETE",
    credentials: true,}));
    
    app.use(express.json());
    app.use(express.urlencoded({extended: true}));
    
    app.use("/", authRoute); // ====> change here
    app.use("/api/users", userRoute);
    
    app.listen("4000", () => {
        console.log("Backend is running.");
    });