oauth snippet -- google strategy
unknown
javascript
a year ago
1.3 kB
14
Indexable
Never
import passport from "passport"; import dotenv from "dotenv"; dotenv.config(); import { Strategy as GoogleStrategy } from "passport-google-oauth20"; import { User } from "../models/User.js"; passport.serializeUser((user, done) => { try { console.log('User:', user); done(null, user._id); //payload for deserialize will be the user id } catch (error) { console.error('Error in serializeUser:', error); done(error, null); } }); passport.deserializeUser(async (payload, done) => { console.log('In the deserialize function'); console.log('Payload:', payload) const user = await User.findById(payload); console.log(user); done(null, user); }); passport.use(new GoogleStrategy({ clientID: process.env.GOOGLE_ID, clientSecret: process.env.GOOGLE_SECRET, callbackURL: process.env.GOOGLE_REDIRECT_URL, scope: ['profile', 'email'] }, async (accessToken, refreshToken, profile, done) => { const email = profile.emails[0].value; const user = await User.findOne({ email: email }); if (!user) { const newUser = new User({ name: profile.displayName, email: email, password: 'oauth2' //todo: change this }); await newUser.save(); done(null, newUser); } else done(null, user); }));