diff --git a/api/src/routes/helpers/auth-helpers.test.ts b/api/src/routes/helpers/auth-helpers.test.ts new file mode 100644 index 00000000000..a68f6f4d9c1 --- /dev/null +++ b/api/src/routes/helpers/auth-helpers.test.ts @@ -0,0 +1,55 @@ +import Fastify, { FastifyInstance } from 'fastify'; + +import db from '../../db/prisma'; +import { createUserInput } from '../../utils/create-user'; +import { findOrCreateUser } from './auth-helpers'; + +const captureException = jest.fn(); + +async function setupServer() { + const fastify = Fastify(); + await fastify.register(db); + // @ts-expect-error we're mocking the Sentry plugin + fastify.Sentry = { captureException }; + return fastify; +} + +describe('findOrCreateUser', () => { + let fastify: FastifyInstance; + const email = 'test@user.com'; + beforeAll(async () => { + fastify = await setupServer(); + }); + + afterEach(async () => { + await fastify.prisma.user.deleteMany({ where: { email } }); + await fastify.close(); + jest.clearAllMocks(); + }); + + it('should send a message to Sentry if there are multiple users with the same email', async () => { + await fastify.prisma.user.create({ data: createUserInput(email) }); + await fastify.prisma.user.create({ data: createUserInput(email) }); + + await findOrCreateUser(fastify, email); + + expect(captureException).toHaveBeenCalledTimes(1); + expect(captureException).toHaveBeenCalledWith( + new Error('Multiple user records found for: test@user.com') + ); + }); + + it('should NOT send a message if there is only one user with the email', async () => { + await fastify.prisma.user.create({ data: createUserInput(email) }); + + await findOrCreateUser(fastify, email); + + expect(captureException).not.toHaveBeenCalled(); + }); + + it('should NOT send a message if there are no users with the email', async () => { + await findOrCreateUser(fastify, email); + + expect(captureException).not.toHaveBeenCalled(); + }); +}); diff --git a/api/src/routes/helpers/auth-helpers.ts b/api/src/routes/helpers/auth-helpers.ts index b82da1d28c8..762c0ece13c 100644 --- a/api/src/routes/helpers/auth-helpers.ts +++ b/api/src/routes/helpers/auth-helpers.ts @@ -10,15 +10,21 @@ import { createUserInput } from '../../utils/create-user'; export const findOrCreateUser = async ( fastify: FastifyInstance, email: string -) => { +): Promise<{ id: string }> => { // TODO: handle the case where there are multiple users with the same email. // e.g. use findMany and throw an error if more than one is found. - const existingUser = await fastify.prisma.user.findFirst({ + const existingUser = await fastify.prisma.user.findMany({ where: { email }, select: { id: true } }); + if (existingUser.length > 1) { + fastify.Sentry.captureException( + new Error(`Multiple user records found for: ${email}`) + ); + } + return ( - existingUser ?? + existingUser[0] ?? (await fastify.prisma.user.create({ data: createUserInput(email), select: { id: true }