Issues in google auth
Asked about 1 month ago
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;