(breaking change) Allow users with a single workspace to update their email. (#15736)
- Users with a single workspace are allowed to update their email across `core.user` and `workspace_xyz.workspaceMember`. - The latter happens asynchronously (built it like this for non-blocking with multiple workspaces), but since we restrict the email update functionality to a single user, we can also update the email in workspaceMember synchronously - I left asynchronous there to receive feedback on whether we should move to synchronous or not. - Merged main and resolved conflicts to ensure we use the `SettingsPermissionGuard` and the updated `workspace.service.ts` code. One edge-case that I was trying to communicate on Discord: Say that an admin is a member of multiple workspaces. Therefore, they can allow roles with PROFILE_INFORMATION permission to update their email. <p align="center"> <img width="553" height="115" alt="image" src="https://github.com/user-attachments/assets/80382b1f-a9e3-4dac-b606-c2defeb2c330" /> </p> However, since the admin is part of multiple workspaces, he/she cannot even update own email - the field stays disabled, leading to some confusion. <p align="center"> <img width="545" height="255" alt="image" src="https://github.com/user-attachments/assets/5e6d27db-c9a8-4d5e-9ab6-65c77beae5b4" /> </p> However, the workspace can have another member with admin role or some other role that has PROFILE_INFORMATION permission flag. That user will be and should be allowed to update email, so we cannot hide `email` from dropdown options. <p align="center"> <img width="585" height="283" alt="image" src="https://github.com/user-attachments/assets/a670d3ac-cf48-4865-a425-b909093d8420" /> </p> The behavior is fine imo, just a little confusing for members with more than one workspace. I have also tested the flow by signing up to YC workspace with my org google account (twenty.com), then changing email to my personal address. - After changing, I need to login using Google with my personal account to access YC workspace again. - If I login using Google with org google account (twenty.com), a new user account is created. This behavior is consistent with Notion and Linear. Finally, as for the verification of email, the user is asked to verify email while they're logged in, but just in case they logout without verifying, the next login would force them to verify their email in the email/password flow. However, for Social/SSO, they must verify before they logout or else they'd have to contact support for assistance. I have not looked into how to show verification screen while logging in via Social/SSO yet, but if that's something critical for completeness here, I shall revisit it. --------- Co-authored-by: Félix Malfait <felix@twenty.com>
This commit is contained in:
@@ -33,7 +33,6 @@ import { AvailableWorkspacesAndAccessTokensOutput } from 'src/engine/core-module
|
||||
import { GetAuthTokenFromEmailVerificationTokenInput } from 'src/engine/core-modules/auth/dto/get-auth-token-from-email-verification-token.input';
|
||||
import { GetAuthorizationUrlForSSOInput } from 'src/engine/core-modules/auth/dto/get-authorization-url-for-sso.input';
|
||||
import { GetAuthorizationUrlForSSOOutput } from 'src/engine/core-modules/auth/dto/get-authorization-url-for-sso.output';
|
||||
import { GetLoginTokenFromEmailVerificationTokenOutput } from 'src/engine/core-modules/auth/dto/get-login-token-from-email-verification-token.output';
|
||||
import { SignUpOutput } from 'src/engine/core-modules/auth/dto/sign-up.output';
|
||||
import { ResetPasswordService } from 'src/engine/core-modules/auth/services/reset-password.service';
|
||||
import { SignInUpService } from 'src/engine/core-modules/auth/services/sign-in-up.service';
|
||||
@@ -51,6 +50,7 @@ import { CaptchaGuard } from 'src/engine/core-modules/captcha/captcha.guard';
|
||||
import { CaptchaGraphqlApiExceptionFilter } from 'src/engine/core-modules/captcha/filters/captcha-graphql-api-exception.filter';
|
||||
import { WorkspaceDomainsService } from 'src/engine/core-modules/domain/workspace-domains/services/workspace-domains.service';
|
||||
import { EmailVerificationExceptionFilter } from 'src/engine/core-modules/email-verification/email-verification-exception-filter.util';
|
||||
import { EmailVerificationTrigger } from 'src/engine/core-modules/email-verification/email-verification.constants';
|
||||
import { EmailVerificationService } from 'src/engine/core-modules/email-verification/services/email-verification.service';
|
||||
import { PreventNestToAutoLogGraphqlErrorsFilter } from 'src/engine/core-modules/graphql/filters/prevent-nest-to-auto-log-graphql-errors.filter';
|
||||
import { ResolverValidationPipe } from 'src/engine/core-modules/graphql/pipes/resolver-validation.pipe';
|
||||
@@ -76,6 +76,7 @@ import { WorkspaceAuthGuard } from 'src/engine/guards/workspace-auth.guard';
|
||||
import { PermissionFlagType } from 'src/engine/metadata-modules/permissions/constants/permission-flag-type.constants';
|
||||
import { PermissionsService } from 'src/engine/metadata-modules/permissions/permissions.service';
|
||||
import { PermissionsGraphqlApiExceptionFilter } from 'src/engine/metadata-modules/permissions/utils/permissions-graphql-api-exception.filter';
|
||||
import { VerifyEmailAndGetLoginTokenOutput } from 'src/engine/core-modules/auth/dto/verify-email-and-get-login-token.output';
|
||||
|
||||
import { ApiKeyToken } from './dto/api-key-token.dto';
|
||||
import { AuthTokens } from './dto/auth-tokens.dto';
|
||||
@@ -239,9 +240,9 @@ export class AuthResolver {
|
||||
};
|
||||
}
|
||||
|
||||
@Mutation(() => GetLoginTokenFromEmailVerificationTokenOutput)
|
||||
@Mutation(() => VerifyEmailAndGetLoginTokenOutput)
|
||||
@UseGuards(PublicEndpointGuard, NoPermissionGuard)
|
||||
async getLoginTokenFromEmailVerificationToken(
|
||||
async verifyEmailAndGetLoginToken(
|
||||
@Args()
|
||||
getAuthTokenFromEmailVerificationTokenInput: GetAuthTokenFromEmailVerificationTokenInput,
|
||||
@Args('origin') origin: string,
|
||||
@@ -252,19 +253,25 @@ export class AuthResolver {
|
||||
getAuthTokenFromEmailVerificationTokenInput,
|
||||
);
|
||||
|
||||
if (appToken.context && appToken.context.email !== appToken.user.email) {
|
||||
await this.userService.updateEmailFromVerificationToken(
|
||||
appToken.user.id,
|
||||
appToken.context.email,
|
||||
);
|
||||
}
|
||||
|
||||
const user = await this.userService.markEmailAsVerified(appToken.user.id);
|
||||
|
||||
await this.appTokenRepository.remove(appToken);
|
||||
|
||||
const workspace =
|
||||
(await this.workspaceDomainsService.getWorkspaceByOriginOrDefaultWorkspace(
|
||||
origin,
|
||||
)) ??
|
||||
(await this.userWorkspaceService.findFirstWorkspaceByUserId(
|
||||
appToken.user.id,
|
||||
));
|
||||
|
||||
await this.userService.markEmailAsVerified(appToken.user.id);
|
||||
await this.appTokenRepository.remove(appToken);
|
||||
(await this.userWorkspaceService.findFirstWorkspaceByUserId(user.id));
|
||||
|
||||
const loginToken = await this.loginTokenService.generateLoginToken(
|
||||
appToken.user.email,
|
||||
user.email,
|
||||
workspace.id,
|
||||
authProvider,
|
||||
);
|
||||
@@ -277,7 +284,7 @@ export class AuthResolver {
|
||||
|
||||
@Mutation(() => AvailableWorkspacesAndAccessTokensOutput)
|
||||
@UseGuards(PublicEndpointGuard, NoPermissionGuard)
|
||||
async getWorkspaceAgnosticTokenFromEmailVerificationToken(
|
||||
async verifyEmailAndGetWorkspaceAgnosticToken(
|
||||
@Args()
|
||||
getAuthTokenFromEmailVerificationTokenInput: GetAuthTokenFromEmailVerificationTokenInput,
|
||||
@AuthProvider() authProvider: AuthProviderEnum,
|
||||
@@ -287,31 +294,39 @@ export class AuthResolver {
|
||||
getAuthTokenFromEmailVerificationTokenInput,
|
||||
);
|
||||
|
||||
await this.userService.markEmailAsVerified(appToken.user.id);
|
||||
if (appToken.context && appToken.context.email !== appToken.user.email) {
|
||||
await this.userService.updateEmailFromVerificationToken(
|
||||
appToken.user.id,
|
||||
appToken.context.email,
|
||||
);
|
||||
}
|
||||
|
||||
const user = await this.userService.markEmailAsVerified(appToken.user.id);
|
||||
|
||||
await this.appTokenRepository.remove(appToken);
|
||||
|
||||
const availableWorkspaces =
|
||||
await this.userWorkspaceService.findAvailableWorkspacesByEmail(
|
||||
appToken.user.email,
|
||||
user.email,
|
||||
);
|
||||
|
||||
return {
|
||||
availableWorkspaces:
|
||||
await this.userWorkspaceService.setLoginTokenToAvailableWorkspacesWhenAuthProviderMatch(
|
||||
availableWorkspaces,
|
||||
appToken.user,
|
||||
user,
|
||||
authProvider,
|
||||
),
|
||||
tokens: {
|
||||
accessOrWorkspaceAgnosticToken:
|
||||
await this.workspaceAgnosticTokenService.generateWorkspaceAgnosticToken(
|
||||
{
|
||||
userId: appToken.user.id,
|
||||
userId: user.id,
|
||||
authProvider: AuthProviderEnum.Password,
|
||||
},
|
||||
),
|
||||
refreshToken: await this.refreshTokenService.generateRefreshToken({
|
||||
userId: appToken.user.id,
|
||||
userId: user.id,
|
||||
authProvider: AuthProviderEnum.Password,
|
||||
targetedTokenType: JwtTokenTypeEnum.WORKSPACE_AGNOSTIC,
|
||||
}),
|
||||
@@ -377,13 +392,14 @@ export class AuthResolver {
|
||||
user.email,
|
||||
);
|
||||
|
||||
await this.emailVerificationService.sendVerificationEmail(
|
||||
user.id,
|
||||
user.email,
|
||||
undefined,
|
||||
signUpInput.locale ?? SOURCE_LOCALE,
|
||||
signUpInput.verifyEmailRedirectPath,
|
||||
);
|
||||
await this.emailVerificationService.sendVerificationEmail({
|
||||
userId: user.id,
|
||||
email: user.email,
|
||||
workspace: undefined,
|
||||
locale: signUpInput.locale ?? SOURCE_LOCALE,
|
||||
verifyEmailRedirectPath: signUpInput.verifyEmailRedirectPath,
|
||||
verificationTrigger: EmailVerificationTrigger.SIGN_UP,
|
||||
});
|
||||
|
||||
return {
|
||||
availableWorkspaces:
|
||||
@@ -459,13 +475,14 @@ export class AuthResolver {
|
||||
},
|
||||
});
|
||||
|
||||
await this.emailVerificationService.sendVerificationEmail(
|
||||
user.id,
|
||||
user.email,
|
||||
await this.emailVerificationService.sendVerificationEmail({
|
||||
userId: user.id,
|
||||
email: user.email,
|
||||
workspace,
|
||||
signUpInput.locale ?? SOURCE_LOCALE,
|
||||
signUpInput.verifyEmailRedirectPath,
|
||||
);
|
||||
locale: signUpInput.locale ?? SOURCE_LOCALE,
|
||||
verifyEmailRedirectPath: signUpInput.verifyEmailRedirectPath,
|
||||
verificationTrigger: EmailVerificationTrigger.SIGN_UP,
|
||||
});
|
||||
|
||||
const loginToken = await this.loginTokenService.generateLoginToken(
|
||||
user.email,
|
||||
|
||||
+2
-2
@@ -4,8 +4,8 @@ import { WorkspaceUrlsDTO } from 'src/engine/core-modules/workspace/dtos/workspa
|
||||
|
||||
import { AuthToken } from './auth-token.dto';
|
||||
|
||||
@ObjectType('GetLoginTokenFromEmailVerificationTokenOutput')
|
||||
export class GetLoginTokenFromEmailVerificationTokenOutput {
|
||||
@ObjectType('VerifyEmailAndGetLoginTokenOutput')
|
||||
export class VerifyEmailAndGetLoginTokenOutput {
|
||||
@Field(() => AuthToken)
|
||||
loginToken: AuthToken;
|
||||
|
||||
+2
@@ -142,6 +142,7 @@ export class WorkspaceDomainsService {
|
||||
return {
|
||||
subdomain: this.twentyConfigService.get('DEFAULT_SUBDOMAIN'),
|
||||
customDomain: null,
|
||||
isCustomDomainEnabled: false,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -149,6 +150,7 @@ export class WorkspaceDomainsService {
|
||||
return {
|
||||
subdomain: workspace.subdomain,
|
||||
customDomain: null,
|
||||
isCustomDomainEnabled: false,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
+4
@@ -0,0 +1,4 @@
|
||||
export enum EmailVerificationTrigger {
|
||||
SIGN_UP = 'SIGN_UP',
|
||||
EMAIL_UPDATE = 'EMAIL_UPDATE',
|
||||
}
|
||||
-2
@@ -11,14 +11,12 @@ import { EmailModule } from 'src/engine/core-modules/email/email.module';
|
||||
import { TwentyConfigModule } from 'src/engine/core-modules/twenty-config/twenty-config.module';
|
||||
import { UserWorkspaceModule } from 'src/engine/core-modules/user-workspace/user-workspace.module';
|
||||
import { UserEntity } from 'src/engine/core-modules/user/user.entity';
|
||||
import { UserModule } from 'src/engine/core-modules/user/user.module';
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
TypeOrmModule.forFeature([AppTokenEntity, UserEntity]),
|
||||
EmailModule,
|
||||
TwentyConfigModule,
|
||||
UserModule,
|
||||
UserWorkspaceModule,
|
||||
WorkspaceDomainsModule,
|
||||
DomainServerConfigModule,
|
||||
|
||||
+41
-13
@@ -8,7 +8,7 @@ import ms from 'ms';
|
||||
import { SendEmailVerificationLinkEmail } from 'twenty-emails';
|
||||
import { type APP_LOCALES } from 'twenty-shared/translations';
|
||||
import { AppPath } from 'twenty-shared/types';
|
||||
import { isDefined } from 'twenty-shared/utils';
|
||||
import { assertIsDefinedOrThrow, isDefined } from 'twenty-shared/utils';
|
||||
import { Repository } from 'typeorm';
|
||||
|
||||
import {
|
||||
@@ -19,6 +19,7 @@ import { EmailVerificationTokenService } from 'src/engine/core-modules/auth/toke
|
||||
import { DomainServerConfigService } from 'src/engine/core-modules/domain/domain-server-config/services/domain-server-config.service';
|
||||
import { WorkspaceDomainsService } from 'src/engine/core-modules/domain/workspace-domains/services/workspace-domains.service';
|
||||
import { WorkspaceDomainConfig } from 'src/engine/core-modules/domain/workspace-domains/types/workspace-domain-config.type';
|
||||
import { EmailVerificationTrigger } from 'src/engine/core-modules/email-verification/email-verification.constants';
|
||||
import {
|
||||
EmailVerificationException,
|
||||
EmailVerificationExceptionCode,
|
||||
@@ -26,29 +27,38 @@ import {
|
||||
import { EmailService } from 'src/engine/core-modules/email/email.service';
|
||||
import { I18nService } from 'src/engine/core-modules/i18n/i18n.service';
|
||||
import { TwentyConfigService } from 'src/engine/core-modules/twenty-config/twenty-config.service';
|
||||
import { UserService } from 'src/engine/core-modules/user/services/user.service';
|
||||
import { UserEntity } from 'src/engine/core-modules/user/user.entity';
|
||||
|
||||
@Injectable()
|
||||
export class EmailVerificationService {
|
||||
constructor(
|
||||
@InjectRepository(AppTokenEntity)
|
||||
private readonly appTokenRepository: Repository<AppTokenEntity>,
|
||||
@InjectRepository(UserEntity)
|
||||
private readonly userRepository: Repository<UserEntity>,
|
||||
private readonly workspaceDomainsService: WorkspaceDomainsService,
|
||||
private readonly domainsServerConfigService: DomainServerConfigService,
|
||||
private readonly emailService: EmailService,
|
||||
private readonly twentyConfigService: TwentyConfigService,
|
||||
private readonly userService: UserService,
|
||||
private readonly emailVerificationTokenService: EmailVerificationTokenService,
|
||||
private readonly i18nService: I18nService,
|
||||
) {}
|
||||
|
||||
async sendVerificationEmail(
|
||||
userId: string,
|
||||
email: string,
|
||||
workspace: WorkspaceDomainConfig | undefined,
|
||||
locale: keyof typeof APP_LOCALES,
|
||||
verifyEmailRedirectPath?: string,
|
||||
) {
|
||||
async sendVerificationEmail({
|
||||
userId,
|
||||
email,
|
||||
workspace,
|
||||
locale,
|
||||
verifyEmailRedirectPath,
|
||||
verificationTrigger = EmailVerificationTrigger.SIGN_UP,
|
||||
}: {
|
||||
userId: string;
|
||||
email: string;
|
||||
workspace: WorkspaceDomainConfig | undefined;
|
||||
locale: keyof typeof APP_LOCALES;
|
||||
verifyEmailRedirectPath?: string;
|
||||
verificationTrigger?: EmailVerificationTrigger;
|
||||
}) {
|
||||
if (!this.twentyConfigService.get('IS_EMAIL_VERIFICATION_REQUIRED')) {
|
||||
return { success: false };
|
||||
}
|
||||
@@ -78,6 +88,8 @@ export class EmailVerificationService {
|
||||
const emailData = {
|
||||
link: verificationLink.toString(),
|
||||
locale,
|
||||
isEmailUpdate:
|
||||
verificationTrigger === EmailVerificationTrigger.EMAIL_UPDATE,
|
||||
};
|
||||
|
||||
const emailTemplate = SendEmailVerificationLinkEmail(emailData);
|
||||
@@ -87,7 +99,10 @@ export class EmailVerificationService {
|
||||
plainText: true,
|
||||
});
|
||||
|
||||
const emailVerificationMsg = msg`Welcome to Twenty: Please Confirm Your Email`;
|
||||
const emailVerificationMsg =
|
||||
verificationTrigger === EmailVerificationTrigger.EMAIL_UPDATE
|
||||
? msg`Please confirm your updated email`
|
||||
: msg`Welcome to Twenty: Please Confirm Your Email`;
|
||||
const i18n = this.i18nService.getI18nInstance(locale);
|
||||
const subject = i18n._(emailVerificationMsg);
|
||||
|
||||
@@ -116,7 +131,14 @@ export class EmailVerificationService {
|
||||
);
|
||||
}
|
||||
|
||||
const user = await this.userService.findUserByEmailOrThrow(email);
|
||||
// TODO: Remove the dependency on querying user altogether when the endpoint is authenticated.
|
||||
const user = await this.userRepository.findOne({
|
||||
where: {
|
||||
email,
|
||||
},
|
||||
});
|
||||
|
||||
assertIsDefinedOrThrow(user);
|
||||
|
||||
if (user.isEmailVerified) {
|
||||
throw new EmailVerificationException(
|
||||
@@ -149,7 +171,13 @@ export class EmailVerificationService {
|
||||
await this.appTokenRepository.delete(existingToken.id);
|
||||
}
|
||||
|
||||
await this.sendVerificationEmail(user.id, email, workspace, locale);
|
||||
await this.sendVerificationEmail({
|
||||
userId: user.id,
|
||||
email,
|
||||
workspace,
|
||||
locale,
|
||||
verificationTrigger: EmailVerificationTrigger.SIGN_UP,
|
||||
});
|
||||
|
||||
return { success: true };
|
||||
}
|
||||
|
||||
@@ -12,6 +12,7 @@ import { StripeModule } from 'src/engine/core-modules/billing/stripe/stripe.modu
|
||||
import { EmailSenderJob } from 'src/engine/core-modules/email/email-sender.job';
|
||||
import { EmailModule } from 'src/engine/core-modules/email/email.module';
|
||||
import { UserWorkspaceModule } from 'src/engine/core-modules/user-workspace/user-workspace.module';
|
||||
import { UpdateWorkspaceMemberEmailJob } from 'src/engine/core-modules/user/jobs/update-workspace-member-email.job';
|
||||
import { UserVarsModule } from 'src/engine/core-modules/user/user-vars/user-vars.module';
|
||||
import { UserModule } from 'src/engine/core-modules/user/user.module';
|
||||
import { WebhookJobModule } from 'src/engine/core-modules/webhook/jobs/webhook-job.module';
|
||||
@@ -74,6 +75,7 @@ import { WorkflowModule } from 'src/modules/workflow/workflow.module';
|
||||
UpdateSubscriptionQuantityJob,
|
||||
HandleWorkspaceMemberDeletedJob,
|
||||
CleanWorkspaceDeletionWarningUserVarsJob,
|
||||
UpdateWorkspaceMemberEmailJob,
|
||||
],
|
||||
})
|
||||
export class JobsModule {
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
import { ArgsType, Field } from '@nestjs/graphql';
|
||||
|
||||
import { IsEmail, IsNotEmpty, IsOptional, IsString } from 'class-validator';
|
||||
|
||||
@ArgsType()
|
||||
export class UpdateUserEmailInput {
|
||||
@Field(() => String)
|
||||
@IsNotEmpty()
|
||||
@IsEmail()
|
||||
newEmail: string;
|
||||
|
||||
@Field({ nullable: true })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
verifyEmailRedirectPath?: string;
|
||||
}
|
||||
+44
@@ -0,0 +1,44 @@
|
||||
import { Logger, Scope } from '@nestjs/common';
|
||||
|
||||
import { Process } from 'src/engine/core-modules/message-queue/decorators/process.decorator';
|
||||
import { Processor } from 'src/engine/core-modules/message-queue/decorators/processor.decorator';
|
||||
import { MessageQueue } from 'src/engine/core-modules/message-queue/message-queue.constants';
|
||||
import { UserWorkspaceService } from 'src/engine/core-modules/user-workspace/user-workspace.service';
|
||||
import { TwentyORMGlobalManager } from 'src/engine/twenty-orm/twenty-orm-global.manager';
|
||||
import { WorkspaceMemberWorkspaceEntity } from 'src/modules/workspace-member/standard-objects/workspace-member.workspace-entity';
|
||||
|
||||
export type UpdateWorkspaceMemberEmailJobData = {
|
||||
userId: string;
|
||||
email: string;
|
||||
};
|
||||
|
||||
@Processor({
|
||||
queueName: MessageQueue.workspaceQueue,
|
||||
scope: Scope.REQUEST,
|
||||
})
|
||||
export class UpdateWorkspaceMemberEmailJob {
|
||||
private readonly logger = new Logger(UpdateWorkspaceMemberEmailJob.name);
|
||||
|
||||
constructor(
|
||||
private readonly userWorkspaceService: UserWorkspaceService,
|
||||
private readonly twentyORMGlobalManager: TwentyORMGlobalManager,
|
||||
) {}
|
||||
|
||||
@Process(UpdateWorkspaceMemberEmailJob.name)
|
||||
async handle({
|
||||
userId,
|
||||
email,
|
||||
}: UpdateWorkspaceMemberEmailJobData): Promise<void> {
|
||||
const workspace =
|
||||
await this.userWorkspaceService.findFirstWorkspaceByUserId(userId);
|
||||
|
||||
const workspaceMemberRepository =
|
||||
await this.twentyORMGlobalManager.getRepositoryForWorkspace<WorkspaceMemberWorkspaceEntity>(
|
||||
workspace.id,
|
||||
'workspaceMember',
|
||||
{ shouldBypassPermissionChecks: true },
|
||||
);
|
||||
|
||||
await workspaceMemberRepository.update({ userId }, { userEmail: email });
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,9 @@ import { type Repository, type UpdateResult } from 'typeorm';
|
||||
|
||||
import { ApplicationService } from 'src/engine/core-modules/application/application.service';
|
||||
import { AuthException } from 'src/engine/core-modules/auth/auth.exception';
|
||||
import { WorkspaceDomainsService } from 'src/engine/core-modules/domain/workspace-domains/services/workspace-domains.service';
|
||||
import { EmailVerificationService } from 'src/engine/core-modules/email-verification/services/email-verification.service';
|
||||
import { MessageQueue } from 'src/engine/core-modules/message-queue/message-queue.constants';
|
||||
import { type UserWorkspaceEntity } from 'src/engine/core-modules/user-workspace/user-workspace.entity';
|
||||
import { UserWorkspaceService } from 'src/engine/core-modules/user-workspace/user-workspace.service';
|
||||
import { UserService } from 'src/engine/core-modules/user/services/user.service';
|
||||
@@ -51,6 +54,21 @@ describe('UserService', () => {
|
||||
provide: WorkspaceService,
|
||||
useValue: { deleteWorkspace: jest.fn() },
|
||||
},
|
||||
{
|
||||
provide: WorkspaceDomainsService,
|
||||
useValue: {
|
||||
getSubdomainAndCustomDomainFromWorkspaceFallbackOnDefaultSubdomain:
|
||||
jest.fn(),
|
||||
},
|
||||
},
|
||||
{
|
||||
provide: EmailVerificationService,
|
||||
useValue: { sendVerificationEmail: jest.fn() },
|
||||
},
|
||||
{
|
||||
provide: `MESSAGE_QUEUE_${MessageQueue.workspaceQueue}`,
|
||||
useValue: { add: jest.fn() },
|
||||
},
|
||||
{
|
||||
provide: TwentyORMGlobalManager,
|
||||
useValue: {
|
||||
|
||||
@@ -4,6 +4,7 @@ import assert from 'assert';
|
||||
|
||||
import { msg } from '@lingui/core/macro';
|
||||
import { TypeOrmQueryService } from '@ptc-org/nestjs-query-typeorm';
|
||||
import { SOURCE_LOCALE } from 'twenty-shared/translations';
|
||||
import { assertIsDefinedOrThrow, isDefined } from 'twenty-shared/utils';
|
||||
import { isWorkspaceActiveOrSuspended } from 'twenty-shared/workspace';
|
||||
import { type QueryRunner, IsNull, Not, Repository } from 'typeorm';
|
||||
@@ -12,9 +13,21 @@ import {
|
||||
AuthException,
|
||||
AuthExceptionCode,
|
||||
} from 'src/engine/core-modules/auth/auth.exception';
|
||||
import { WorkspaceDomainsService } from 'src/engine/core-modules/domain/workspace-domains/services/workspace-domains.service';
|
||||
import { EmailVerificationTrigger } from 'src/engine/core-modules/email-verification/email-verification.constants';
|
||||
import { EmailVerificationService } from 'src/engine/core-modules/email-verification/services/email-verification.service';
|
||||
import { UserInputError } from 'src/engine/core-modules/graphql/utils/graphql-errors.util';
|
||||
import { InjectMessageQueue } from 'src/engine/core-modules/message-queue/decorators/message-queue.decorator';
|
||||
import { MessageQueue } from 'src/engine/core-modules/message-queue/message-queue.constants';
|
||||
import { MessageQueueService } from 'src/engine/core-modules/message-queue/services/message-queue.service';
|
||||
import { UserWorkspaceEntity } from 'src/engine/core-modules/user-workspace/user-workspace.entity';
|
||||
import { UserWorkspaceService } from 'src/engine/core-modules/user-workspace/user-workspace.service';
|
||||
import {
|
||||
UpdateWorkspaceMemberEmailJob,
|
||||
UpdateWorkspaceMemberEmailJobData,
|
||||
} from 'src/engine/core-modules/user/jobs/update-workspace-member-email.job';
|
||||
import { UserEntity } from 'src/engine/core-modules/user/user.entity';
|
||||
import { UserExceptionCode } from 'src/engine/core-modules/user/user.exception';
|
||||
import { userValidator } from 'src/engine/core-modules/user/user.validate';
|
||||
import { WorkspaceService } from 'src/engine/core-modules/workspace/services/workspace.service';
|
||||
import { WorkspaceEntity } from 'src/engine/core-modules/workspace/workspace.entity';
|
||||
@@ -32,10 +45,14 @@ export class UserService extends TypeOrmQueryService<UserEntity> {
|
||||
constructor(
|
||||
@InjectRepository(UserEntity)
|
||||
private readonly userRepository: Repository<UserEntity>,
|
||||
private readonly workspaceDomainsService: WorkspaceDomainsService,
|
||||
private readonly emailVerificationService: EmailVerificationService,
|
||||
private readonly workspaceService: WorkspaceService,
|
||||
private readonly twentyORMGlobalManager: TwentyORMGlobalManager,
|
||||
private readonly userRoleService: UserRoleService,
|
||||
private readonly userWorkspaceService: UserWorkspaceService,
|
||||
@InjectMessageQueue(MessageQueue.workspaceQueue)
|
||||
private readonly workspaceQueueService: MessageQueueService,
|
||||
) {
|
||||
super(userRepository);
|
||||
}
|
||||
@@ -284,4 +301,94 @@ export class UserService extends TypeOrmQueryService<UserEntity> {
|
||||
? await queryRunner.manager.save(UserEntity, user)
|
||||
: await this.userRepository.save(user);
|
||||
}
|
||||
|
||||
async updateEmailFromVerificationToken(userId: string, email: string) {
|
||||
const user = await this.findUserByIdOrThrow(userId);
|
||||
|
||||
user.email = email;
|
||||
|
||||
const updatedUser = await this.userRepository.save(user);
|
||||
|
||||
await this.enqueueWorkspaceMemberEmailUpdate({
|
||||
userId: user.id,
|
||||
email,
|
||||
});
|
||||
|
||||
return updatedUser;
|
||||
}
|
||||
|
||||
async updateUserEmail({
|
||||
user,
|
||||
workspace,
|
||||
newEmail,
|
||||
verifyEmailRedirectPath,
|
||||
}: {
|
||||
user: UserEntity;
|
||||
workspace: WorkspaceEntity;
|
||||
newEmail: string;
|
||||
verifyEmailRedirectPath?: string;
|
||||
}): Promise<void> {
|
||||
const normalizedEmail = newEmail.trim().toLowerCase();
|
||||
|
||||
if (normalizedEmail === user.email) {
|
||||
throw new UserInputError(
|
||||
'New email must be different from current email',
|
||||
{
|
||||
subCode: UserExceptionCode.EMAIL_UNCHANGED,
|
||||
userFriendlyMessage: msg`New email must be different from current email`,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
const userWorkspaceCount =
|
||||
await this.userWorkspaceService.countUserWorkspaces(user.id);
|
||||
|
||||
if (userWorkspaceCount > 1) {
|
||||
throw new UserInputError(
|
||||
'Email updates are available only for users with a single workspace',
|
||||
{
|
||||
subCode:
|
||||
UserExceptionCode.EMAIL_UPDATE_RESTRICTED_TO_SINGLE_WORKSPACE,
|
||||
userFriendlyMessage: msg`Email can only be updated when you belong to a single workspace.`,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
const existingUser = await this.userRepository.findOne({
|
||||
where: { email: normalizedEmail },
|
||||
});
|
||||
|
||||
if (existingUser && existingUser.id !== user.id) {
|
||||
throw new UserInputError('Email already in use', {
|
||||
subCode: UserExceptionCode.EMAIL_ALREADY_IN_USE,
|
||||
userFriendlyMessage: msg`Email already in use`,
|
||||
});
|
||||
}
|
||||
|
||||
const workspaceDomainConfig =
|
||||
this.workspaceDomainsService.getSubdomainAndCustomDomainFromWorkspaceFallbackOnDefaultSubdomain(
|
||||
workspace,
|
||||
);
|
||||
|
||||
await this.emailVerificationService.sendVerificationEmail({
|
||||
userId: user.id,
|
||||
email: normalizedEmail,
|
||||
workspace: workspaceDomainConfig,
|
||||
locale: user.locale || SOURCE_LOCALE,
|
||||
verifyEmailRedirectPath,
|
||||
verificationTrigger: EmailVerificationTrigger.EMAIL_UPDATE,
|
||||
});
|
||||
}
|
||||
|
||||
async enqueueWorkspaceMemberEmailUpdate(
|
||||
data: UpdateWorkspaceMemberEmailJobData,
|
||||
) {
|
||||
await this.workspaceQueueService.add<UpdateWorkspaceMemberEmailJobData>(
|
||||
UpdateWorkspaceMemberEmailJob.name,
|
||||
data,
|
||||
{
|
||||
retryLimit: 2,
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { Field, ObjectType, registerEnumType } from '@nestjs/graphql';
|
||||
|
||||
import { IDField } from '@ptc-org/nestjs-query-graphql';
|
||||
import { SOURCE_LOCALE } from 'twenty-shared/translations';
|
||||
import { APP_LOCALES, SOURCE_LOCALE } from 'twenty-shared/translations';
|
||||
import {
|
||||
BeforeInsert,
|
||||
BeforeUpdate,
|
||||
@@ -95,8 +95,8 @@ export class UserEntity {
|
||||
deletedAt: Date;
|
||||
|
||||
@Field(() => String, { nullable: false })
|
||||
@Column({ nullable: false, default: SOURCE_LOCALE })
|
||||
locale: string;
|
||||
@Column({ nullable: false, default: SOURCE_LOCALE, type: 'varchar' })
|
||||
locale: keyof typeof APP_LOCALES;
|
||||
|
||||
@OneToMany(() => AppTokenEntity, (appToken) => appToken.user, {
|
||||
cascade: true,
|
||||
|
||||
@@ -4,4 +4,7 @@ export class UserException extends CustomException<UserExceptionCode> {}
|
||||
|
||||
export enum UserExceptionCode {
|
||||
USER_NOT_FOUND = 'USER_NOT_FOUND',
|
||||
EMAIL_ALREADY_IN_USE = 'EMAIL_ALREADY_IN_USE',
|
||||
EMAIL_UNCHANGED = 'EMAIL_UNCHANGED',
|
||||
EMAIL_UPDATE_RESTRICTED_TO_SINGLE_WORKSPACE = 'EMAIL_UPDATE_RESTRICTED_TO_SINGLE_WORKSPACE',
|
||||
}
|
||||
|
||||
@@ -22,6 +22,8 @@ import { DataSourceModule } from 'src/engine/metadata-modules/data-source/data-s
|
||||
import { ObjectMetadataEntity } from 'src/engine/metadata-modules/object-metadata/object-metadata.entity';
|
||||
import { PermissionsModule } from 'src/engine/metadata-modules/permissions/permissions.module';
|
||||
import { UserRoleModule } from 'src/engine/metadata-modules/user-role/user-role.module';
|
||||
import { WorkspaceDomainsModule } from 'src/engine/core-modules/domain/workspace-domains/workspace-domains.module';
|
||||
import { EmailVerificationModule } from 'src/engine/core-modules/email-verification/email-verification.module';
|
||||
|
||||
import { userAutoResolverOpts } from './user.auto-resolver-opts';
|
||||
|
||||
@@ -49,6 +51,8 @@ import { UserService } from './services/user.service';
|
||||
UserRoleModule,
|
||||
FeatureFlagModule,
|
||||
PermissionsModule,
|
||||
EmailVerificationModule,
|
||||
WorkspaceDomainsModule,
|
||||
],
|
||||
exports: [UserService, WorkspaceMemberTranspiler],
|
||||
providers: [UserService, UserResolver, WorkspaceMemberTranspiler],
|
||||
|
||||
@@ -38,6 +38,7 @@ import { buildTwoFactorAuthenticationMethodSummary } from 'src/engine/core-modul
|
||||
import { UserWorkspaceEntity } from 'src/engine/core-modules/user-workspace/user-workspace.entity';
|
||||
import { UserWorkspaceService } from 'src/engine/core-modules/user-workspace/user-workspace.service';
|
||||
import { DeletedWorkspaceMemberDTO } from 'src/engine/core-modules/user/dtos/deleted-workspace-member.dto';
|
||||
import { UpdateUserEmailInput } from 'src/engine/core-modules/user/dtos/update-user-email.input';
|
||||
import { WorkspaceMemberDTO } from 'src/engine/core-modules/user/dtos/workspace-member.dto';
|
||||
import { UserService } from 'src/engine/core-modules/user/services/user.service';
|
||||
import {
|
||||
@@ -56,6 +57,7 @@ import { AuthUser } from 'src/engine/decorators/auth/auth-user.decorator';
|
||||
import { AuthWorkspace } from 'src/engine/decorators/auth/auth-workspace.decorator';
|
||||
import { CustomPermissionGuard } from 'src/engine/guards/custom-permission.guard';
|
||||
import { NoPermissionGuard } from 'src/engine/guards/no-permission.guard';
|
||||
import { SettingsPermissionGuard } from 'src/engine/guards/settings-permission.guard';
|
||||
import { UserAuthGuard } from 'src/engine/guards/user-auth.guard';
|
||||
import { WorkspaceAuthGuard } from 'src/engine/guards/workspace-auth.guard';
|
||||
import { PermissionFlagType } from 'src/engine/metadata-modules/permissions/constants/permission-flag-type.constants';
|
||||
@@ -97,7 +99,6 @@ export class UserResolver {
|
||||
private readonly userWorkspaceRepository: Repository<UserWorkspaceEntity>,
|
||||
private readonly userRoleService: UserRoleService,
|
||||
private readonly permissionsService: PermissionsService,
|
||||
|
||||
private readonly workspaceMemberTranspiler: WorkspaceMemberTranspiler,
|
||||
private readonly userWorkspaceService: UserWorkspaceService,
|
||||
private readonly twentyORMGlobalManager: TwentyORMGlobalManager,
|
||||
@@ -512,4 +513,34 @@ export class UserResolver {
|
||||
authProvider,
|
||||
);
|
||||
}
|
||||
|
||||
@Mutation(() => Boolean)
|
||||
@UseGuards(
|
||||
UserAuthGuard,
|
||||
WorkspaceAuthGuard,
|
||||
SettingsPermissionGuard(PermissionFlagType.PROFILE_INFORMATION),
|
||||
)
|
||||
async updateUserEmail(
|
||||
@Args() { newEmail, verifyEmailRedirectPath }: UpdateUserEmailInput,
|
||||
@AuthUser() user: UserEntity,
|
||||
@AuthWorkspace() workspace: WorkspaceEntity,
|
||||
) {
|
||||
const editableFields = workspace.editableProfileFields || [];
|
||||
|
||||
if (!editableFields.includes('email')) {
|
||||
throw new PermissionsException(
|
||||
PermissionsExceptionMessage.PERMISSION_DENIED,
|
||||
PermissionsExceptionCode.PERMISSION_DENIED,
|
||||
);
|
||||
}
|
||||
|
||||
await this.userService.updateUserEmail({
|
||||
user,
|
||||
workspace,
|
||||
newEmail,
|
||||
verifyEmailRedirectPath,
|
||||
});
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
+7
@@ -1,6 +1,7 @@
|
||||
import { Field, InputType } from '@nestjs/graphql';
|
||||
|
||||
import {
|
||||
IsArray,
|
||||
IsBoolean,
|
||||
IsInt,
|
||||
IsOptional,
|
||||
@@ -102,4 +103,10 @@ export class UpdateWorkspaceInput {
|
||||
@IsString()
|
||||
@IsOptional()
|
||||
routerModel?: string;
|
||||
|
||||
@Field(() => [String], { nullable: true })
|
||||
@IsArray()
|
||||
@IsString({ each: true })
|
||||
@IsOptional()
|
||||
editableProfileFields?: string[];
|
||||
}
|
||||
|
||||
@@ -69,6 +69,7 @@ export class WorkspaceService extends TypeOrmQueryService<WorkspaceEntity> {
|
||||
isGoogleAuthEnabled: PermissionFlagType.SECURITY,
|
||||
isMicrosoftAuthEnabled: PermissionFlagType.SECURITY,
|
||||
isPasswordAuthEnabled: PermissionFlagType.SECURITY,
|
||||
editableProfileFields: PermissionFlagType.SECURITY,
|
||||
isTwoFactorAuthenticationEnforced: PermissionFlagType.SECURITY,
|
||||
defaultRoleId: PermissionFlagType.ROLES,
|
||||
routerModel: PermissionFlagType.WORKSPACE,
|
||||
|
||||
@@ -262,6 +262,15 @@ export class WorkspaceEntity {
|
||||
@Column({ default: false })
|
||||
isCustomDomainEnabled: boolean;
|
||||
|
||||
@Field(() => [String], { nullable: true })
|
||||
@Column({
|
||||
type: 'varchar',
|
||||
array: true,
|
||||
nullable: true,
|
||||
default: '{email,profilePicture,firstName,lastName}',
|
||||
})
|
||||
editableProfileFields: string[] | null;
|
||||
|
||||
// TODO: set as non nullable
|
||||
@Column({ nullable: true, type: 'uuid' })
|
||||
defaultRoleId: string | null;
|
||||
|
||||
Reference in New Issue
Block a user