From 64f5649db1d757225a62819ff2f66339743154d1 Mon Sep 17 00:00:00 2001 From: Khalim Conn-Kowlessar Date: Tue, 11 Jul 2023 10:31:26 +0100 Subject: [PATCH] Added better error handling for sign in api --- src/app/api/auth/[...nextauth]/route.ts | 56 +++++++++++++++---------- 1 file changed, 33 insertions(+), 23 deletions(-) diff --git a/src/app/api/auth/[...nextauth]/route.ts b/src/app/api/auth/[...nextauth]/route.ts index ad18277e..a1335e88 100644 --- a/src/app/api/auth/[...nextauth]/route.ts +++ b/src/app/api/auth/[...nextauth]/route.ts @@ -32,33 +32,43 @@ export const AuthOptions: NextAuthOptions = { }, callbacks: { async signIn({ user, account }) { - if (user == null || user.email == null) { - return "/beta"; - } + try { + if (user == null || user.email == null) { + return "/beta"; + } - const dbUser: User[] = await db - .select() - .from(userTable) - .where(eq(userTable.email, String(user.email))); - - if (dbUser.length !== 1 || account == null) { - return "/beta"; - } - - if (!dbUser[0].oauthId) { - // We make a second query to populate the oauthId and oauthProvider - console.log("Updating user with oauthId and oauthProvider"); - const provider = account.provider as OauthProvider; - - await db - .update(userTable) - .set({ oauthId: user.id, oauthProvider: provider }) + const dbUser: User[] = await db + .select() + .from(userTable) .where(eq(userTable.email, String(user.email))); - console.log("Updated oauthId and oauthProvider"); - } + if (dbUser.length > 1) { + console.error(`Multiple users found with email ${user.email}`); + return false; + } - return true; + if (dbUser.length !== 0 || account == null) { + return "/beta"; + } + + if (!dbUser[0].oauthId) { + // We make a second query to populate the oauthId and oauthProvider + console.log("Updating user with oauthId and oauthProvider"); + const provider = account.provider as OauthProvider; + + await db + .update(userTable) + .set({ oauthId: user.id, oauthProvider: provider }) + .where(eq(userTable.email, String(user.email))); + + console.log("Updated oauthId and oauthProvider"); + } + + return true; + } catch (error) { + console.error("Error during sign-in: ", error); + return false; + } }, async redirect({ baseUrl }) { const redirectUrl = baseUrl + "/home";