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.
 

70 lines
1.5 KiB

import 'dotenv/config';
import { Router } from 'express';
import mongoose from 'mongoose';
import passport from 'passport';
import { Strategy as GoogleStrategy } from 'passport-google-oauth20';
interface UserInterface {
username: string;
googleId: string;
}
const UserSchema: mongoose.Schema<UserInterface> = new mongoose.Schema({
username: String,
googleId: String,
});
export const User = mongoose.model('User', UserSchema);
passport.use(
new GoogleStrategy(
{
clientID: process.env.GOOGLE_CLIENT_ID!,
clientSecret: process.env.GOOGLE_CLIENT_SECRET!,
callbackURL: process.env.GOOGLE_CALLBACK!,
},
async (accessToken: any, refreshToken: any, profile: any, cb) => {
User.findOne({ googleId: profile.id! }, async (err: any, user: any) => {
if (err) {
console.log('happens');
return cb(err);
}
if (!user) {
await User.create({
username: profile.displayName,
googleId: profile.id,
});
}
return cb(err, user);
});
}
)
);
export const authRouter = Router();
passport.serializeUser((user: any, done) => {
done(null, user);
});
passport.deserializeUser((user: any, done) => {
done(null, user);
});
authRouter.get(
'/google',
passport.authenticate('google', { scope: ['profile'] })
);
authRouter.get(
'/google/callback',
passport.authenticate('google'),
(req, res) => {
res.redirect('/');
}
);
authRouter.get('/logout', (req, res) => {
req.logout();
res.redirect((req.query['redirect'] as string) || '/');
});