From bbeea5b0ec64885e3cccebd536215c1c78e9d2bf Mon Sep 17 00:00:00 2001 From: Jayvin Hernandez Date: Sat, 17 Dec 2022 09:37:29 -0800 Subject: [PATCH] hotfix: make oauthid optional (#249) --- .../migration.sql | 2 +- src/lib/middleware/withOAuth.ts | 42 ++++++++++++++----- 2 files changed, 32 insertions(+), 12 deletions(-) diff --git a/prisma/migrations/20221207035224_add_oauth_user_id/migration.sql b/prisma/migrations/20221207035224_add_oauth_user_id/migration.sql index 2cc9785..ac2562b 100644 --- a/prisma/migrations/20221207035224_add_oauth_user_id/migration.sql +++ b/prisma/migrations/20221207035224_add_oauth_user_id/migration.sql @@ -6,7 +6,7 @@ */ -- AlterTable -ALTER TABLE "OAuth" ADD COLUMN "oauthId" TEXT NOT NULL; +ALTER TABLE "OAuth" ADD COLUMN "oauthId" TEXT; -- CreateIndex CREATE UNIQUE INDEX "OAuth_provider_oauthId_key" ON "OAuth"("provider", "oauthId"); diff --git a/src/lib/middleware/withOAuth.ts b/src/lib/middleware/withOAuth.ts index 76d96c5..21e9675 100644 --- a/src/lib/middleware/withOAuth.ts +++ b/src/lib/middleware/withOAuth.ts @@ -56,14 +56,34 @@ export const withOAuth = const { state } = req.query as { state?: string }; - const existingOauth = await prisma.oAuth.findUnique({ - where: { - provider_oauthId: { - provider: provider.toUpperCase() as OauthProviders, - oauthId: oauth_resp.user_id, + let existingOauth; + try { + existingOauth = await prisma.oAuth.findUnique({ + where: { + provider_oauthId: { + provider: provider.toUpperCase() as OauthProviders, + oauthId: oauth_resp.user_id as string, + }, }, - }, - }); + }); + } catch (e) { + if (e.code === 'P2002') { + const existing = await prisma.user.findFirst({ + where: { + oauth: { + some: { + provider: provider.toUpperCase() as OauthProviders, + username: oauth_resp.username, + }, + }, + }, + include: { + oauth: true, + }, + }); + existingOauth = existing?.oauth?.find((o) => o.provider === provider.toUpperCase()); + } + } const existingUser = await prisma.user.findFirst({ where: { @@ -98,7 +118,7 @@ export const withOAuth = token: oauth_resp.access_token, refresh: oauth_resp.refresh_token || null, username: oauth_resp.username, - oauthId: oauth_resp.user_id, + oauthId: oauth_resp.user_id as string, }, }, avatar: oauth_resp.avatar, @@ -125,7 +145,7 @@ export const withOAuth = token: oauth_resp.access_token, refresh: oauth_resp.refresh_token || null, username: oauth_resp.username, - oauthId: oauth_resp.user_id, + oauthId: oauth_resp.user_id as string, }, }); @@ -142,7 +162,7 @@ export const withOAuth = token: oauth_resp.access_token, refresh: oauth_resp.refresh_token || null, username: oauth_resp.username, - oauthId: oauth_resp.user_id, + oauthId: oauth_resp.user_id as string, }, }); @@ -168,7 +188,7 @@ export const withOAuth = token: oauth_resp.access_token, refresh: oauth_resp.refresh_token || null, username: oauth_resp.username, - oauthId: oauth_resp.user_id, + oauthId: oauth_resp.user_id as string, }, }, avatar: oauth_resp.avatar,