I've successfully set up an express server that uses Google OAuth for user authentication. One interesting challenge I'm facing is how to handle the scenario where a user logs out of Google services (like Gmail) and automatically log them out from my app as well.
app.get('/auth/google/callback', async (req, res) => {
const code = req.query.code as string
const { tokens } = await authClient.getToken(code)
authClient.setCredentials(tokens)
const { data } = await google.oauth2('v2').userinfo.get({ auth: authClient })
let user = await prisma.user.findUnique({ where: { googleId: data.id! } })
if (!user) {
user = await prisma.user.create({
data: { googleId: data.id!, displayName: data.name! },
})
}
const token = jwt.sign(user, secret)
res.cookie('token', token, { httpOnly: true, maxAge: 24 * 60 * 60 * 1000 })
res.redirect(origin)
})