feat: use google to login

This commit is contained in:
Lin, Hung-Shin committed 2023-10-05 11:50:00 +08:00
1 parent 44b3304046
commit 1880b30029
2 files changed
+39 -2

No files matched your search

+33 -1
View File
@@ -1,6 +1,7 @@
import GoogleStrategy from 'passport-google-oidc'
import config from '../config.js'
import User from '../models/user.js'
console.log('Google config:', config.google)
@@ -13,6 +14,37 @@ export default new GoogleStrategy(
},
function verify(issuer, profile, cb) {
console.log('Get a google login:', profile)
return cb(null, profile)
process.nextTick(async () => {
const email = profile.emails[0]?.value
if (!email) {
cb(new Error('No email found'))
return
}
let user = await User.findOne({ 'google.id': profile.id })
if (!user) {
user = await User.findOne({ email })
const google = {
id: profile.id,
displayName: profile.displayName,
}
console.log('Existing user:', user)
if (!user) {
user = new User({
email,
google,
})
} else if (user.google?.id) {
cb(new Error('Email already used and binded to another account'))
return
} else {
user.google = google
}
await user.save()
}
cb(null, user)
})
}
)
+6 -1
View File
@@ -4,7 +4,8 @@ const User = model('User', {
username: {
type: String,
unique: true,
required: true,
required: false, // should be required,
// but need to let social login users to pick one after login
},
email: {
type: String,
@@ -12,6 +13,10 @@ const User = model('User', {
required: true,
},
hashedPassword: String,
google: {
id: String,
displayName: String,
},
})
export default User