passport.ts40 lines, 1.0 KB
| 1 | import passport from "passport"; |
| 2 | import { Strategy as GoogleStrategy } from "passport-google-oauth20"; |
| 3 | import User, { IUser } from "../models/user.model"; |
| 4 | |
| 5 | passport.use( |
| 6 | new GoogleStrategy( |
| 7 | { |
| 8 | clientID: process.env.GOOGLE_CLIENT_ID!, |
| 9 | clientSecret: process.env.GOOGLE_CLIENT_SECRET!, |
| 10 | callbackURL: "/auth/google/callback", |
| 11 | }, |
| 12 | async (accessToken, refreshToken, profile, done) => { |
| 13 | try { |
| 14 | let user = await User.findOne({ googleId: profile.id }); |
| 15 | |
| 16 | if (!user) { |
| 17 | user = await User.create({ |
| 18 | googleId: profile.id, |
| 19 | email: profile.emails![0].value, |
| 20 | displayName: profile.displayName, |
| 21 | profilePicture: profile.photos![0].value, |
| 22 | }); |
| 23 | } |
| 24 | |
| 25 | done(null, user); |
| 26 | } catch (error) { |
| 27 | done(error as Error, undefined); |
| 28 | } |
| 29 | } |
| 30 | ) |
| 31 | ); |
| 32 | |
| 33 | passport.serializeUser((user: any, done) => { |
| 34 | done(null, user._id); |
| 35 | }); |
| 36 | |
| 37 | passport.deserializeUser(async (id: string, done) => { |
| 38 | const user = await User.findById(id); |
| 39 | done(null, user); |
| 40 | }); |