driver to user id
This commit is contained in:
218
core/identity/application/use-cases/SignupSponsorUseCase.test.ts
Normal file
218
core/identity/application/use-cases/SignupSponsorUseCase.test.ts
Normal file
@@ -0,0 +1,218 @@
|
||||
import { describe, it, expect, vi, type Mock } from 'vitest';
|
||||
import { SignupSponsorUseCase } from './SignupSponsorUseCase';
|
||||
import { EmailAddress } from '../../domain/value-objects/EmailAddress';
|
||||
import { UserId } from '../../domain/value-objects/UserId';
|
||||
import { User } from '../../domain/entities/User';
|
||||
import type { IAuthRepository } from '../../domain/repositories/IAuthRepository';
|
||||
import type { ICompanyRepository } from '../../domain/repositories/ICompanyRepository';
|
||||
import type { IPasswordHashingService } from '../../domain/services/PasswordHashingService';
|
||||
import type { Logger, UseCaseOutputPort } from '@core/shared/application';
|
||||
|
||||
vi.mock('../../domain/value-objects/PasswordHash', () => ({
|
||||
PasswordHash: {
|
||||
fromHash: (hash: string) => ({ value: hash }),
|
||||
},
|
||||
}));
|
||||
|
||||
type SignupSponsorOutput = unknown;
|
||||
|
||||
describe('SignupSponsorUseCase', () => {
|
||||
let authRepo: {
|
||||
findByEmail: Mock;
|
||||
save: Mock;
|
||||
};
|
||||
let companyRepo: {
|
||||
create: Mock;
|
||||
save: Mock;
|
||||
delete: Mock;
|
||||
};
|
||||
let passwordService: {
|
||||
hash: Mock;
|
||||
};
|
||||
let logger: Logger;
|
||||
let output: UseCaseOutputPort<SignupSponsorOutput> & { present: Mock };
|
||||
let useCase: SignupSponsorUseCase;
|
||||
|
||||
beforeEach(() => {
|
||||
authRepo = {
|
||||
findByEmail: vi.fn(),
|
||||
save: vi.fn(),
|
||||
};
|
||||
companyRepo = {
|
||||
create: vi.fn(),
|
||||
save: vi.fn(),
|
||||
delete: vi.fn(),
|
||||
};
|
||||
passwordService = {
|
||||
hash: vi.fn(),
|
||||
};
|
||||
logger = {
|
||||
debug: vi.fn(),
|
||||
info: vi.fn(),
|
||||
warn: vi.fn(),
|
||||
error: vi.fn(),
|
||||
} as unknown as Logger;
|
||||
output = {
|
||||
present: vi.fn(),
|
||||
};
|
||||
|
||||
useCase = new SignupSponsorUseCase(
|
||||
authRepo as unknown as IAuthRepository,
|
||||
companyRepo as unknown as ICompanyRepository,
|
||||
passwordService as unknown as IPasswordHashingService,
|
||||
logger,
|
||||
output,
|
||||
);
|
||||
});
|
||||
|
||||
it('creates user and company successfully when email is free', async () => {
|
||||
const input = {
|
||||
email: 'sponsor@example.com',
|
||||
password: 'Password123',
|
||||
displayName: 'John Doe',
|
||||
companyName: 'Acme Racing Co.',
|
||||
};
|
||||
|
||||
authRepo.findByEmail.mockResolvedValue(null);
|
||||
passwordService.hash.mockResolvedValue('hashed-password');
|
||||
companyRepo.create.mockImplementation((data) => ({
|
||||
getId: () => 'company-123',
|
||||
getName: data.getName,
|
||||
getOwnerUserId: data.getOwnerUserId,
|
||||
getContactEmail: data.getContactEmail,
|
||||
}));
|
||||
companyRepo.save.mockResolvedValue(undefined);
|
||||
authRepo.save.mockResolvedValue(undefined);
|
||||
|
||||
const result = await useCase.execute(input);
|
||||
|
||||
// Verify the basic flow worked
|
||||
expect(result.isOk()).toBe(true);
|
||||
expect(output.present).toHaveBeenCalled();
|
||||
|
||||
// Verify key repository methods were called
|
||||
expect(authRepo.findByEmail).toHaveBeenCalled();
|
||||
expect(passwordService.hash).toHaveBeenCalled();
|
||||
expect(companyRepo.create).toHaveBeenCalled();
|
||||
expect(companyRepo.save).toHaveBeenCalled();
|
||||
expect(authRepo.save).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('rolls back company creation when user save fails', async () => {
|
||||
const input = {
|
||||
email: 'sponsor@example.com',
|
||||
password: 'Password123',
|
||||
displayName: 'John Doe',
|
||||
companyName: 'Acme Racing Co.',
|
||||
};
|
||||
|
||||
authRepo.findByEmail.mockResolvedValue(null);
|
||||
passwordService.hash.mockResolvedValue('hashed-password');
|
||||
companyRepo.create.mockImplementation((data) => ({
|
||||
getId: () => 'company-123',
|
||||
getName: data.getName,
|
||||
getOwnerUserId: data.getOwnerUserId,
|
||||
getContactEmail: data.getContactEmail,
|
||||
}));
|
||||
companyRepo.save.mockResolvedValue(undefined);
|
||||
authRepo.save.mockRejectedValue(new Error('Database error'));
|
||||
|
||||
const result = await useCase.execute(input);
|
||||
|
||||
// Verify company was deleted (rollback)
|
||||
expect(companyRepo.delete).toHaveBeenCalled();
|
||||
const deletedCompanyId = companyRepo.delete.mock.calls[0][0];
|
||||
expect(deletedCompanyId).toBeDefined();
|
||||
|
||||
// Verify error result
|
||||
expect(result.isErr()).toBe(true);
|
||||
const error = result.unwrapErr();
|
||||
expect(error.code).toBe('REPOSITORY_ERROR');
|
||||
});
|
||||
|
||||
it('fails when user already exists', async () => {
|
||||
const input = {
|
||||
email: 'existing@example.com',
|
||||
password: 'Password123',
|
||||
displayName: 'John Doe',
|
||||
companyName: 'Acme Racing Co.',
|
||||
};
|
||||
|
||||
const existingUser = User.create({
|
||||
id: UserId.create(),
|
||||
displayName: 'Existing User',
|
||||
email: input.email,
|
||||
});
|
||||
|
||||
authRepo.findByEmail.mockResolvedValue(existingUser);
|
||||
|
||||
const result = await useCase.execute(input);
|
||||
|
||||
expect(result.isErr()).toBe(true);
|
||||
const error = result.unwrapErr();
|
||||
expect(error.code).toBe('USER_ALREADY_EXISTS');
|
||||
|
||||
// Verify no company was created
|
||||
expect(companyRepo.create).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('fails when company creation throws an error', async () => {
|
||||
const input = {
|
||||
email: 'sponsor@example.com',
|
||||
password: 'Password123',
|
||||
displayName: 'John Doe',
|
||||
companyName: 'Acme Racing Co.',
|
||||
};
|
||||
|
||||
authRepo.findByEmail.mockResolvedValue(null);
|
||||
passwordService.hash.mockResolvedValue('hashed-password');
|
||||
companyRepo.create.mockImplementation(() => {
|
||||
throw new Error('Invalid company data');
|
||||
});
|
||||
|
||||
const result = await useCase.execute(input);
|
||||
|
||||
expect(result.isErr()).toBe(true);
|
||||
const error = result.unwrapErr();
|
||||
expect(error.code).toBe('REPOSITORY_ERROR');
|
||||
// The error message might be wrapped, so just check it's a repository error
|
||||
});
|
||||
|
||||
it('fails with weak password', async () => {
|
||||
const input = {
|
||||
email: 'sponsor@example.com',
|
||||
password: 'weak',
|
||||
displayName: 'John Doe',
|
||||
companyName: 'Acme Racing Co.',
|
||||
};
|
||||
|
||||
const result = await useCase.execute(input);
|
||||
|
||||
expect(result.isErr()).toBe(true);
|
||||
const error = result.unwrapErr();
|
||||
expect(error.code).toBe('WEAK_PASSWORD');
|
||||
|
||||
// Verify no repository calls
|
||||
expect(authRepo.findByEmail).not.toHaveBeenCalled();
|
||||
expect(companyRepo.create).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('fails with invalid display name', async () => {
|
||||
const input = {
|
||||
email: 'sponsor@example.com',
|
||||
password: 'Password123',
|
||||
displayName: 'user123', // Invalid - alphanumeric only
|
||||
companyName: 'Acme Racing Co.',
|
||||
};
|
||||
|
||||
const result = await useCase.execute(input);
|
||||
|
||||
expect(result.isErr()).toBe(true);
|
||||
const error = result.unwrapErr();
|
||||
expect(error.code).toBe('INVALID_DISPLAY_NAME');
|
||||
|
||||
// Verify no repository calls
|
||||
expect(authRepo.findByEmail).not.toHaveBeenCalled();
|
||||
expect(companyRepo.create).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
180
core/identity/application/use-cases/SignupSponsorUseCase.ts
Normal file
180
core/identity/application/use-cases/SignupSponsorUseCase.ts
Normal file
@@ -0,0 +1,180 @@
|
||||
import { EmailAddress } from '../../domain/value-objects/EmailAddress';
|
||||
import { UserId } from '../../domain/value-objects/UserId';
|
||||
import { User } from '../../domain/entities/User';
|
||||
import { Company } from '../../domain/entities/Company';
|
||||
import { IAuthRepository } from '../../domain/repositories/IAuthRepository';
|
||||
import { ICompanyRepository } from '../../domain/repositories/ICompanyRepository';
|
||||
import { IPasswordHashingService } from '../../domain/services/PasswordHashingService';
|
||||
import { Result } from '@core/shared/application/Result';
|
||||
import type { ApplicationErrorCode } from '@core/shared/errors/ApplicationErrorCode';
|
||||
import type { UseCaseOutputPort, Logger, UseCase } from '@core/shared/application';
|
||||
|
||||
export type SignupSponsorInput = {
|
||||
email: string;
|
||||
password: string;
|
||||
displayName: string;
|
||||
companyName: string;
|
||||
};
|
||||
|
||||
export type SignupSponsorResult = {
|
||||
user: User;
|
||||
company: Company;
|
||||
};
|
||||
|
||||
export type SignupSponsorErrorCode = 'USER_ALREADY_EXISTS' | 'WEAK_PASSWORD' | 'INVALID_DISPLAY_NAME' | 'REPOSITORY_ERROR';
|
||||
|
||||
export type SignupSponsorApplicationError = ApplicationErrorCode<SignupSponsorErrorCode, { message: string }>;
|
||||
|
||||
/**
|
||||
* Application Use Case: SignupSponsorUseCase
|
||||
*
|
||||
* Handles sponsor registration by creating both a User and a Company atomically.
|
||||
* If any step fails, the operation is rolled back.
|
||||
*/
|
||||
export class SignupSponsorUseCase implements UseCase<SignupSponsorInput, void, SignupSponsorErrorCode> {
|
||||
constructor(
|
||||
private readonly authRepo: IAuthRepository,
|
||||
private readonly companyRepo: ICompanyRepository,
|
||||
private readonly passwordService: IPasswordHashingService,
|
||||
private readonly logger: Logger,
|
||||
private readonly output: UseCaseOutputPort<SignupSponsorResult>,
|
||||
) {}
|
||||
|
||||
async execute(input: SignupSponsorInput): Promise<Result<void, SignupSponsorApplicationError>> {
|
||||
let createdCompany: Company | null = null;
|
||||
|
||||
try {
|
||||
// Validate password strength first (before any repository calls)
|
||||
if (!this.isPasswordStrong(input.password)) {
|
||||
return Result.err({
|
||||
code: 'WEAK_PASSWORD',
|
||||
details: { message: 'Password must be at least 8 characters and contain uppercase, lowercase, and number' },
|
||||
});
|
||||
}
|
||||
|
||||
// Validate display name format (before any repository calls)
|
||||
// We do this by attempting to create a User and catching any validation errors
|
||||
try {
|
||||
// Temporarily create user to validate display name
|
||||
User.create({
|
||||
id: UserId.create(),
|
||||
displayName: input.displayName,
|
||||
});
|
||||
} catch (error) {
|
||||
if (error instanceof Error) {
|
||||
if (error.message.includes('Name must be at least') ||
|
||||
error.message.includes('Name can only contain') ||
|
||||
error.message.includes('Please use your real name')) {
|
||||
return Result.err({
|
||||
code: 'INVALID_DISPLAY_NAME',
|
||||
details: { message: error.message },
|
||||
});
|
||||
}
|
||||
}
|
||||
// Re-throw if it's a different error
|
||||
throw error;
|
||||
}
|
||||
|
||||
// Validate email format
|
||||
const emailVO = EmailAddress.create(input.email);
|
||||
|
||||
// Check if user exists
|
||||
const existingUser = await this.authRepo.findByEmail(emailVO);
|
||||
if (existingUser) {
|
||||
return Result.err({
|
||||
code: 'USER_ALREADY_EXISTS',
|
||||
details: { message: 'User already exists' },
|
||||
});
|
||||
}
|
||||
|
||||
// Hash password
|
||||
const hashedPassword = await this.passwordService.hash(input.password);
|
||||
const passwordHashModule = await import('../../domain/value-objects/PasswordHash');
|
||||
const passwordHash = passwordHashModule.PasswordHash.fromHash(hashedPassword);
|
||||
|
||||
// Create user with all fields
|
||||
const userId = UserId.create();
|
||||
const user = User.create({
|
||||
id: userId,
|
||||
displayName: input.displayName,
|
||||
email: emailVO.value,
|
||||
passwordHash,
|
||||
});
|
||||
|
||||
// Create company via repository
|
||||
const company = this.companyRepo.create({
|
||||
getName: () => input.companyName,
|
||||
getOwnerUserId: () => userId,
|
||||
getContactEmail: () => emailVO.value,
|
||||
});
|
||||
|
||||
// Save company first
|
||||
await this.companyRepo.save(company);
|
||||
createdCompany = company;
|
||||
|
||||
// Link user to company
|
||||
user.setCompanyId(company.getId());
|
||||
|
||||
// Save user
|
||||
await this.authRepo.save(user);
|
||||
|
||||
this.output.present({ user, company });
|
||||
return Result.ok(undefined);
|
||||
} catch (error) {
|
||||
// Rollback: delete company if it was created
|
||||
if (createdCompany && typeof createdCompany.getId === 'function') {
|
||||
try {
|
||||
const companyId = createdCompany.getId();
|
||||
await this.companyRepo.delete(companyId);
|
||||
this.logger.info('[SignupSponsorUseCase] Rolled back company creation', {
|
||||
companyId,
|
||||
});
|
||||
} catch (rollbackError) {
|
||||
this.logger.error('[SignupSponsorUseCase] Failed to rollback company creation', rollbackError instanceof Error ? rollbackError : undefined, {
|
||||
companyId: createdCompany.getId ? createdCompany.getId() : 'unknown',
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Handle specific validation errors from User entity
|
||||
if (error instanceof Error) {
|
||||
if (error.message.includes('Name must be at least') ||
|
||||
error.message.includes('Name can only contain') ||
|
||||
error.message.includes('Please use your real name')) {
|
||||
return Result.err({
|
||||
code: 'INVALID_DISPLAY_NAME',
|
||||
details: { message: error.message },
|
||||
});
|
||||
}
|
||||
if (error.message.includes('Company name')) {
|
||||
return Result.err({
|
||||
code: 'REPOSITORY_ERROR',
|
||||
details: { message: error.message },
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const message =
|
||||
error instanceof Error && error.message
|
||||
? error.message
|
||||
: 'Failed to execute SignupSponsorUseCase';
|
||||
|
||||
this.logger.error('SignupSponsorUseCase.execute failed', error instanceof Error ? error : undefined, {
|
||||
input,
|
||||
});
|
||||
|
||||
return Result.err({
|
||||
code: 'REPOSITORY_ERROR',
|
||||
details: { message },
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
private isPasswordStrong(password: string): boolean {
|
||||
if (password.length < 8) return false;
|
||||
if (!/[a-z]/.test(password)) return false;
|
||||
if (!/[A-Z]/.test(password)) return false;
|
||||
if (!/\d/.test(password)) return false;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
98
core/identity/domain/entities/Company.ts
Normal file
98
core/identity/domain/entities/Company.ts
Normal file
@@ -0,0 +1,98 @@
|
||||
import { UserId } from '../value-objects/UserId';
|
||||
|
||||
export interface CompanyProps {
|
||||
id: string;
|
||||
name: string;
|
||||
ownerUserId: UserId;
|
||||
contactEmail: string | undefined;
|
||||
createdAt: Date;
|
||||
}
|
||||
|
||||
export class Company {
|
||||
private readonly id: string;
|
||||
private readonly name: string;
|
||||
private readonly ownerUserId: UserId;
|
||||
private readonly contactEmail: string | undefined;
|
||||
private readonly createdAt: Date;
|
||||
|
||||
private constructor(props: CompanyProps) {
|
||||
this.validateName(props.name);
|
||||
|
||||
this.id = props.id;
|
||||
this.name = props.name;
|
||||
this.ownerUserId = props.ownerUserId;
|
||||
this.contactEmail = props.contactEmail;
|
||||
this.createdAt = props.createdAt;
|
||||
}
|
||||
|
||||
private validateName(name: string): void {
|
||||
const trimmed = name?.trim();
|
||||
|
||||
if (!trimmed) {
|
||||
throw new Error('Company name cannot be empty');
|
||||
}
|
||||
|
||||
if (trimmed.length < 2) {
|
||||
throw new Error('Company name must be at least 2 characters long');
|
||||
}
|
||||
|
||||
if (trimmed.length > 100) {
|
||||
throw new Error('Company name must be no more than 100 characters');
|
||||
}
|
||||
}
|
||||
|
||||
public static create(props: {
|
||||
name: string;
|
||||
ownerUserId: UserId;
|
||||
contactEmail?: string;
|
||||
}): Company {
|
||||
return new Company({
|
||||
id: this.generateId(),
|
||||
name: props.name,
|
||||
ownerUserId: props.ownerUserId,
|
||||
contactEmail: props.contactEmail,
|
||||
createdAt: new Date(),
|
||||
});
|
||||
}
|
||||
|
||||
public static rehydrate(props: {
|
||||
id: string;
|
||||
name: string;
|
||||
ownerUserId: string;
|
||||
contactEmail?: string;
|
||||
createdAt: Date;
|
||||
}): Company {
|
||||
return new Company({
|
||||
id: props.id,
|
||||
name: props.name,
|
||||
ownerUserId: UserId.fromString(props.ownerUserId),
|
||||
contactEmail: props.contactEmail,
|
||||
createdAt: props.createdAt,
|
||||
});
|
||||
}
|
||||
|
||||
private static generateId(): string {
|
||||
// Simple UUID-like generation for now
|
||||
return `comp_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
|
||||
}
|
||||
|
||||
public getId(): string {
|
||||
return this.id;
|
||||
}
|
||||
|
||||
public getName(): string {
|
||||
return this.name;
|
||||
}
|
||||
|
||||
public getOwnerUserId(): UserId {
|
||||
return this.ownerUserId;
|
||||
}
|
||||
|
||||
public getContactEmail(): string | undefined {
|
||||
return this.contactEmail;
|
||||
}
|
||||
|
||||
public getCreatedAt(): Date {
|
||||
return this.createdAt;
|
||||
}
|
||||
}
|
||||
@@ -12,6 +12,7 @@ export interface UserProps {
|
||||
iracingCustomerId?: string;
|
||||
primaryDriverId?: string;
|
||||
avatarUrl?: string;
|
||||
companyId?: string;
|
||||
}
|
||||
|
||||
export class User {
|
||||
@@ -22,6 +23,7 @@ export class User {
|
||||
private iracingCustomerId: string | undefined;
|
||||
private primaryDriverId: string | undefined;
|
||||
private avatarUrl: string | undefined;
|
||||
private companyId: string | undefined;
|
||||
|
||||
private constructor(props: UserProps) {
|
||||
this.validateDisplayName(props.displayName);
|
||||
@@ -33,6 +35,7 @@ export class User {
|
||||
this.iracingCustomerId = props.iracingCustomerId;
|
||||
this.primaryDriverId = props.primaryDriverId;
|
||||
this.avatarUrl = props.avatarUrl;
|
||||
this.companyId = props.companyId;
|
||||
}
|
||||
|
||||
private validateDisplayName(displayName: string): void {
|
||||
@@ -108,6 +111,7 @@ export class User {
|
||||
iracingCustomerId?: string;
|
||||
primaryDriverId?: string;
|
||||
avatarUrl?: string;
|
||||
companyId?: string;
|
||||
}): User {
|
||||
const email =
|
||||
props.email !== undefined
|
||||
@@ -128,6 +132,7 @@ export class User {
|
||||
...(props.iracingCustomerId !== undefined ? { iracingCustomerId: props.iracingCustomerId } : {}),
|
||||
...(props.primaryDriverId !== undefined ? { primaryDriverId: props.primaryDriverId } : {}),
|
||||
...(props.avatarUrl !== undefined ? { avatarUrl: props.avatarUrl } : {}),
|
||||
...(props.companyId !== undefined ? { companyId: props.companyId } : {}),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -144,6 +149,7 @@ export class User {
|
||||
...(stored.primaryDriverId !== undefined
|
||||
? { primaryDriverId: stored.primaryDriverId }
|
||||
: {}),
|
||||
...(stored.companyId !== undefined ? { companyId: stored.companyId } : {}),
|
||||
};
|
||||
|
||||
return new User(userProps);
|
||||
@@ -177,6 +183,10 @@ export class User {
|
||||
return this.avatarUrl;
|
||||
}
|
||||
|
||||
public getCompanyId(): string | undefined {
|
||||
return this.companyId;
|
||||
}
|
||||
|
||||
/**
|
||||
* Update display name - NOT ALLOWED after initial creation
|
||||
* This method will always throw an error to enforce immutability
|
||||
@@ -193,4 +203,13 @@ export class User {
|
||||
// All users created through proper channels have immutable names
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set company ID (for linking user to company during sponsor signup)
|
||||
* This is only allowed during initial creation via rehydrate/fromStored
|
||||
* For runtime updates, a separate method would be needed
|
||||
*/
|
||||
public setCompanyId(companyId: string): void {
|
||||
this.companyId = companyId;
|
||||
}
|
||||
}
|
||||
33
core/identity/domain/repositories/ICompanyRepository.ts
Normal file
33
core/identity/domain/repositories/ICompanyRepository.ts
Normal file
@@ -0,0 +1,33 @@
|
||||
import { Company } from '../entities/Company';
|
||||
|
||||
/**
|
||||
* Domain Repository: ICompanyRepository
|
||||
*
|
||||
* Repository interface for Company entity operations.
|
||||
*/
|
||||
export interface ICompanyRepository {
|
||||
/**
|
||||
* Create a new company (returns unsaved entity)
|
||||
*/
|
||||
create(company: Pick<Company, 'getName' | 'getOwnerUserId' | 'getContactEmail'>): Company;
|
||||
|
||||
/**
|
||||
* Save a company to the database
|
||||
*/
|
||||
save(company: Company): Promise<void>;
|
||||
|
||||
/**
|
||||
* Delete a company by ID
|
||||
*/
|
||||
delete(id: string): Promise<void>;
|
||||
|
||||
/**
|
||||
* Find company by ID
|
||||
*/
|
||||
findById(id: string): Promise<Company | null>;
|
||||
|
||||
/**
|
||||
* Find company by owner user ID
|
||||
*/
|
||||
findByOwnerUserId(userId: string): Promise<Company | null>;
|
||||
}
|
||||
@@ -16,6 +16,7 @@ export interface StoredUser {
|
||||
passwordHash: string;
|
||||
salt?: string;
|
||||
primaryDriverId?: string | undefined;
|
||||
companyId?: string | undefined;
|
||||
createdAt: Date;
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user