-
-
Save rewbs/dc1b70bea341cc6599f85af9994bce3f to your computer and use it in GitHub Desktop.
Auth0 -> privy matching
This file contains hidden or 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
| export async function findExistingDbUserFromPrivyUser(privyUser: PrivyInternalUser) { | |
| const log = getUtilityLogger(); | |
| // First, check if a Privy account already exists | |
| const account = await db.account.findUnique({ | |
| where: { | |
| provider_providerAccountId: { | |
| provider: "privy", | |
| providerAccountId: privyUser.id, | |
| }, | |
| }, | |
| include: { | |
| user: { | |
| include: { | |
| accounts: true, | |
| } | |
| } | |
| }, | |
| }); | |
| if (account) { | |
| // Privy account exists, return the user | |
| return {isPrivyLinked: true, user: account.user}; | |
| } | |
| // No Privy account exists, gather all the other parameters we can use to find an existing user | |
| const linkedIds = privyUser.linkedAccounts.map((linkedAccount) => { | |
| if (linkedAccount.type === 'email' && linkedAccount.address) { | |
| return { email: linkedAccount.address, idpId: undefined }; | |
| } | |
| let email; | |
| if ('email' in linkedAccount && linkedAccount.email) { | |
| email = linkedAccount.email; | |
| } | |
| let idpId; | |
| if ('subject' in linkedAccount && linkedAccount.subject) { | |
| idpId = {provider: linkedAccount.type, id: linkedAccount.subject }; | |
| } | |
| return { email, idpId }; | |
| }); | |
| // try email and IDP ids of each linked account | |
| for (const { email, idpId } of linkedIds) { | |
| if (email) { | |
| const existingUser = await db.user.findUnique({ | |
| where: { email }, | |
| include: { accounts: true }, | |
| }); | |
| if (existingUser) { | |
| log.info("Found existing user by email", { email, userId: existingUser.id }); | |
| return {isPrivyLinked: false, user: existingUser }; | |
| } | |
| } | |
| const auth0IdpString = idpId && privyIdpDetailsToAuth0Id(idpId); | |
| if (auth0IdpString) { | |
| const existingUser = await db.user.findFirst({ | |
| where: { | |
| accounts: { | |
| some: { | |
| provider: "auth0", | |
| providerAccountId: auth0IdpString, | |
| }, | |
| }, | |
| }, | |
| include: { accounts: true }, | |
| }); | |
| if (existingUser) { | |
| log.info("Found existing user by IDP ID", { idpId, userId: existingUser.id }); | |
| return {isPrivyLinked: false, user: existingUser }; | |
| } | |
| } | |
| } | |
| return null; // No existing user found | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment