You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
49 lines
1.2 KiB
49 lines
1.2 KiB
import passport from 'passport';
|
|
import { Strategy as GoogleStrategy } from 'passport-google-oauth20';
|
|
import dotenv from 'dotenv';
|
|
import User from '../models/User.js';
|
|
|
|
dotenv.config();
|
|
|
|
passport.serializeUser((user, done) => {
|
|
done(null, user.id);
|
|
});
|
|
|
|
passport.deserializeUser(async (id, done) => {
|
|
try {
|
|
const user = await User.findById(id);
|
|
done(null, user);
|
|
} catch (err) {
|
|
done(err, null);
|
|
}
|
|
});
|
|
|
|
passport.use(
|
|
new GoogleStrategy(
|
|
{
|
|
clientID: process.env.GOOGLE_CLIENT_ID,
|
|
clientSecret: process.env.GOOGLE_CLIENT_SECRET,
|
|
callbackURL: 'http://localhost:5000/auth/google/callback',
|
|
proxy: true
|
|
},
|
|
async (accessToken, refreshToken, profile, done) => {
|
|
try {
|
|
const existingUser = await User.findOne({ googleId: profile.id });
|
|
if (existingUser) {
|
|
return done(null, existingUser);
|
|
}
|
|
|
|
const newUser = await new User({
|
|
googleId: profile.id,
|
|
email: profile.emails[0].value,
|
|
name: profile.displayName,
|
|
avatar: profile.photos[0].value,
|
|
}).save();
|
|
|
|
done(null, newUser);
|
|
} catch (err) {
|
|
done(err, null);
|
|
}
|
|
}
|
|
)
|
|
); |