refactor(api): replace new Logger() with DI LoggerService and split large files
- Migrate 30 files from `new Logger(ClassName.name)` to injected LoggerService for consistent PII masking and centralized logging config - Split prisma-admin-query.repository.ts (313→121 lines) into admin-stats.queries.ts and admin-user.queries.ts - Split admin.controller.ts (285→154 lines) into admin-moderation.controller.ts - Split prisma-listing.repository.ts (274→111 lines) into listing-read.queries.ts - Update 28 test files with mock LoggerService - All 831 tests passing, zero direct new Logger() calls remaining Co-Authored-By: Paperclip <noreply@paperclip.ing>
This commit is contained in:
@@ -73,11 +73,14 @@ describe('OAuthService', () => {
|
||||
|
||||
mockEventBus = { publish: vi.fn() };
|
||||
|
||||
const mockLogger = { log: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn(), verbose: vi.fn() };
|
||||
|
||||
service = new OAuthService(
|
||||
mockUserRepo as any,
|
||||
mockTokenService as any,
|
||||
mockPrisma as any,
|
||||
mockEventBus as any,
|
||||
mockLogger as any,
|
||||
);
|
||||
});
|
||||
|
||||
|
||||
@@ -21,7 +21,8 @@ describe('ZaloOAuthStrategy', () => {
|
||||
authenticateOAuth: vi.fn().mockResolvedValue(mockTokenPair),
|
||||
};
|
||||
|
||||
strategy = new ZaloOAuthStrategy(mockOAuthService as unknown as OAuthService);
|
||||
const mockLogger = { log: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn(), verbose: vi.fn() };
|
||||
strategy = new ZaloOAuthStrategy(mockOAuthService as unknown as OAuthService, mockLogger as any);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
@@ -31,13 +32,15 @@ describe('ZaloOAuthStrategy', () => {
|
||||
|
||||
it('throws if ZALO_APP_ID is missing', () => {
|
||||
vi.stubEnv('ZALO_APP_ID', '');
|
||||
expect(() => new ZaloOAuthStrategy(mockOAuthService as unknown as OAuthService))
|
||||
const mockLogger = { log: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn(), verbose: vi.fn() };
|
||||
expect(() => new ZaloOAuthStrategy(mockOAuthService as unknown as OAuthService, mockLogger as any))
|
||||
.toThrow('ZALO_APP_ID');
|
||||
});
|
||||
|
||||
it('throws if ZALO_APP_SECRET is missing', () => {
|
||||
vi.stubEnv('ZALO_APP_SECRET', '');
|
||||
expect(() => new ZaloOAuthStrategy(mockOAuthService as unknown as OAuthService))
|
||||
const mockLogger = { log: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn(), verbose: vi.fn() };
|
||||
expect(() => new ZaloOAuthStrategy(mockOAuthService as unknown as OAuthService, mockLogger as any))
|
||||
.toThrow('ZALO_APP_SECRET');
|
||||
});
|
||||
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import { Inject, Injectable, Logger } from '@nestjs/common';
|
||||
import { Inject, Injectable } from '@nestjs/common';
|
||||
import { type EventBus } from '@nestjs/cqrs';
|
||||
import { createId } from '@paralleldrive/cuid2';
|
||||
import { type OAuthProvider, type Prisma } from '@prisma/client';
|
||||
import { type PrismaService } from '@modules/shared';
|
||||
import { type PrismaService, type LoggerService } from '@modules/shared';
|
||||
import { UserEntity } from '../../domain/entities/user.entity';
|
||||
import { UserRegisteredEvent } from '../../domain/events/user-registered.event';
|
||||
import { USER_REPOSITORY, type IUserRepository } from '../../domain/repositories/user.repository';
|
||||
@@ -25,13 +25,12 @@ export interface OAuthUserProfile {
|
||||
|
||||
@Injectable()
|
||||
export class OAuthService {
|
||||
private readonly logger = new Logger(OAuthService.name);
|
||||
|
||||
constructor(
|
||||
@Inject(USER_REPOSITORY) private readonly userRepo: IUserRepository,
|
||||
private readonly tokenService: TokenService,
|
||||
private readonly prisma: PrismaService,
|
||||
private readonly eventBus: EventBus,
|
||||
private readonly logger: LoggerService,
|
||||
) {}
|
||||
|
||||
/**
|
||||
@@ -66,7 +65,7 @@ export class OAuthService {
|
||||
throw new Error('Tài khoản đã bị vô hiệu hóa');
|
||||
}
|
||||
|
||||
this.logger.log(`OAuth login: existing account for ${profile.provider}/${profile.providerUserId}`);
|
||||
this.logger.log(`OAuth login: existing account for ${profile.provider}/${profile.providerUserId}`, 'OAuthService');
|
||||
return this.generateTokensForUser(existingOAuth.user);
|
||||
}
|
||||
|
||||
@@ -78,7 +77,7 @@ export class OAuthService {
|
||||
throw new Error('Tài khoản đã bị vô hiệu hóa');
|
||||
}
|
||||
await this.createOAuthAccount(existingUser.id, profile);
|
||||
this.logger.log(`OAuth link: linked ${profile.provider} to existing user by email`);
|
||||
this.logger.log(`OAuth link: linked ${profile.provider} to existing user by email`, 'OAuthService');
|
||||
return this.generateTokensForUser({
|
||||
id: existingUser.id,
|
||||
phone: existingUser.phone.value,
|
||||
@@ -97,7 +96,7 @@ export class OAuthService {
|
||||
throw new Error('Tài khoản đã bị vô hiệu hóa');
|
||||
}
|
||||
await this.createOAuthAccount(existingUser.id, profile);
|
||||
this.logger.log(`OAuth link: linked ${profile.provider} to existing user by phone`);
|
||||
this.logger.log(`OAuth link: linked ${profile.provider} to existing user by phone`, 'OAuthService');
|
||||
return this.generateTokensForUser({
|
||||
id: existingUser.id,
|
||||
phone: existingUser.phone.value,
|
||||
@@ -130,7 +129,7 @@ export class OAuthService {
|
||||
// Publish domain event
|
||||
this.eventBus.publish(new UserRegisteredEvent(userId, phone.value, 'BUYER'));
|
||||
|
||||
this.logger.log(`OAuth register: new user created via ${profile.provider}`);
|
||||
this.logger.log(`OAuth register: new user created via ${profile.provider}`, 'OAuthService');
|
||||
return this.generateTokensForUser({
|
||||
id: userId,
|
||||
phone: phone.value,
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { Injectable, Logger } from '@nestjs/common';
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { type LoggerService } from '@modules/shared';
|
||||
import { type OAuthService, type OAuthUserProfile } from '../services/oauth.service';
|
||||
import { type TokenPair } from '../services/token.service';
|
||||
|
||||
@@ -36,13 +37,14 @@ interface ZaloUserInfo {
|
||||
|
||||
@Injectable()
|
||||
export class ZaloOAuthStrategy {
|
||||
private readonly logger = new Logger(ZaloOAuthStrategy.name);
|
||||
|
||||
private readonly appId: string;
|
||||
private readonly appSecret: string;
|
||||
private readonly callbackUrl: string;
|
||||
|
||||
constructor(private readonly oauthService: OAuthService) {
|
||||
constructor(
|
||||
private readonly oauthService: OAuthService,
|
||||
private readonly logger: LoggerService,
|
||||
) {
|
||||
const appId = process.env['ZALO_APP_ID'];
|
||||
const appSecret = process.env['ZALO_APP_SECRET'];
|
||||
|
||||
@@ -119,7 +121,7 @@ export class ZaloOAuthStrategy {
|
||||
const data = (await response.json()) as ZaloTokenResponse;
|
||||
|
||||
if (data.error) {
|
||||
this.logger.error(`Zalo token exchange failed: ${data.error_description ?? data.error}`);
|
||||
this.logger.error(`Zalo token exchange failed: ${data.error_description ?? data.error}`, undefined, 'ZaloOAuthStrategy');
|
||||
throw new Error(`Zalo OAuth error: ${data.error_description ?? 'Token exchange failed'}`);
|
||||
}
|
||||
|
||||
@@ -143,7 +145,7 @@ export class ZaloOAuthStrategy {
|
||||
const data = (await response.json()) as ZaloUserInfo;
|
||||
|
||||
if (data.error) {
|
||||
this.logger.error(`Zalo user info fetch failed: ${data.message ?? data.error}`);
|
||||
this.logger.error(`Zalo user info fetch failed: ${data.message ?? data.error}`, undefined, 'ZaloOAuthStrategy');
|
||||
throw new Error(`Zalo OAuth error: ${data.message ?? 'Failed to fetch user info'}`);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,13 +1,15 @@
|
||||
import { Injectable, Logger, type CanActivate, type ExecutionContext } from '@nestjs/common';
|
||||
import { Injectable, type CanActivate, type ExecutionContext } from '@nestjs/common';
|
||||
import { type Reflector } from '@nestjs/core';
|
||||
import { type UserRole } from '@prisma/client';
|
||||
import { type LoggerService } from '@modules/shared';
|
||||
import { ROLES_KEY } from '../decorators/roles.decorator';
|
||||
|
||||
@Injectable()
|
||||
export class RolesGuard implements CanActivate {
|
||||
private readonly logger = new Logger(RolesGuard.name);
|
||||
|
||||
constructor(private readonly reflector: Reflector) {}
|
||||
constructor(
|
||||
private readonly reflector: Reflector,
|
||||
private readonly logger: LoggerService,
|
||||
) {}
|
||||
|
||||
canActivate(context: ExecutionContext): boolean {
|
||||
const requiredRoles = this.reflector.getAllAndOverride<UserRole[]>(ROLES_KEY, [
|
||||
@@ -30,6 +32,7 @@ export class RolesGuard implements CanActivate {
|
||||
this.logger.warn(
|
||||
`Access denied: userId=${user?.sub ?? 'unknown'}, role=${user?.role ?? 'none'}, ` +
|
||||
`required=${requiredRoles.join(',')}, action=${controller}.${handler}, ip=${ip}`,
|
||||
'RolesGuard',
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user