refactor utils

This commit is contained in:
wancat committed 2024-02-19 18:05:00 +08:00
1 parent 9509bbc355
commit d6c95cea4a
13 files changed
+126 -31

No files matched your search

+47
View File
@@ -0,0 +1,47 @@
import { User } from '@linux-odyssey/models'
import type { Profile } from 'passport'
import type { VerifyCallback } from 'passport-oauth2'
export type SocialLogin = {
provider: string
id: string
displayName: string
}
export default async function oauthVerify(
provider: string,
profile: Profile,
query: Record<string, any>,
cb: VerifyCallback
) {
process.nextTick(async () => {
try {
const email = profile.emails ? profile.emails[0]?.value : undefined
if (!email) {
return cb(new Error('No email found'))
}
const socialLogin = {
provider,
id: profile.id,
displayName: profile.displayName,
}
let user = await User.findOne(query)
if (!user) {
user = await User.findOne({ email })
if (!user) {
const newUser = { email, socialLogin }
return cb(null, { newUser })
}
user.socialLogins.set(provider, socialLogin)
await user.save()
}
return cb(null, user)
} catch (err) {
return cb(
err instanceof Error ? err : new Error('An unknown error occurred')
)
}
})
}