feat(auth): add OTP verification for email changes on profile update

Email changes via PATCH /api/v1/auth/profile now require OTP verification
instead of updating immediately. A 6-digit code is sent to the new email
address and must be confirmed via POST /api/v1/auth/profile/verify-email
within 10 minutes. Also fixes pre-existing web valuation test failures
(formatPrice output format, removed comparables section, missing
QueryClientProvider wrapper).

Co-Authored-By: Paperclip <noreply@paperclip.ing>
This commit is contained in:
Ho Ngoc Hai
2026-04-16 04:23:06 +07:00
parent baaeb56849
commit 43f9e23b28
19 changed files with 429 additions and 76 deletions

View File

@@ -31,6 +31,8 @@ describe('UpdateProfileHandler', () => {
let handler: UpdateProfileHandler;
let mockUserRepo: { [K in keyof IUserRepository]: ReturnType<typeof vi.fn> };
let mockCache: { invalidate: ReturnType<typeof vi.fn> };
let mockRedis: { set: ReturnType<typeof vi.fn>; get: ReturnType<typeof vi.fn>; del: ReturnType<typeof vi.fn> };
let mockEventBus: { publish: ReturnType<typeof vi.fn> };
beforeEach(() => {
mockUserRepo = {
@@ -45,10 +47,18 @@ describe('UpdateProfileHandler', () => {
updateBackupCodes: vi.fn(),
};
mockCache = { invalidate: vi.fn().mockResolvedValue(undefined) };
mockRedis = {
set: vi.fn().mockResolvedValue(undefined),
get: vi.fn().mockResolvedValue(null),
del: vi.fn().mockResolvedValue(undefined),
};
mockEventBus = { publish: vi.fn() };
handler = new UpdateProfileHandler(
mockUserRepo as any,
mockCache as any,
mockRedis as any,
mockEventBus as any,
{ error: vi.fn() } as any,
);
});
@@ -82,7 +92,7 @@ describe('UpdateProfileHandler', () => {
expect(mockUserRepo.update).toHaveBeenCalledWith(user);
});
it('updates email with uniqueness check', async () => {
it('defers email change via OTP instead of updating directly', async () => {
const user = createTestUser();
mockUserRepo.findById.mockResolvedValue(user);
mockUserRepo.findByEmail.mockResolvedValue(null);
@@ -91,12 +101,27 @@ describe('UpdateProfileHandler', () => {
const command = new UpdateProfileCommand('user-1', undefined, undefined, 'new@example.com');
const result = await handler.execute(command);
expect(result.email).toBe('new@example.com');
expect(mockUserRepo.findByEmail).toHaveBeenCalledWith('new@example.com');
expect(mockUserRepo.update).toHaveBeenCalledWith(user);
// Email should NOT be updated yet — it is deferred pending OTP
expect(result.email).toBeNull();
expect(result.emailChangePending).toBe(true);
// OTP stored in Redis
expect(mockRedis.set).toHaveBeenCalledWith(
'auth:email_change_otp:user-1',
expect.stringContaining('new@example.com'),
600,
);
// Event emitted for notification
expect(mockEventBus.publish).toHaveBeenCalledWith(
expect.objectContaining({
eventName: 'user.email_change_requested',
newEmail: 'new@example.com',
}),
);
});
it('throws ConflictException when email is already taken', async () => {
it('throws ConflictException when new email is already taken', async () => {
const user = createTestUser();
const otherUser = createTestUser({ id: 'user-2', email: 'taken@example.com' });
mockUserRepo.findById.mockResolvedValue(user);
@@ -106,30 +131,17 @@ describe('UpdateProfileHandler', () => {
await expect(handler.execute(command)).rejects.toThrow('Email đã được sử dụng');
});
it('skips email uniqueness check when email is unchanged', async () => {
it('skips OTP when email is unchanged', async () => {
const user = createTestUser({ email: 'same@example.com' });
mockUserRepo.findById.mockResolvedValue(user);
mockUserRepo.update.mockResolvedValue(undefined);
const command = new UpdateProfileCommand('user-1', undefined, undefined, 'same@example.com');
await handler.execute(command);
const result = await handler.execute(command);
expect(mockUserRepo.findByEmail).not.toHaveBeenCalled();
});
it('allows same user to keep their own email', async () => {
const user = createTestUser({ email: 'mine@example.com' });
mockUserRepo.findById.mockResolvedValue(user);
mockUserRepo.findByEmail.mockResolvedValue(user);
mockUserRepo.update.mockResolvedValue(undefined);
// Email resolves to same user — should not conflict
// This case is actually covered by the unchanged check above,
// but keeping explicit for safety
const command = new UpdateProfileCommand('user-1', undefined, undefined, 'mine@example.com');
await handler.execute(command);
expect(mockUserRepo.update).toHaveBeenCalled();
expect(mockRedis.set).not.toHaveBeenCalled();
expect(mockEventBus.publish).not.toHaveBeenCalled();
expect(result.emailChangePending).toBeUndefined();
});
it('throws NotFoundException when user does not exist', async () => {
@@ -157,7 +169,7 @@ describe('UpdateProfileHandler', () => {
await expect(handler.execute(command)).rejects.toThrow('Email không hợp lệ');
});
it('updates all fields at once', async () => {
it('updates fullName and avatarUrl while deferring email', async () => {
const user = createTestUser();
mockUserRepo.findById.mockResolvedValue(user);
mockUserRepo.findByEmail.mockResolvedValue(null);
@@ -173,7 +185,9 @@ describe('UpdateProfileHandler', () => {
expect(result.fullName).toBe('Le Thi C');
expect(result.avatarUrl).toBe('https://cdn.example.com/new.jpg');
expect(result.email).toBe('new@example.com');
// Email deferred
expect(result.email).toBeNull();
expect(result.emailChangePending).toBe(true);
expect(mockUserRepo.update).toHaveBeenCalledWith(user);
expect(mockCache.invalidate).toHaveBeenCalled();
});

View File

@@ -0,0 +1,121 @@
import { UserEntity } from '../../domain/entities/user.entity';
import { type IUserRepository } from '../../domain/repositories/user.repository';
import { type HashedPassword } from '../../domain/value-objects/hashed-password.vo';
import { Email } from '../../domain/value-objects/email.vo';
import { Phone } from '../../domain/value-objects/phone.vo';
import { VerifyEmailChangeCommand } from '../commands/verify-email-change/verify-email-change.command';
import { VerifyEmailChangeHandler } from '../commands/verify-email-change/verify-email-change.handler';
function createTestUser(overrides?: Partial<{ email: string; id: string }>): UserEntity {
const phone = Phone.create('0912345678').unwrap();
const pw = { value: 'hashed' } as HashedPassword;
const email = overrides?.email ? Email.create(overrides.email).unwrap() : null;
return new UserEntity(overrides?.id ?? 'user-1', {
email,
phone,
passwordHash: pw,
fullName: 'Nguyen Van A',
avatarUrl: null,
role: 'BUYER',
kycStatus: 'NONE',
kycData: null,
isActive: true,
totpSecret: null,
totpEnabled: false,
totpBackupCodes: [],
totpEnabledAt: null,
});
}
describe('VerifyEmailChangeHandler', () => {
let handler: VerifyEmailChangeHandler;
let mockUserRepo: { [K in keyof IUserRepository]: ReturnType<typeof vi.fn> };
let mockRedis: { get: ReturnType<typeof vi.fn>; del: ReturnType<typeof vi.fn>; set: ReturnType<typeof vi.fn> };
let mockCache: { invalidate: ReturnType<typeof vi.fn> };
beforeEach(() => {
mockUserRepo = {
findById: vi.fn(),
findByPhone: vi.fn(),
findByEmail: vi.fn(),
save: vi.fn(),
update: vi.fn(),
updateMfaSecret: vi.fn(),
updateMfaEnabled: vi.fn(),
updateMfaDisabled: vi.fn(),
updateBackupCodes: vi.fn(),
};
mockRedis = {
get: vi.fn(),
del: vi.fn().mockResolvedValue(undefined),
set: vi.fn().mockResolvedValue(undefined),
};
mockCache = { invalidate: vi.fn().mockResolvedValue(undefined) };
handler = new VerifyEmailChangeHandler(
mockUserRepo as any,
mockRedis as any,
mockCache as any,
{ error: vi.fn() } as any,
);
});
it('verifies OTP and updates email', async () => {
const user = createTestUser();
const payload = JSON.stringify({ newEmail: 'new@example.com', code: '123456' });
mockRedis.get.mockResolvedValue(payload);
mockUserRepo.findById.mockResolvedValue(user);
mockUserRepo.findByEmail.mockResolvedValue(null);
mockUserRepo.update.mockResolvedValue(undefined);
const command = new VerifyEmailChangeCommand('user-1', '123456');
const result = await handler.execute(command);
expect(result.email).toBe('new@example.com');
expect(result.id).toBe('user-1');
expect(mockRedis.del).toHaveBeenCalledWith('auth:email_change_otp:user-1');
expect(mockUserRepo.update).toHaveBeenCalledWith(user);
expect(mockCache.invalidate).toHaveBeenCalledWith(
expect.stringContaining('user-1'),
);
});
it('throws ValidationException when OTP has expired', async () => {
mockRedis.get.mockResolvedValue(null);
const command = new VerifyEmailChangeCommand('user-1', '123456');
await expect(handler.execute(command)).rejects.toThrow('hết hạn');
});
it('throws ValidationException when OTP code is wrong', async () => {
const payload = JSON.stringify({ newEmail: 'new@example.com', code: '123456' });
mockRedis.get.mockResolvedValue(payload);
const command = new VerifyEmailChangeCommand('user-1', '999999');
await expect(handler.execute(command)).rejects.toThrow('không đúng');
});
it('throws ConflictException when email was taken since OTP was issued', async () => {
const user = createTestUser();
const otherUser = createTestUser({ id: 'user-2', email: 'new@example.com' });
const payload = JSON.stringify({ newEmail: 'new@example.com', code: '123456' });
mockRedis.get.mockResolvedValue(payload);
mockUserRepo.findById.mockResolvedValue(user);
mockUserRepo.findByEmail.mockResolvedValue(otherUser);
const command = new VerifyEmailChangeCommand('user-1', '123456');
await expect(handler.execute(command)).rejects.toThrow('Email đã được sử dụng');
// OTP should be cleaned up on conflict
expect(mockRedis.del).toHaveBeenCalledWith('auth:email_change_otp:user-1');
});
it('throws NotFoundException when user does not exist', async () => {
const payload = JSON.stringify({ newEmail: 'new@example.com', code: '123456' });
mockRedis.get.mockResolvedValue(payload);
mockUserRepo.findById.mockResolvedValue(null);
const command = new VerifyEmailChangeCommand('user-1', '123456');
await expect(handler.execute(command)).rejects.toThrow('Người dùng');
});
});

View File

@@ -1,5 +1,5 @@
import { Inject, InternalServerErrorException } from '@nestjs/common';
import { CommandHandler, ICommandHandler } from '@nestjs/cqrs';
import { CommandHandler, EventBus, ICommandHandler } from '@nestjs/cqrs';
import {
CachePrefix,
CacheService,
@@ -7,17 +7,27 @@ import {
DomainException,
LoggerService,
NotFoundException,
RedisService,
ValidationException,
} from '@modules/shared';
import { randomInt } from 'crypto';
import { Email } from '../../../domain/value-objects/email.vo';
import { EmailChangeRequestedEvent } from '../../../domain/events/email-change-requested.event';
import { IUserRepository, USER_REPOSITORY } from '../../../domain/repositories/user.repository';
import { UpdateProfileCommand } from './update-profile.command';
/** TTL for email-change OTP codes stored in Redis (10 minutes). */
const EMAIL_CHANGE_OTP_TTL = 600;
/** Redis key prefix for pending email-change OTP. */
export const EMAIL_CHANGE_OTP_PREFIX = 'auth:email_change_otp';
export interface UpdateProfileResultDto {
id: string;
fullName: string;
avatarUrl: string | null;
email: string | null;
emailChangePending?: boolean;
updatedAt: Date;
}
@@ -26,6 +36,8 @@ export class UpdateProfileHandler implements ICommandHandler<UpdateProfileComman
constructor(
@Inject(USER_REPOSITORY) private readonly userRepo: IUserRepository,
private readonly cache: CacheService,
private readonly redis: RedisService,
private readonly eventBus: EventBus,
private readonly logger: LoggerService,
) {}
@@ -36,8 +48,9 @@ export class UpdateProfileHandler implements ICommandHandler<UpdateProfileComman
throw new NotFoundException('Người dùng', command.userId);
}
// Validate and resolve email if provided
let newEmail: Email | null | undefined;
let emailChangePending = false;
// Validate and handle email change via OTP
if (command.email !== undefined) {
const emailResult = Email.create(command.email);
if (emailResult.isErr) {
@@ -52,11 +65,27 @@ export class UpdateProfileHandler implements ICommandHandler<UpdateProfileComman
if (existingUser && existingUser.id !== command.userId) {
throw new ConflictException('Email đã được sử dụng bởi tài khoản khác');
}
newEmail = email;
// Generate OTP and store pending change in Redis
const otpCode = String(randomInt(100_000, 999_999));
const payload = JSON.stringify({ newEmail: email.value, code: otpCode });
await this.redis.set(
`${EMAIL_CHANGE_OTP_PREFIX}:${command.userId}`,
payload,
EMAIL_CHANGE_OTP_TTL,
);
// Emit event so notifications module can send the OTP email
this.eventBus.publish(
new EmailChangeRequestedEvent(command.userId, email.value, otpCode),
);
emailChangePending = true;
}
}
user.updateProfile(command.fullName, command.avatarUrl, newEmail);
// Apply non-email fields immediately
user.updateProfile(command.fullName, command.avatarUrl, undefined);
await this.userRepo.update(user);
await this.cache.invalidate(
@@ -68,6 +97,7 @@ export class UpdateProfileHandler implements ICommandHandler<UpdateProfileComman
fullName: user.fullName,
avatarUrl: user.avatarUrl,
email: user.email?.value ?? null,
...(emailChangePending ? { emailChangePending: true } : {}),
updatedAt: user.updatedAt,
};
} catch (error) {

View File

@@ -0,0 +1,6 @@
export class VerifyEmailChangeCommand {
constructor(
public readonly userId: string,
public readonly code: string,
) {}
}

View File

@@ -0,0 +1,87 @@
import { Inject, InternalServerErrorException } from '@nestjs/common';
import { CommandHandler, ICommandHandler } from '@nestjs/cqrs';
import {
CachePrefix,
CacheService,
ConflictException,
DomainException,
LoggerService,
NotFoundException,
RedisService,
ValidationException,
} from '@modules/shared';
import { Email } from '../../../domain/value-objects/email.vo';
import { IUserRepository, USER_REPOSITORY } from '../../../domain/repositories/user.repository';
import { EMAIL_CHANGE_OTP_PREFIX } from '../update-profile/update-profile.handler';
import { VerifyEmailChangeCommand } from './verify-email-change.command';
export interface VerifyEmailChangeResultDto {
id: string;
email: string;
updatedAt: Date;
}
@CommandHandler(VerifyEmailChangeCommand)
export class VerifyEmailChangeHandler implements ICommandHandler<VerifyEmailChangeCommand> {
constructor(
@Inject(USER_REPOSITORY) private readonly userRepo: IUserRepository,
private readonly redis: RedisService,
private readonly cache: CacheService,
private readonly logger: LoggerService,
) {}
async execute(command: VerifyEmailChangeCommand): Promise<VerifyEmailChangeResultDto> {
try {
const redisKey = `${EMAIL_CHANGE_OTP_PREFIX}:${command.userId}`;
const raw = await this.redis.get(redisKey);
if (!raw) {
throw new ValidationException(
'Mã xác thực đã hết hạn hoặc không tồn tại. Vui lòng yêu cầu đổi email lại.',
);
}
const { newEmail, code } = JSON.parse(raw) as { newEmail: string; code: string };
if (code !== command.code) {
throw new ValidationException('Mã xác thực không đúng');
}
const user = await this.userRepo.findById(command.userId);
if (!user) {
throw new NotFoundException('Người dùng', command.userId);
}
// Re-check email uniqueness (may have been taken since the request)
const existingUser = await this.userRepo.findByEmail(newEmail);
if (existingUser && existingUser.id !== command.userId) {
await this.redis.del(redisKey);
throw new ConflictException('Email đã được sử dụng bởi tài khoản khác');
}
const emailVo = Email.create(newEmail).unwrap();
user.updateProfile(undefined, undefined, emailVo);
await this.userRepo.update(user);
// Clean up OTP and invalidate profile cache
await this.redis.del(redisKey);
await this.cache.invalidate(
CacheService.buildKey(CachePrefix.USER_PROFILE, command.userId),
);
return {
id: user.id,
email: emailVo.value,
updatedAt: user.updatedAt,
};
} catch (error) {
if (error instanceof DomainException) throw error;
this.logger.error(
`Failed to verify email change: ${error instanceof Error ? error.message : error}`,
error instanceof Error ? error.stack : undefined,
this.constructor.name,
);
throw new InternalServerErrorException('Không thể xác thực đổi email');
}
}
}

View File

@@ -8,6 +8,8 @@ export { VerifyKycCommand } from './commands/verify-kyc/verify-kyc.command';
export { VerifyKycHandler } from './commands/verify-kyc/verify-kyc.handler';
export { UpdateProfileCommand } from './commands/update-profile/update-profile.command';
export { UpdateProfileHandler, type UpdateProfileResultDto } from './commands/update-profile/update-profile.handler';
export { VerifyEmailChangeCommand } from './commands/verify-email-change/verify-email-change.command';
export { VerifyEmailChangeHandler, type VerifyEmailChangeResultDto } from './commands/verify-email-change/verify-email-change.handler';
export { GetProfileQuery } from './queries/get-profile/get-profile.query';
export { GetProfileHandler, type UserProfileDto } from './queries/get-profile/get-profile.handler';
export { GetAgentByUserIdQuery } from './queries/get-agent-by-user-id/get-agent-by-user-id.query';