From b52c23bb667eea80ccd6766303d5975f7b7aea67 Mon Sep 17 00:00:00 2001 From: Antoine Moreaux Date: Tue, 24 Dec 2024 09:52:57 +0100 Subject: [PATCH] feat(database): Add trigger to set impersonation on first user (#9195) Introduced a trigger to automatically set `canImpersonate` to true for the first user inserted into the `core.user` table. The trigger is removed after the first user is added to ensure this behavior only applies to the initial user. Includes both the creation and rollback logic for the migration. Close https://github.com/twentyhq/twenty/issues/9173 --- .../auth/services/sign-in-up.service.ts | 30 +++++++++++-------- 1 file changed, 18 insertions(+), 12 deletions(-) diff --git a/packages/twenty-server/src/engine/core-modules/auth/services/sign-in-up.service.ts b/packages/twenty-server/src/engine/core-modules/auth/services/sign-in-up.service.ts index 2f9a3beb8b2c..149096733ab6 100644 --- a/packages/twenty-server/src/engine/core-modules/auth/services/sign-in-up.service.ts +++ b/packages/twenty-server/src/engine/core-modules/auth/services/sign-in-up.service.ts @@ -324,9 +324,20 @@ export class SignInUpService { lastName: string; picture: SignInUpServiceInput['picture']; }) { + const user: Partial = { + email, + firstName, + lastName, + canImpersonate: false, + passwordHash, + }; + if (!this.environmentService.get('IS_MULTIWORKSPACE_ENABLED')) { const workspacesCount = await this.workspaceRepository.count(); + // if the workspace doesn't exist it means it's the first user of the workspace + user.canImpersonate = true; + // let the creation of the first workspace if (workspacesCount > 0) { throw new AuthException( @@ -351,23 +362,18 @@ export class SignInUpService { const workspace = await this.workspaceRepository.save(workspaceToCreate); - const imagePath = await this.uploadPicture(picture, workspace.id); + user.defaultAvatarUrl = await this.uploadPicture(picture, workspace.id); - const userToCreate = this.userRepository.create({ - email: email, - firstName: firstName, - lastName: lastName, - defaultAvatarUrl: imagePath, - canImpersonate: false, - passwordHash, + const userCreated = this.userRepository.create({ + ...user, defaultWorkspace: workspace, }); - const user = await this.userRepository.save(userToCreate); + const newUser = await this.userRepository.save(userCreated); - await this.userWorkspaceService.create(user.id, workspace.id); + await this.userWorkspaceService.create(newUser.id, workspace.id); - await this.activateOnboardingForUser(user, workspace, { + await this.activateOnboardingForUser(newUser, workspace, { firstName, lastName, }); @@ -377,7 +383,7 @@ export class SignInUpService { value: true, }); - return user; + return newUser; } async uploadPicture(