From 42a133e99169ff74c50f4e58958fd8802b88f9e1 Mon Sep 17 00:00:00 2001 From: Luke Vella Date: Wed, 7 Feb 2024 16:59:53 +0700 Subject: [PATCH] =?UTF-8?q?=F0=9F=90=9B=20Fix=20broken=20account=20linking?= =?UTF-8?q?=20when=20using=20SSO=20(#1019)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- apps/web/src/utils/auth.ts | 10 +++++++--- apps/web/src/utils/auth/merge-user.ts | 16 +--------------- 2 files changed, 8 insertions(+), 18 deletions(-) diff --git a/apps/web/src/utils/auth.ts b/apps/web/src/utils/auth.ts index 00831159d..cff04b80a 100644 --- a/apps/web/src/utils/auth.ts +++ b/apps/web/src/utils/auth.ts @@ -222,8 +222,8 @@ const getAuthOptions = (...args: GetServerSessionParams) => } else { // merge guest user into newly logged in user const session = await getServerSession(...args); - if (session && user.email && session.user.email === null) { - await mergeGuestsIntoUser(user.email, [session.user.id]); + if (session && session.user.email === null) { + await mergeGuestsIntoUser(user.id, [session.user.id]); } posthog?.capture({ @@ -238,7 +238,11 @@ const getAuthOptions = (...args: GetServerSessionParams) => return true; }, - async jwt({ token, user, trigger, session }) { + async jwt({ token, user, trigger, account, session }) { + if (trigger === "signUp" && account?.providerAccountId) { + // merge accounts assigned to provider account id to the current user id + await mergeGuestsIntoUser(user.id, [account.providerAccountId]); + } if (trigger === "update" && session) { if (token.email) { // For registered users we want to save the preferences to the database diff --git a/apps/web/src/utils/auth/merge-user.ts b/apps/web/src/utils/auth/merge-user.ts index f7cc4da82..cf560fd43 100644 --- a/apps/web/src/utils/auth/merge-user.ts +++ b/apps/web/src/utils/auth/merge-user.ts @@ -1,23 +1,9 @@ import { prisma } from "@rallly/database"; -import * as Sentry from "@sentry/node"; export const mergeGuestsIntoUser = async ( - email: string, + userId: string, guestIds: string[], ) => { - const user = await prisma.user.findUnique({ - where: { - email: email, - }, - }); - - const userId = user?.id; - - if (!userId) { - Sentry.captureMessage("Could not find user to merge guests into."); - return; - } - await prisma.poll.updateMany({ where: { userId: {