Issues in google auth

Asked about 1 month ago

1 Votes
3 Answers
8 Views

i have issues in production , i don't face it in local with google auth


const passport = require('passport');
const GoogleStrategy = require('passport-google-oauth20').Strategy;
const User = require('../models/userAuthModel');
require('dotenv').config();
const jwt = require('jsonwebtoken');
const express = require('express');
const router = express.Router();

const GOOGLE_CLIENT_ID = process.env.GOOGLE_CLIENT_ID;
const GOOGLE_CLIENT_SECRET = process.env.GOOGLE_CLIENT_SECRET;

passport.use(
    new GoogleStrategy(
        {
            clientID: GOOGLE_CLIENT_ID,
            clientSecret: GOOGLE_CLIENT_SECRET,
            callbackURL: 'http://localhost:8090/auth/google/callback', 
        },
        async (accessToken, refreshToken, profile, done) => {
            try {
                let user = await User.findOne({ googleId: profile.id });

                if (!user) {
                    user = new User({
                        googleId: profile.id,
                        name: profile.displayName,
                        email: profile.emails[0].value,
                        mobile: null, // Use null instead of an empty string
                        image: profile.photos[0].value,
                    });

                    await user.save();
                }

                return done(null, user);
            } catch (error) {
                return done(error, null);
            }
        }
    )
);

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

passport.deserializeUser(async (id, done) => {
    try {
        const user = await User.findById(id);
        done(null, user);
    } catch (error) {
        done(error, null);
    }
});

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

router.get('/auth/google/callback', passport.authenticate('google', { failureRedirect: '/' }), (req, res) => {
    try {
        // This will execute if authentication is successful
        const token = jwt.sign({ _id: req.user.id }, process.env.JWT_SECRET, {
            expiresIn: "15d",
        });

        res.cookie('user-auth-token', token, {
            httpOnly: true,
            secure: process.env.NODE_ENV === 'production',
            sameSite: 'None',
            maxAge: 15 * 24 * 60 * 60 * 1000
        });

        res.redirect('https://..........com');  // Change to your frontend URL
    } catch (error) {
        console.error("Error during Google callback:", error);
        res.status(500).json({ message: 'Authentication failed', error: error.message });
    }
});


router.get('/user', (req, res) => {
    if (req.isAuthenticated()) {
        res.json(req.user);
    } else {
        res.status(401).json({ message: 'Unauthorized' });
    }
});

module.exports = router;

3 Answers

Sort by:

Hi Ameer 👋,

I believe the issue is with the callbackURL

callbackURL: 'http://localhost:8090/auth/google/callback'

try to change to callbackURL: 'https://yourdomain/auth/google/callback'

Since you're using localhost so it wont work in production env. Try to change it to your production domain and verify that it has an SSL certificate due OAuth requirements.

Also I'm wondering if you're using MongoDB with Mongoose here, you're using User model without importing it. Try to use await User.create instead of new User followed by user.save();

Happy hacking.

شنو الدومين مالتك الي دتستعمله بالبرودكشن؟