Last active
August 5, 2024 08:13
-
-
Save MinSomai/78598fe3ad3b4091e00e52448d0b2644 to your computer and use it in GitHub Desktop.
PayloadCMS upsert social auth user after arctic auth
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const upsertAuthUser = async (result: { | |
email: string | null; | |
userId: string | null; | |
token: string | null; | |
refreshToken: string | null; | |
name: string | null; | |
meta: any; | |
}, providerType: ProviderTypes): Promise<Result> => { | |
let foundSocialUser: null | SocialAuthUser = null; | |
const foundSocialUserAll = await payload.find({ | |
collection: "social-auth-users", | |
where: { | |
and: [ | |
{ | |
isDeleted: { | |
equals: false, | |
}, | |
}, | |
{ | |
or: [{ | |
email: { | |
equals: result?.email, | |
}, | |
providerUserId: { | |
equals: result?.userId, | |
} | |
}] | |
} | |
] | |
} | |
}) as unknown as PaginatedDocs<SocialAuthUser>; | |
if (foundSocialUserAll?.docs?.length === 0 && foundSocialUserAll?.totalDocs === 0) { | |
const foundUser = await payload.find({ | |
collection: "users", | |
where: { | |
email: { | |
equals: result?.email | |
} | |
} | |
}) | |
if (foundUser?.docs?.length !== 0 && foundUser?.totalDocs !== 0) { | |
throw new Error("User already exist"); | |
} | |
const randomSecret = Encryption.randomBytes(); | |
const encryptedRandomSecret = Encryption.encrypt(randomSecret); | |
const createdSocialUser = await payload.create({ | |
collection: "social-auth-users", | |
data: { | |
name: result?.name, | |
email: result?.email, | |
providerUserId: result?.userId, | |
provider: providerType, | |
secret: encryptedRandomSecret, | |
providerAccessToken: result?.token, | |
providerRefreshToken: result?.refreshToken, | |
meta: result?.meta | |
}, | |
}) as unknown as SocialAuthUser; | |
const createdUser = await payload.create({ | |
collection: "users", | |
data: { | |
name: result?.name, | |
email: result?.email, | |
password: encryptedRandomSecret, | |
}, | |
}); | |
await payload.create({ | |
collection: "auth-identities", | |
data: { | |
user: createdUser?.id, | |
email: result?.email, | |
provider: providerType, | |
socialAuthUser: createdSocialUser?.id, | |
}, | |
}); | |
foundSocialUser = createdSocialUser; | |
} else { | |
foundSocialUser = foundSocialUserAll?.docs?.[0] | |
} | |
const user = await payload.login({ | |
collection: "users", | |
data: { | |
email: foundSocialUser.email, | |
password: foundSocialUser.secret, | |
}, | |
}); | |
return user; | |
} | |
export { | |
upsertAuthUser | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment