From 39034e2249a5a5ef1d0852f39028bfa9b1d46bb4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Frane=20Poli=C4=87?= <16856471+fPolic@users.noreply.github.com> Date: Mon, 23 Sep 2024 10:53:53 +0200 Subject: [PATCH] fix(user): check if user account with email already exist on invite create (#9243) **What** - when creating an invite, validate that provided email is not already used for existing user account --- FIXES CC-513 --- .../__tests__/invite.spec.ts | 23 +++++++++++++++++++ .../modules/user/src/services/user-module.ts | 13 +++++++++++ 2 files changed, 36 insertions(+) diff --git a/packages/modules/user/integration-tests/__tests__/invite.spec.ts b/packages/modules/user/integration-tests/__tests__/invite.spec.ts index 0247945f88..9fd1aef4f1 100644 --- a/packages/modules/user/integration-tests/__tests__/invite.spec.ts +++ b/packages/modules/user/integration-tests/__tests__/invite.spec.ts @@ -223,6 +223,29 @@ moduleIntegrationTestRunner({ ) }) + it("should throw if there is an existing user with the invite email", async () => { + let error + await service.createUsers([ + { + email: "existing@email.com", + }, + ]) + + try { + await service.createInvites([ + { + email: "existing@email.com", + }, + ]) + } catch (e) { + error = e + } + + expect(error.message).toBe( + `User account for following email(s) already exist: existing@email.com` + ) + }) + it("should emit invite created events", async () => { const eventBusSpy = jest.spyOn(MockEventBusService.prototype, "emit") await service.createInvites(defaultInviteData) diff --git a/packages/modules/user/src/services/user-module.ts b/packages/modules/user/src/services/user-module.ts index 09faa00a4f..df53020118 100644 --- a/packages/modules/user/src/services/user-module.ts +++ b/packages/modules/user/src/services/user-module.ts @@ -298,6 +298,19 @@ export default class UserModuleService data: UserTypes.CreateInviteDTO[], @MedusaContext() sharedContext: Context = {} ): Promise { + const alreadyExistingUsers = await this.listUsers({ + email: data.map((d) => d.email), + }) + + if (alreadyExistingUsers.length) { + throw new MedusaError( + MedusaError.Types.INVALID_DATA, + `User account for following email(s) already exist: ${alreadyExistingUsers + .map((u) => u.email) + .join(", ")}` + ) + } + const toCreate = data.map((invite) => { return { ...invite,