From 981336f1f6cf8bf135c26d9fcf06ee98af9ab1b4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Cl=C3=A9ment=20JANIN?= Date: Thu, 22 Feb 2024 11:14:11 -0500 Subject: [PATCH] fix: retrieve internal user id instead and pass it to the UserSignIn audit log instead of using the Cognito sub id (#3266) --- pages/api/auth/[...nextauth].ts | 26 +++++++++++++++++++++++++- 1 file changed, 25 insertions(+), 1 deletion(-) diff --git a/pages/api/auth/[...nextauth].ts b/pages/api/auth/[...nextauth].ts index 0f8ad6e2ea..96aed44a5d 100644 --- a/pages/api/auth/[...nextauth].ts +++ b/pages/api/auth/[...nextauth].ts @@ -115,7 +115,31 @@ export const authOptions: NextAuthOptions = { adapter: PrismaAdapter(prisma), events: { async signIn({ user }) { - logEvent(user.id, { type: "User", id: user.id }, "UserSignIn"); + if (!user.email) { + throw new Error( + "Could not produce UserSignIn audit log because of undefined email information" + ); + } + + const internalUser = await prisma.user.findUnique({ + where: { + email: user.email, + }, + select: { + id: true, + }, + }); + + if (internalUser === null) { + throw new Error("Could not produce UserSignIn audit log because user does not exist"); + } + + logEvent( + internalUser.id, + { type: "User", id: internalUser.id }, + "UserSignIn", + `Cognito user unique identifier (sub): ${user.id}` + ); }, async signOut({ token }) { logEvent(token.userId, { type: "User", id: token.userId }, "UserSignOut");