feat(api): send message to Sentry if duplicate accounts (#55171)

This commit is contained in:
Oliver Eyton-Williams
2024-06-13 16:15:11 +02:00
committed by GitHub
parent c508259cf2
commit b54edc7e1c
2 changed files with 64 additions and 3 deletions

View File

@@ -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();
});
});

View File

@@ -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 }