driver to user id
This commit is contained in:
@@ -0,0 +1,50 @@
|
||||
import { Company } from '@core/identity/domain/entities/Company';
|
||||
import { ICompanyRepository } from '@core/identity/domain/repositories/ICompanyRepository';
|
||||
|
||||
/**
|
||||
* In-memory implementation of ICompanyRepository for testing
|
||||
*/
|
||||
export class InMemoryCompanyRepository implements ICompanyRepository {
|
||||
private companies: Map<string, Company> = new Map();
|
||||
|
||||
create(company: Pick<Company, 'getName' | 'getOwnerUserId' | 'getContactEmail'>): Company {
|
||||
// Create a new Company instance with generated ID
|
||||
const contactEmail = company.getContactEmail();
|
||||
return Company.create({
|
||||
name: company.getName(),
|
||||
ownerUserId: company.getOwnerUserId(),
|
||||
...(contactEmail !== undefined ? { contactEmail } : {}),
|
||||
});
|
||||
}
|
||||
|
||||
async save(company: Company): Promise<void> {
|
||||
this.companies.set(company.getId(), company);
|
||||
}
|
||||
|
||||
async delete(id: string): Promise<void> {
|
||||
this.companies.delete(id);
|
||||
}
|
||||
|
||||
async findById(id: string): Promise<Company | null> {
|
||||
return this.companies.get(id) || null;
|
||||
}
|
||||
|
||||
async findByOwnerUserId(userId: string): Promise<Company | null> {
|
||||
for (const company of this.companies.values()) {
|
||||
if (company.getOwnerUserId().toString() === userId) {
|
||||
return company;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
// Helper method for testing to get all companies
|
||||
getAll(): Company[] {
|
||||
return Array.from(this.companies.values());
|
||||
}
|
||||
|
||||
// Helper method for testing to clear all
|
||||
clear(): void {
|
||||
this.companies.clear();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import { Entity, PrimaryGeneratedColumn, Column, CreateDateColumn } from 'typeorm';
|
||||
|
||||
@Entity('companies')
|
||||
export class CompanyOrmEntity {
|
||||
@PrimaryGeneratedColumn('uuid')
|
||||
id!: string;
|
||||
|
||||
@Column({ type: 'varchar', length: 100 })
|
||||
name!: string;
|
||||
|
||||
@Column({ name: 'owner_user_id', type: 'varchar' })
|
||||
ownerUserId!: string;
|
||||
|
||||
@Column({ type: 'varchar', nullable: true })
|
||||
contactEmail: string | null = null;
|
||||
|
||||
@CreateDateColumn({ name: 'created_at' })
|
||||
createdAt!: Date;
|
||||
}
|
||||
@@ -21,6 +21,9 @@ export class UserOrmEntity {
|
||||
@Column({ type: 'text', nullable: true })
|
||||
primaryDriverId!: string | null;
|
||||
|
||||
@Column({ name: 'company_id', type: 'text', nullable: true })
|
||||
companyId!: string | null;
|
||||
|
||||
@CreateDateColumn({ type: 'timestamptz' })
|
||||
createdAt!: Date;
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
import { Company } from '@core/identity/domain/entities/Company';
|
||||
import { CompanyOrmEntity } from '../entities/CompanyOrmEntity';
|
||||
|
||||
export class CompanyOrmMapper {
|
||||
toDomain(entity: CompanyOrmEntity): Company {
|
||||
const contactEmail = entity.contactEmail ?? undefined;
|
||||
return Company.rehydrate({
|
||||
id: entity.id,
|
||||
name: entity.name,
|
||||
ownerUserId: entity.ownerUserId,
|
||||
...(contactEmail !== undefined ? { contactEmail } : {}),
|
||||
createdAt: entity.createdAt,
|
||||
});
|
||||
}
|
||||
|
||||
toPersistence(domain: Company): CompanyOrmEntity {
|
||||
const entity = new CompanyOrmEntity();
|
||||
entity.id = domain.getId();
|
||||
entity.name = domain.getName();
|
||||
entity.ownerUserId = domain.getOwnerUserId().toString();
|
||||
entity.contactEmail = domain.getContactEmail() ?? null;
|
||||
// Note: createdAt is handled by @CreateDateColumn
|
||||
return entity;
|
||||
}
|
||||
}
|
||||
@@ -17,6 +17,7 @@ export class UserOrmMapper {
|
||||
assertNonEmptyString(entityName, 'passwordHash', entity.passwordHash);
|
||||
assertOptionalStringOrNull(entityName, 'salt', entity.salt);
|
||||
assertOptionalStringOrNull(entityName, 'primaryDriverId', entity.primaryDriverId);
|
||||
assertOptionalStringOrNull(entityName, 'companyId', entity.companyId);
|
||||
assertDate(entityName, 'createdAt', entity.createdAt);
|
||||
} catch (error) {
|
||||
if (error instanceof TypeOrmIdentitySchemaError) {
|
||||
@@ -35,6 +36,7 @@ export class UserOrmMapper {
|
||||
displayName: entity.displayName,
|
||||
...(passwordHash ? { passwordHash } : {}),
|
||||
...(entity.primaryDriverId ? { primaryDriverId: entity.primaryDriverId } : {}),
|
||||
...(entity.companyId ? { companyId: entity.companyId } : {}),
|
||||
});
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : 'Invalid persisted User';
|
||||
@@ -50,6 +52,7 @@ export class UserOrmMapper {
|
||||
entity.passwordHash = stored.passwordHash;
|
||||
entity.salt = stored.salt ?? '';
|
||||
entity.primaryDriverId = stored.primaryDriverId ?? null;
|
||||
entity.companyId = stored.companyId ?? null;
|
||||
entity.createdAt = stored.createdAt;
|
||||
return entity;
|
||||
}
|
||||
@@ -62,6 +65,7 @@ export class UserOrmMapper {
|
||||
passwordHash: entity.passwordHash,
|
||||
...(entity.salt ? { salt: entity.salt } : {}),
|
||||
primaryDriverId: entity.primaryDriverId ?? undefined,
|
||||
companyId: entity.companyId ?? undefined,
|
||||
createdAt: entity.createdAt,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -42,6 +42,7 @@ export class TypeOrmAuthRepository implements IAuthRepository {
|
||||
entity.passwordHash = passwordHash;
|
||||
entity.salt = '';
|
||||
entity.primaryDriverId = user.getPrimaryDriverId() ?? null;
|
||||
entity.companyId = user.getCompanyId() ?? null;
|
||||
entity.createdAt = existing?.createdAt ?? new Date();
|
||||
|
||||
await repo.save(entity);
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
import type { DataSource } from 'typeorm';
|
||||
|
||||
import { Company } from '@core/identity/domain/entities/Company';
|
||||
import type { ICompanyRepository } from '@core/identity/domain/repositories/ICompanyRepository';
|
||||
|
||||
import { CompanyOrmEntity } from '../entities/CompanyOrmEntity';
|
||||
import { CompanyOrmMapper } from '../mappers/CompanyOrmMapper';
|
||||
|
||||
export class TypeOrmCompanyRepository implements ICompanyRepository {
|
||||
constructor(
|
||||
private readonly dataSource: DataSource,
|
||||
private readonly mapper: CompanyOrmMapper,
|
||||
) {}
|
||||
|
||||
create(company: Pick<Company, 'getName' | 'getOwnerUserId' | 'getContactEmail'>): Company {
|
||||
// Create a new Company instance with generated ID
|
||||
const contactEmail = company.getContactEmail();
|
||||
return Company.create({
|
||||
name: company.getName(),
|
||||
ownerUserId: company.getOwnerUserId(),
|
||||
...(contactEmail !== undefined ? { contactEmail } : {}),
|
||||
});
|
||||
}
|
||||
|
||||
async save(company: Company): Promise<void> {
|
||||
const repo = this.dataSource.getRepository(CompanyOrmEntity);
|
||||
const entity = this.mapper.toPersistence(company);
|
||||
await repo.save(entity);
|
||||
}
|
||||
|
||||
async delete(id: string): Promise<void> {
|
||||
const repo = this.dataSource.getRepository(CompanyOrmEntity);
|
||||
await repo.delete(id);
|
||||
}
|
||||
|
||||
async findById(id: string): Promise<Company | null> {
|
||||
const repo = this.dataSource.getRepository(CompanyOrmEntity);
|
||||
const entity = await repo.findOne({ where: { id } });
|
||||
return entity ? this.mapper.toDomain(entity) : null;
|
||||
}
|
||||
|
||||
async findByOwnerUserId(userId: string): Promise<Company | null> {
|
||||
const repo = this.dataSource.getRepository(CompanyOrmEntity);
|
||||
const entity = await repo.findOne({ where: { ownerUserId: userId } });
|
||||
return entity ? this.mapper.toDomain(entity) : null;
|
||||
}
|
||||
}
|
||||
@@ -4,9 +4,9 @@
|
||||
* Run with: npm test -- feature-loader.test.ts
|
||||
*/
|
||||
|
||||
import { describe, it, expect, beforeAll, beforeEach } from 'vitest';
|
||||
import { describe, it, expect, beforeEach } from 'vitest';
|
||||
import { loadFeatureConfig, isFeatureEnabled, getFeatureState, getAllFeatures } from './feature-loader';
|
||||
import { FlattenedFeatures, FeatureState } from './feature-types';
|
||||
import { FlattenedFeatures } from './feature-types';
|
||||
|
||||
describe('Feature Flag Configuration', () => {
|
||||
const originalEnv = process.env.NODE_ENV;
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
* Integration test to verify the feature flag system works end-to-end
|
||||
*/
|
||||
|
||||
import { describe, it, expect, beforeAll } from 'vitest';
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { loadFeatureConfig, isFeatureEnabled, getFeatureState } from './feature-loader';
|
||||
|
||||
describe('Feature Flag Integration Test', () => {
|
||||
|
||||
@@ -6,7 +6,7 @@ import request from 'supertest';
|
||||
import { Mock, vi } from 'vitest';
|
||||
import { AuthController } from './AuthController';
|
||||
import { AuthService } from './AuthService';
|
||||
import { AuthSessionDTO, LoginParamsDTO, SignupParamsDTO } from './dtos/AuthDto';
|
||||
import { AuthSessionDTO, LoginParamsDTO, SignupParamsDTO, SignupSponsorParamsDTO } from './dtos/AuthDto';
|
||||
import type { CommandResultDTO } from './presenters/CommandResultPresenter';
|
||||
import { AuthenticationGuard } from './AuthenticationGuard';
|
||||
import { AuthorizationGuard } from './AuthorizationGuard';
|
||||
@@ -21,6 +21,7 @@ describe('AuthController', () => {
|
||||
beforeEach(() => {
|
||||
service = {
|
||||
signupWithEmail: vi.fn(),
|
||||
signupSponsor: vi.fn(),
|
||||
loginWithEmail: vi.fn(),
|
||||
getCurrentSession: vi.fn(),
|
||||
logout: vi.fn(),
|
||||
@@ -56,6 +57,32 @@ describe('AuthController', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('signupSponsor', () => {
|
||||
it('should call service.signupSponsor and return session DTO', async () => {
|
||||
const params: SignupSponsorParamsDTO = {
|
||||
email: 'sponsor@example.com',
|
||||
password: 'Password123',
|
||||
displayName: 'John Doe',
|
||||
companyName: 'Acme Racing Co.',
|
||||
};
|
||||
const session: AuthSessionDTO = {
|
||||
token: 'token123',
|
||||
user: {
|
||||
userId: 'user1',
|
||||
email: 'sponsor@example.com',
|
||||
displayName: 'John Doe',
|
||||
companyId: 'company-123',
|
||||
},
|
||||
};
|
||||
(service.signupSponsor as Mock).mockResolvedValue(session);
|
||||
|
||||
const result = await controller.signupSponsor(params);
|
||||
|
||||
expect(service.signupSponsor).toHaveBeenCalledWith(params);
|
||||
expect(result).toEqual(session);
|
||||
});
|
||||
});
|
||||
|
||||
describe('login', () => {
|
||||
it('should call service.loginWithEmail and return session DTO', async () => {
|
||||
const params: LoginParamsDTO = {
|
||||
@@ -155,6 +182,7 @@ describe('AuthController', () => {
|
||||
getCurrentSession: vi.fn(async () => null),
|
||||
loginWithEmail: vi.fn(),
|
||||
signupWithEmail: vi.fn(),
|
||||
signupSponsor: vi.fn(),
|
||||
logout: vi.fn(),
|
||||
startIracingAuth: vi.fn(),
|
||||
iracingCallback: vi.fn(),
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { Controller, Get, Post, Body, Query, Inject, Res } from '@nestjs/common';
|
||||
import { Public } from './Public';
|
||||
import { AuthService } from './AuthService';
|
||||
import { LoginParamsDTO, SignupParamsDTO, AuthSessionDTO, ForgotPasswordDTO, ResetPasswordDTO } from './dtos/AuthDto';
|
||||
import { LoginParamsDTO, SignupParamsDTO, SignupSponsorParamsDTO, AuthSessionDTO, ForgotPasswordDTO, ResetPasswordDTO } from './dtos/AuthDto';
|
||||
import type { CommandResultDTO } from './presenters/CommandResultPresenter';
|
||||
import type { Response } from 'express';
|
||||
|
||||
@@ -15,6 +15,11 @@ export class AuthController {
|
||||
return this.authService.signupWithEmail(params);
|
||||
}
|
||||
|
||||
@Post('signup-sponsor')
|
||||
async signupSponsor(@Body() params: SignupSponsorParamsDTO): Promise<AuthSessionDTO> {
|
||||
return this.authService.signupSponsor(params);
|
||||
}
|
||||
|
||||
@Post('login')
|
||||
async login(@Body() params: LoginParamsDTO): Promise<AuthSessionDTO> {
|
||||
return this.authService.loginWithEmail(params);
|
||||
|
||||
@@ -4,16 +4,19 @@ import { CookieIdentitySessionAdapter } from '@adapters/identity/session/CookieI
|
||||
import { LoginUseCase } from '@core/identity/application/use-cases/LoginUseCase';
|
||||
import { LogoutUseCase } from '@core/identity/application/use-cases/LogoutUseCase';
|
||||
import { SignupUseCase } from '@core/identity/application/use-cases/SignupUseCase';
|
||||
import { SignupSponsorUseCase } from '@core/identity/application/use-cases/SignupSponsorUseCase';
|
||||
import { ForgotPasswordUseCase } from '@core/identity/application/use-cases/ForgotPasswordUseCase';
|
||||
import { ResetPasswordUseCase } from '@core/identity/application/use-cases/ResetPasswordUseCase';
|
||||
import type { IdentitySessionPort } from '@core/identity/application/ports/IdentitySessionPort';
|
||||
import type { IAuthRepository } from '@core/identity/domain/repositories/IAuthRepository';
|
||||
import type { ICompanyRepository } from '@core/identity/domain/repositories/ICompanyRepository';
|
||||
import type { IMagicLinkRepository } from '@core/identity/domain/repositories/IMagicLinkRepository';
|
||||
import type { IPasswordHashingService } from '@core/identity/domain/services/PasswordHashingService';
|
||||
import type { IMagicLinkNotificationPort } from '@core/identity/domain/ports/IMagicLinkNotificationPort';
|
||||
import type { LoginResult } from '@core/identity/application/use-cases/LoginUseCase';
|
||||
import type { LogoutResult } from '@core/identity/application/use-cases/LogoutUseCase';
|
||||
import type { SignupResult } from '@core/identity/application/use-cases/SignupUseCase';
|
||||
import type { SignupSponsorResult } from '@core/identity/application/use-cases/SignupSponsorUseCase';
|
||||
import type { ForgotPasswordResult } from '@core/identity/application/use-cases/ForgotPasswordUseCase';
|
||||
import type { ResetPasswordResult } from '@core/identity/application/use-cases/ResetPasswordUseCase';
|
||||
import type { Logger, UseCaseOutputPort } from '@core/shared/application';
|
||||
@@ -23,6 +26,7 @@ import {
|
||||
PASSWORD_HASHING_SERVICE_TOKEN,
|
||||
USER_REPOSITORY_TOKEN,
|
||||
MAGIC_LINK_REPOSITORY_TOKEN,
|
||||
COMPANY_REPOSITORY_TOKEN,
|
||||
} from '../../persistence/identity/IdentityPersistenceTokens';
|
||||
|
||||
import { AuthSessionPresenter } from './presenters/AuthSessionPresenter';
|
||||
@@ -37,6 +41,7 @@ export const LOGGER_TOKEN = 'Logger';
|
||||
export const IDENTITY_SESSION_PORT_TOKEN = 'IdentitySessionPort';
|
||||
export const LOGIN_USE_CASE_TOKEN = 'LoginUseCase';
|
||||
export const SIGNUP_USE_CASE_TOKEN = 'SignupUseCase';
|
||||
export const SIGNUP_SPONSOR_USE_CASE_TOKEN = 'SignupSponsorUseCase';
|
||||
export const LOGOUT_USE_CASE_TOKEN = 'LogoutUseCase';
|
||||
export const FORGOT_PASSWORD_USE_CASE_TOKEN = 'ForgotPasswordUseCase';
|
||||
export const RESET_PASSWORD_USE_CASE_TOKEN = 'ResetPasswordUseCase';
|
||||
@@ -45,6 +50,7 @@ export const AUTH_SESSION_OUTPUT_PORT_TOKEN = 'AuthSessionOutputPort';
|
||||
export const COMMAND_RESULT_OUTPUT_PORT_TOKEN = 'CommandResultOutputPort';
|
||||
export const FORGOT_PASSWORD_OUTPUT_PORT_TOKEN = 'ForgotPasswordOutputPort';
|
||||
export const RESET_PASSWORD_OUTPUT_PORT_TOKEN = 'ResetPasswordOutputPort';
|
||||
export const SIGNUP_SPONSOR_OUTPUT_PORT_TOKEN = 'SignupSponsorOutputPort';
|
||||
export const MAGIC_LINK_NOTIFICATION_PORT_TOKEN = 'MagicLinkNotificationPort';
|
||||
|
||||
export const AuthProviders: Provider[] = [
|
||||
@@ -83,6 +89,17 @@ export const AuthProviders: Provider[] = [
|
||||
) => new SignupUseCase(authRepo, passwordHashing, logger, output),
|
||||
inject: [AUTH_REPOSITORY_TOKEN, PASSWORD_HASHING_SERVICE_TOKEN, LOGGER_TOKEN, AUTH_SESSION_OUTPUT_PORT_TOKEN],
|
||||
},
|
||||
{
|
||||
provide: SIGNUP_SPONSOR_USE_CASE_TOKEN,
|
||||
useFactory: (
|
||||
authRepo: IAuthRepository,
|
||||
companyRepo: ICompanyRepository,
|
||||
passwordHashing: IPasswordHashingService,
|
||||
logger: Logger,
|
||||
output: UseCaseOutputPort<SignupSponsorResult>,
|
||||
) => new SignupSponsorUseCase(authRepo, companyRepo, passwordHashing, logger, output),
|
||||
inject: [AUTH_REPOSITORY_TOKEN, COMPANY_REPOSITORY_TOKEN, PASSWORD_HASHING_SERVICE_TOKEN, LOGGER_TOKEN, SIGNUP_SPONSOR_OUTPUT_PORT_TOKEN],
|
||||
},
|
||||
{
|
||||
provide: LOGOUT_USE_CASE_TOKEN,
|
||||
useFactory: (sessionPort: IdentitySessionPort, logger: Logger, output: UseCaseOutputPort<LogoutResult>) =>
|
||||
@@ -99,6 +116,10 @@ export const AuthProviders: Provider[] = [
|
||||
provide: RESET_PASSWORD_OUTPUT_PORT_TOKEN,
|
||||
useExisting: ResetPasswordPresenter,
|
||||
},
|
||||
{
|
||||
provide: SIGNUP_SPONSOR_OUTPUT_PORT_TOKEN,
|
||||
useExisting: AuthSessionPresenter,
|
||||
},
|
||||
{
|
||||
provide: MAGIC_LINK_NOTIFICATION_PORT_TOKEN,
|
||||
useFactory: (logger: Logger) => new ConsoleMagicLinkNotificationAdapter(logger),
|
||||
|
||||
@@ -1,155 +0,0 @@
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { AuthService } from './AuthService';
|
||||
import { Result } from '@core/shared/application/Result';
|
||||
|
||||
class FakeAuthSessionPresenter {
|
||||
private model: any = null;
|
||||
reset() { this.model = null; }
|
||||
present(model: any) { this.model = model; }
|
||||
get responseModel() {
|
||||
if (!this.model) throw new Error('Presenter not presented');
|
||||
return this.model;
|
||||
}
|
||||
}
|
||||
|
||||
class FakeCommandResultPresenter {
|
||||
private model: any = null;
|
||||
reset() { this.model = null; }
|
||||
present(model: any) { this.model = model; }
|
||||
get responseModel() {
|
||||
if (!this.model) throw new Error('Presenter not presented');
|
||||
return this.model;
|
||||
}
|
||||
}
|
||||
|
||||
class FakeForgotPasswordPresenter {
|
||||
private model: any = null;
|
||||
reset() { this.model = null; }
|
||||
present(model: any) { this.model = model; }
|
||||
get responseModel() {
|
||||
if (!this.model) throw new Error('Presenter not presented');
|
||||
return this.model;
|
||||
}
|
||||
}
|
||||
|
||||
class FakeResetPasswordPresenter {
|
||||
private model: any = null;
|
||||
reset() { this.model = null; }
|
||||
present(model: any) { this.model = model; }
|
||||
get responseModel() {
|
||||
if (!this.model) throw new Error('Presenter not presented');
|
||||
return this.model;
|
||||
}
|
||||
}
|
||||
|
||||
describe('AuthService - New Methods', () => {
|
||||
describe('forgotPassword', () => {
|
||||
it('should execute forgot password use case and return result', async () => {
|
||||
const forgotPasswordPresenter = new FakeForgotPasswordPresenter();
|
||||
const forgotPasswordUseCase = {
|
||||
execute: vi.fn(async () => {
|
||||
forgotPasswordPresenter.present({ message: 'Reset link sent', magicLink: 'http://example.com/reset?token=abc123' });
|
||||
return Result.ok(undefined);
|
||||
}),
|
||||
};
|
||||
|
||||
const service = new AuthService(
|
||||
{ debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn() } as any,
|
||||
{ getCurrentSession: vi.fn(), createSession: vi.fn() } as any,
|
||||
{ execute: vi.fn() } as any,
|
||||
{ execute: vi.fn() } as any,
|
||||
{ execute: vi.fn() } as any,
|
||||
forgotPasswordUseCase as any,
|
||||
{ execute: vi.fn() } as any,
|
||||
new FakeAuthSessionPresenter() as any,
|
||||
new FakeCommandResultPresenter() as any,
|
||||
forgotPasswordPresenter as any,
|
||||
new FakeResetPasswordPresenter() as any,
|
||||
);
|
||||
|
||||
const result = await service.forgotPassword({ email: 'test@example.com' });
|
||||
|
||||
expect(forgotPasswordUseCase.execute).toHaveBeenCalledWith({ email: 'test@example.com' });
|
||||
expect(result).toEqual({
|
||||
message: 'Reset link sent',
|
||||
magicLink: 'http://example.com/reset?token=abc123',
|
||||
});
|
||||
});
|
||||
|
||||
it('should throw error on use case failure', async () => {
|
||||
const service = new AuthService(
|
||||
{ debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn() } as any,
|
||||
{ getCurrentSession: vi.fn(), createSession: vi.fn() } as any,
|
||||
{ execute: vi.fn() } as any,
|
||||
{ execute: vi.fn() } as any,
|
||||
{ execute: vi.fn() } as any,
|
||||
{ execute: vi.fn(async () => Result.err({ code: 'RATE_LIMIT_EXCEEDED', details: { message: 'Too many attempts' } })) } as any,
|
||||
{ execute: vi.fn() } as any,
|
||||
new FakeAuthSessionPresenter() as any,
|
||||
new FakeCommandResultPresenter() as any,
|
||||
new FakeForgotPasswordPresenter() as any,
|
||||
new FakeResetPasswordPresenter() as any,
|
||||
);
|
||||
|
||||
await expect(service.forgotPassword({ email: 'test@example.com' })).rejects.toThrow('Too many attempts');
|
||||
});
|
||||
});
|
||||
|
||||
describe('resetPassword', () => {
|
||||
it('should execute reset password use case and return result', async () => {
|
||||
const resetPasswordPresenter = new FakeResetPasswordPresenter();
|
||||
const resetPasswordUseCase = {
|
||||
execute: vi.fn(async () => {
|
||||
resetPasswordPresenter.present({ message: 'Password reset successfully' });
|
||||
return Result.ok(undefined);
|
||||
}),
|
||||
};
|
||||
|
||||
const service = new AuthService(
|
||||
{ debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn() } as any,
|
||||
{ getCurrentSession: vi.fn(), createSession: vi.fn() } as any,
|
||||
{ execute: vi.fn() } as any,
|
||||
{ execute: vi.fn() } as any,
|
||||
{ execute: vi.fn() } as any,
|
||||
{ execute: vi.fn() } as any,
|
||||
resetPasswordUseCase as any,
|
||||
new FakeAuthSessionPresenter() as any,
|
||||
new FakeCommandResultPresenter() as any,
|
||||
new FakeForgotPasswordPresenter() as any,
|
||||
resetPasswordPresenter as any,
|
||||
);
|
||||
|
||||
const result = await service.resetPassword({
|
||||
token: 'abc123',
|
||||
newPassword: 'NewPass123!',
|
||||
});
|
||||
|
||||
expect(resetPasswordUseCase.execute).toHaveBeenCalledWith({
|
||||
token: 'abc123',
|
||||
newPassword: 'NewPass123!',
|
||||
});
|
||||
expect(result).toEqual({ message: 'Password reset successfully' });
|
||||
});
|
||||
|
||||
it('should throw error on use case failure', async () => {
|
||||
const resetPasswordPresenter = new FakeResetPasswordPresenter();
|
||||
const service = new AuthService(
|
||||
{ debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn() } as any,
|
||||
{ getCurrentSession: vi.fn(), createSession: vi.fn() } as any,
|
||||
{ execute: vi.fn() } as any,
|
||||
{ execute: vi.fn() } as any,
|
||||
{ execute: vi.fn() } as any,
|
||||
{ execute: vi.fn() } as any,
|
||||
{ execute: vi.fn(async () => Result.err({ code: 'INVALID_TOKEN', details: { message: 'Invalid token' } })) } as any,
|
||||
new FakeAuthSessionPresenter() as any,
|
||||
new FakeCommandResultPresenter() as any,
|
||||
new FakeForgotPasswordPresenter() as any,
|
||||
resetPasswordPresenter as any,
|
||||
);
|
||||
|
||||
await expect(
|
||||
service.resetPassword({ token: 'invalid', newPassword: 'NewPass123!' })
|
||||
).rejects.toThrow('Invalid token');
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -40,6 +40,7 @@ describe('AuthService', () => {
|
||||
{ execute: vi.fn() } as any,
|
||||
{ execute: vi.fn() } as any,
|
||||
{ execute: vi.fn() } as any,
|
||||
{ execute: vi.fn() } as any,
|
||||
new FakeAuthSessionPresenter() as any,
|
||||
new FakeCommandResultPresenter() as any,
|
||||
new FakeAuthSessionPresenter() as any,
|
||||
@@ -64,6 +65,7 @@ describe('AuthService', () => {
|
||||
{ execute: vi.fn() } as any,
|
||||
{ execute: vi.fn() } as any,
|
||||
{ execute: vi.fn() } as any,
|
||||
{ execute: vi.fn() } as any,
|
||||
new FakeAuthSessionPresenter() as any,
|
||||
new FakeCommandResultPresenter() as any,
|
||||
new FakeAuthSessionPresenter() as any,
|
||||
@@ -98,6 +100,7 @@ describe('AuthService', () => {
|
||||
{ execute: vi.fn() } as any,
|
||||
{ execute: vi.fn() } as any,
|
||||
{ execute: vi.fn() } as any,
|
||||
{ execute: vi.fn() } as any,
|
||||
authSessionPresenter as any,
|
||||
new FakeCommandResultPresenter() as any,
|
||||
new FakeAuthSessionPresenter() as any,
|
||||
@@ -132,6 +135,7 @@ describe('AuthService', () => {
|
||||
{ execute: vi.fn() } as any,
|
||||
{ execute: vi.fn() } as any,
|
||||
{ execute: vi.fn() } as any,
|
||||
{ execute: vi.fn() } as any,
|
||||
new FakeAuthSessionPresenter() as any,
|
||||
new FakeCommandResultPresenter() as any,
|
||||
new FakeAuthSessionPresenter() as any,
|
||||
@@ -165,6 +169,7 @@ describe('AuthService', () => {
|
||||
{ execute: vi.fn() } as any,
|
||||
{ execute: vi.fn() } as any,
|
||||
{ execute: vi.fn() } as any,
|
||||
{ execute: vi.fn() } as any,
|
||||
authSessionPresenter as any,
|
||||
new FakeCommandResultPresenter() as any,
|
||||
new FakeAuthSessionPresenter() as any,
|
||||
@@ -196,6 +201,7 @@ describe('AuthService', () => {
|
||||
{ execute: vi.fn() } as any,
|
||||
{ execute: vi.fn() } as any,
|
||||
{ execute: vi.fn() } as any,
|
||||
{ execute: vi.fn() } as any,
|
||||
new FakeAuthSessionPresenter() as any,
|
||||
new FakeCommandResultPresenter() as any,
|
||||
new FakeAuthSessionPresenter() as any,
|
||||
@@ -214,6 +220,7 @@ describe('AuthService', () => {
|
||||
{ execute: vi.fn() } as any,
|
||||
{ execute: vi.fn() } as any,
|
||||
{ execute: vi.fn() } as any,
|
||||
{ execute: vi.fn() } as any,
|
||||
new FakeAuthSessionPresenter() as any,
|
||||
new FakeCommandResultPresenter() as any,
|
||||
new FakeAuthSessionPresenter() as any,
|
||||
@@ -237,6 +244,7 @@ describe('AuthService', () => {
|
||||
{ getCurrentSession: vi.fn(), createSession: vi.fn() } as any,
|
||||
{ execute: vi.fn() } as any,
|
||||
{ execute: vi.fn() } as any,
|
||||
{ execute: vi.fn() } as any,
|
||||
logoutUseCase as any,
|
||||
{ execute: vi.fn() } as any,
|
||||
{ execute: vi.fn() } as any,
|
||||
@@ -255,6 +263,7 @@ describe('AuthService', () => {
|
||||
{ getCurrentSession: vi.fn(), createSession: vi.fn() } as any,
|
||||
{ execute: vi.fn() } as any,
|
||||
{ execute: vi.fn() } as any,
|
||||
{ execute: vi.fn() } as any,
|
||||
{ execute: vi.fn(async () => Result.err({ code: 'REPOSITORY_ERROR' } as any)) } as any,
|
||||
{ execute: vi.fn() } as any,
|
||||
{ execute: vi.fn() } as any,
|
||||
|
||||
@@ -13,6 +13,11 @@ import {
|
||||
type SignupApplicationError,
|
||||
type SignupInput,
|
||||
} from '@core/identity/application/use-cases/SignupUseCase';
|
||||
import {
|
||||
SignupSponsorUseCase,
|
||||
type SignupSponsorApplicationError,
|
||||
type SignupSponsorInput,
|
||||
} from '@core/identity/application/use-cases/SignupSponsorUseCase';
|
||||
import {
|
||||
ForgotPasswordUseCase,
|
||||
type ForgotPasswordApplicationError,
|
||||
@@ -36,11 +41,12 @@ import {
|
||||
LOGIN_USE_CASE_TOKEN,
|
||||
LOGOUT_USE_CASE_TOKEN,
|
||||
SIGNUP_USE_CASE_TOKEN,
|
||||
SIGNUP_SPONSOR_USE_CASE_TOKEN,
|
||||
FORGOT_PASSWORD_USE_CASE_TOKEN,
|
||||
RESET_PASSWORD_USE_CASE_TOKEN,
|
||||
} from './AuthProviders';
|
||||
import type { AuthSessionDTO } from './dtos/AuthDto';
|
||||
import { LoginParamsDTO, SignupParamsDTO } from './dtos/AuthDto';
|
||||
import { LoginParamsDTO, SignupParamsDTO, SignupSponsorParamsDTO } from './dtos/AuthDto';
|
||||
import { AuthSessionPresenter } from './presenters/AuthSessionPresenter';
|
||||
import type { CommandResultDTO } from './presenters/CommandResultPresenter';
|
||||
import { CommandResultPresenter } from './presenters/CommandResultPresenter';
|
||||
@@ -72,6 +78,7 @@ export class AuthService {
|
||||
private readonly identitySessionPort: IdentitySessionPort,
|
||||
@Inject(LOGIN_USE_CASE_TOKEN) private readonly loginUseCase: LoginUseCase,
|
||||
@Inject(SIGNUP_USE_CASE_TOKEN) private readonly signupUseCase: SignupUseCase,
|
||||
@Inject(SIGNUP_SPONSOR_USE_CASE_TOKEN) private readonly signupSponsorUseCase: SignupSponsorUseCase,
|
||||
@Inject(LOGOUT_USE_CASE_TOKEN) private readonly logoutUseCase: LogoutUseCase,
|
||||
@Inject(FORGOT_PASSWORD_USE_CASE_TOKEN) private readonly forgotPasswordUseCase: ForgotPasswordUseCase,
|
||||
@Inject(RESET_PASSWORD_USE_CASE_TOKEN) private readonly resetPasswordUseCase: ResetPasswordUseCase,
|
||||
@@ -139,6 +146,40 @@ export class AuthService {
|
||||
};
|
||||
}
|
||||
|
||||
async signupSponsor(params: SignupSponsorParamsDTO): Promise<AuthSessionDTO> {
|
||||
this.logger.debug(`[AuthService] Attempting sponsor signup for email: ${params.email}`);
|
||||
|
||||
this.authSessionPresenter.reset();
|
||||
|
||||
const input: SignupSponsorInput = {
|
||||
email: params.email,
|
||||
password: params.password,
|
||||
displayName: params.displayName,
|
||||
companyName: params.companyName,
|
||||
};
|
||||
|
||||
const result = await this.signupSponsorUseCase.execute(input);
|
||||
|
||||
if (result.isErr()) {
|
||||
const error = result.unwrapErr() as SignupSponsorApplicationError;
|
||||
throw new Error(mapApplicationErrorToMessage(error, 'Sponsor signup failed'));
|
||||
}
|
||||
|
||||
const userDTO = this.authSessionPresenter.responseModel;
|
||||
const inferredRole = inferDemoRoleFromEmail(userDTO.email);
|
||||
const session = await this.identitySessionPort.createSession({
|
||||
id: userDTO.userId,
|
||||
displayName: userDTO.displayName,
|
||||
email: userDTO.email,
|
||||
...(inferredRole ? { role: inferredRole } : {}),
|
||||
});
|
||||
|
||||
return {
|
||||
token: session.token,
|
||||
user: userDTO,
|
||||
};
|
||||
}
|
||||
|
||||
async loginWithEmail(params: LoginParamsDTO): Promise<AuthSessionDTO> {
|
||||
this.logger.debug(`[AuthService] Attempting login for email: ${params.email}`);
|
||||
|
||||
|
||||
@@ -12,6 +12,8 @@ export class AuthenticatedUserDTO {
|
||||
primaryDriverId?: string;
|
||||
@ApiProperty({ required: false, nullable: true })
|
||||
avatarUrl?: string | null;
|
||||
@ApiProperty({ required: false })
|
||||
companyId?: string;
|
||||
@ApiProperty({ required: false, enum: ['driver', 'sponsor', 'league-owner', 'league-steward', 'league-admin', 'system-owner', 'super-admin'] })
|
||||
role?: 'driver' | 'sponsor' | 'league-owner' | 'league-steward' | 'league-admin' | 'system-owner' | 'super-admin';
|
||||
}
|
||||
@@ -48,6 +50,27 @@ export class SignupParamsDTO {
|
||||
avatarUrl?: string | null;
|
||||
}
|
||||
|
||||
export class SignupSponsorParamsDTO {
|
||||
@ApiProperty()
|
||||
@IsEmail()
|
||||
email!: string;
|
||||
|
||||
@ApiProperty()
|
||||
@IsString()
|
||||
@MinLength(8)
|
||||
password!: string;
|
||||
|
||||
@ApiProperty()
|
||||
@IsString()
|
||||
@MinLength(2)
|
||||
displayName!: string;
|
||||
|
||||
@ApiProperty()
|
||||
@IsString()
|
||||
@MinLength(2)
|
||||
companyName!: string;
|
||||
}
|
||||
|
||||
export class LoginParamsDTO {
|
||||
@ApiProperty()
|
||||
@IsEmail()
|
||||
|
||||
@@ -2,8 +2,9 @@ import type { UseCaseOutputPort } from '@core/shared/application/UseCaseOutputPo
|
||||
import { AuthenticatedUserDTO } from '../dtos/AuthDto';
|
||||
import type { LoginResult } from '@core/identity/application/use-cases/LoginUseCase';
|
||||
import type { SignupResult } from '@core/identity/application/use-cases/SignupUseCase';
|
||||
import type { SignupSponsorResult } from '@core/identity/application/use-cases/SignupSponsorUseCase';
|
||||
|
||||
type AuthSessionResult = LoginResult | SignupResult;
|
||||
type AuthSessionResult = LoginResult | SignupResult | SignupSponsorResult;
|
||||
|
||||
export class AuthSessionPresenter implements UseCaseOutputPort<AuthSessionResult> {
|
||||
private model: AuthenticatedUserDTO | null = null;
|
||||
@@ -15,12 +16,14 @@ export class AuthSessionPresenter implements UseCaseOutputPort<AuthSessionResult
|
||||
present(result: AuthSessionResult): void {
|
||||
const primaryDriverId = result.user.getPrimaryDriverId();
|
||||
const avatarUrl = result.user.getAvatarUrl();
|
||||
const companyId = result.user.getCompanyId();
|
||||
this.model = {
|
||||
userId: result.user.getId().value,
|
||||
email: result.user.getEmail() ?? '',
|
||||
displayName: result.user.getDisplayName() ?? '',
|
||||
...(primaryDriverId !== undefined ? { primaryDriverId } : {}),
|
||||
...(avatarUrl !== undefined ? { avatarUrl } : {}),
|
||||
...(companyId !== undefined ? { companyId } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
export const AUTH_REPOSITORY_TOKEN = 'IAuthRepository';
|
||||
export const USER_REPOSITORY_TOKEN = 'IUserRepository';
|
||||
export const PASSWORD_HASHING_SERVICE_TOKEN = 'IPasswordHashingService';
|
||||
export const MAGIC_LINK_REPOSITORY_TOKEN = 'IMagicLinkRepository';
|
||||
export const MAGIC_LINK_REPOSITORY_TOKEN = 'IMagicLinkRepository';
|
||||
export const COMPANY_REPOSITORY_TOKEN = 'ICompanyRepository';
|
||||
@@ -10,8 +10,9 @@ import { InMemoryAuthRepository } from '@adapters/identity/persistence/inmemory/
|
||||
import { InMemoryUserRepository } from '@adapters/identity/persistence/inmemory/InMemoryUserRepository';
|
||||
import { InMemoryPasswordHashingService } from '@adapters/identity/services/InMemoryPasswordHashingService';
|
||||
import { InMemoryMagicLinkRepository } from '@adapters/identity/persistence/inmemory/InMemoryMagicLinkRepository';
|
||||
import { InMemoryCompanyRepository } from '@adapters/identity/persistence/inmemory/InMemoryCompanyRepository';
|
||||
|
||||
import { AUTH_REPOSITORY_TOKEN, PASSWORD_HASHING_SERVICE_TOKEN, USER_REPOSITORY_TOKEN, MAGIC_LINK_REPOSITORY_TOKEN } from '../identity/IdentityPersistenceTokens';
|
||||
import { AUTH_REPOSITORY_TOKEN, PASSWORD_HASHING_SERVICE_TOKEN, USER_REPOSITORY_TOKEN, MAGIC_LINK_REPOSITORY_TOKEN, COMPANY_REPOSITORY_TOKEN } from '../identity/IdentityPersistenceTokens';
|
||||
|
||||
@Module({
|
||||
imports: [LoggingModule],
|
||||
@@ -48,7 +49,11 @@ import { AUTH_REPOSITORY_TOKEN, PASSWORD_HASHING_SERVICE_TOKEN, USER_REPOSITORY_
|
||||
useFactory: (logger: Logger) => new InMemoryMagicLinkRepository(logger),
|
||||
inject: ['Logger'],
|
||||
},
|
||||
{
|
||||
provide: COMPANY_REPOSITORY_TOKEN,
|
||||
useClass: InMemoryCompanyRepository,
|
||||
},
|
||||
],
|
||||
exports: [USER_REPOSITORY_TOKEN, AUTH_REPOSITORY_TOKEN, PASSWORD_HASHING_SERVICE_TOKEN, MAGIC_LINK_REPOSITORY_TOKEN],
|
||||
exports: [USER_REPOSITORY_TOKEN, AUTH_REPOSITORY_TOKEN, PASSWORD_HASHING_SERVICE_TOKEN, MAGIC_LINK_REPOSITORY_TOKEN, COMPANY_REPOSITORY_TOKEN],
|
||||
})
|
||||
export class InMemoryIdentityPersistenceModule {}
|
||||
@@ -4,11 +4,14 @@ import type { DataSource } from 'typeorm';
|
||||
import type { Logger } from '@core/shared/application/Logger';
|
||||
|
||||
import { UserOrmEntity } from '@adapters/identity/persistence/typeorm/entities/UserOrmEntity';
|
||||
import { CompanyOrmEntity } from '@adapters/identity/persistence/typeorm/entities/CompanyOrmEntity';
|
||||
import { PasswordResetRequestOrmEntity } from '@adapters/identity/persistence/typeorm/entities/PasswordResetRequestOrmEntity';
|
||||
import { TypeOrmAuthRepository } from '@adapters/identity/persistence/typeorm/repositories/TypeOrmAuthRepository';
|
||||
import { TypeOrmUserRepository } from '@adapters/identity/persistence/typeorm/repositories/TypeOrmUserRepository';
|
||||
import { TypeOrmMagicLinkRepository } from '@adapters/identity/persistence/typeorm/repositories/TypeOrmMagicLinkRepository';
|
||||
import { TypeOrmCompanyRepository } from '@adapters/identity/persistence/typeorm/repositories/TypeOrmCompanyRepository';
|
||||
import { UserOrmMapper } from '@adapters/identity/persistence/typeorm/mappers/UserOrmMapper';
|
||||
import { CompanyOrmMapper } from '@adapters/identity/persistence/typeorm/mappers/CompanyOrmMapper';
|
||||
import { InMemoryPasswordHashingService } from '@adapters/identity/services/InMemoryPasswordHashingService';
|
||||
|
||||
import {
|
||||
@@ -16,9 +19,10 @@ import {
|
||||
PASSWORD_HASHING_SERVICE_TOKEN,
|
||||
USER_REPOSITORY_TOKEN,
|
||||
MAGIC_LINK_REPOSITORY_TOKEN,
|
||||
COMPANY_REPOSITORY_TOKEN,
|
||||
} from '../identity/IdentityPersistenceTokens';
|
||||
|
||||
const typeOrmFeatureImports = [TypeOrmModule.forFeature([UserOrmEntity, PasswordResetRequestOrmEntity])];
|
||||
const typeOrmFeatureImports = [TypeOrmModule.forFeature([UserOrmEntity, CompanyOrmEntity, PasswordResetRequestOrmEntity])];
|
||||
|
||||
@Module({
|
||||
imports: [...typeOrmFeatureImports],
|
||||
@@ -43,7 +47,13 @@ const typeOrmFeatureImports = [TypeOrmModule.forFeature([UserOrmEntity, Password
|
||||
useFactory: (dataSource: DataSource, logger: Logger) => new TypeOrmMagicLinkRepository(dataSource, logger),
|
||||
inject: [getDataSourceToken(), 'Logger'],
|
||||
},
|
||||
{
|
||||
provide: COMPANY_REPOSITORY_TOKEN,
|
||||
useFactory: (dataSource: DataSource, mapper: CompanyOrmMapper) => new TypeOrmCompanyRepository(dataSource, mapper),
|
||||
inject: [getDataSourceToken(), CompanyOrmMapper],
|
||||
},
|
||||
{ provide: CompanyOrmMapper, useFactory: () => new CompanyOrmMapper() },
|
||||
],
|
||||
exports: [USER_REPOSITORY_TOKEN, AUTH_REPOSITORY_TOKEN, PASSWORD_HASHING_SERVICE_TOKEN, MAGIC_LINK_REPOSITORY_TOKEN],
|
||||
exports: [USER_REPOSITORY_TOKEN, AUTH_REPOSITORY_TOKEN, PASSWORD_HASHING_SERVICE_TOKEN, MAGIC_LINK_REPOSITORY_TOKEN, COMPANY_REPOSITORY_TOKEN],
|
||||
})
|
||||
export class PostgresIdentityPersistenceModule {}
|
||||
File diff suppressed because it is too large
Load Diff
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