From 81ad00a816b8bf938b240202a8cbccd98775e1af Mon Sep 17 00:00:00 2001 From: Morgan <33722304+ThyMinimalDev@users.noreply.github.com> Date: Thu, 15 Feb 2024 15:19:31 +0200 Subject: [PATCH] fix: safely delete userPassword (#13705) * fix: safely delete userPassword * fixup! fix: safely delete userPassword * fixup! Merge branch 'main' into fix-safely-delete-userpassword --- .../features/auth/lib/next-auth-options.ts | 23 +++++++++++++++---- 1 file changed, 19 insertions(+), 4 deletions(-) diff --git a/packages/features/auth/lib/next-auth-options.ts b/packages/features/auth/lib/next-auth-options.ts index aba2c07697..ce934bf695 100644 --- a/packages/features/auth/lib/next-auth-options.ts +++ b/packages/features/auth/lib/next-auth-options.ts @@ -1,4 +1,5 @@ import type { Membership, Team, UserPermissionRole } from "@prisma/client"; +import { PrismaClientKnownRequestError } from "@prisma/client/runtime/library"; import type { AuthOptions, Session } from "next-auth"; import type { JWT } from "next-auth/jwt"; import { encode } from "next-auth/jwt"; @@ -806,18 +807,32 @@ export const AUTH_OPTIONS: AuthOptions = { existingUserWithEmail.identityProvider === IdentityProvider.CAL && (idP === IdentityProvider.GOOGLE || idP === IdentityProvider.SAML) ) { - await prisma.user.update({ + const updatedUser = await prisma.user.update({ where: { email: existingUserWithEmail.email }, // also update email to the IdP email data: { - password: { - delete: true, - }, email: user.email, identityProvider: idP, identityProviderId: account.providerAccountId, }, }); + + // safely delete password from UserPassword table if it exists + try { + await prisma.userPassword.delete({ + where: { userId: updatedUser.id }, + }); + } catch (err) { + if ( + err instanceof PrismaClientKnownRequestError && + (err.code === "P2025" || err.code === "P2016") + ) { + log.warn("UserPassword not found for user", safeStringify(existingUserWithEmail)); + } else { + log.warn("Could not delete UserPassword for user", safeStringify(existingUserWithEmail)); + } + } + if (existingUserWithEmail.twoFactorEnabled) { return loginWithTotp(existingUserWithEmail.email); } else {