refactor
This commit is contained in:
@@ -1,40 +1,33 @@
|
||||
import { Inject, Injectable, InternalServerErrorException } from '@nestjs/common';
|
||||
import { Inject, Injectable } from '@nestjs/common';
|
||||
|
||||
// Core Use Cases
|
||||
import { LoginUseCase } from '@core/identity/application/use-cases/LoginUseCase';
|
||||
import { LoginUseCase, type LoginInput } 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 { SignupUseCase, type SignupInput } from '@core/identity/application/use-cases/SignupUseCase';
|
||||
|
||||
// Core Interfaces and Tokens
|
||||
import { AuthenticatedUserDTO as CoreAuthenticatedUserDTO } from '@core/identity/application/dto/AuthenticatedUserDTO';
|
||||
import { IdentitySessionPort } from '@core/identity/application/ports/IdentitySessionPort';
|
||||
import { User } from '@core/identity/domain/entities/User';
|
||||
import type { IAuthRepository } from '@core/identity/domain/repositories/IAuthRepository';
|
||||
import type { IUserRepository } from '@core/identity/domain/repositories/IUserRepository';
|
||||
import type { IPasswordHashingService } from '@core/identity/domain/services/PasswordHashingService';
|
||||
import type { Logger } from "@core/shared/application";
|
||||
import { AUTH_REPOSITORY_TOKEN, IDENTITY_SESSION_PORT_TOKEN, LOGGER_TOKEN, PASSWORD_HASHING_SERVICE_TOKEN, USER_REPOSITORY_TOKEN } from './AuthProviders';
|
||||
import { AuthSessionDTO, LoginParams, SignupParams, AuthenticatedUserDTO } from './dtos/AuthDto';
|
||||
import type { Logger } from '@core/shared/application';
|
||||
import { IDENTITY_SESSION_PORT_TOKEN, LOGGER_TOKEN, LOGIN_USE_CASE_TOKEN, LOGOUT_USE_CASE_TOKEN, SIGNUP_USE_CASE_TOKEN, USER_REPOSITORY_TOKEN } from './AuthProviders';
|
||||
import { AuthenticatedUserDTO, AuthSessionDTO, LoginParams, SignupParams } from './dtos/AuthDto';
|
||||
import { AuthSessionPresenter } from './presenters/AuthSessionPresenter';
|
||||
import type { CommandResultDTO } from './presenters/CommandResultPresenter';
|
||||
import { CommandResultPresenter } from './presenters/CommandResultPresenter';
|
||||
|
||||
@Injectable()
|
||||
export class AuthService {
|
||||
private readonly loginUseCase: LoginUseCase;
|
||||
private readonly signupUseCase: SignupUseCase;
|
||||
private readonly logoutUseCase: LogoutUseCase;
|
||||
|
||||
constructor(
|
||||
@Inject(AUTH_REPOSITORY_TOKEN) private authRepository: IAuthRepository,
|
||||
@Inject(PASSWORD_HASHING_SERVICE_TOKEN) private passwordHashingService: IPasswordHashingService,
|
||||
@Inject(LOGGER_TOKEN) private logger: Logger,
|
||||
@Inject(IDENTITY_SESSION_PORT_TOKEN) private identitySessionPort: IdentitySessionPort,
|
||||
@Inject(USER_REPOSITORY_TOKEN) private userRepository: IUserRepository, // Inject IUserRepository here
|
||||
) {
|
||||
this.loginUseCase = new LoginUseCase(this.authRepository, this.passwordHashingService);
|
||||
this.signupUseCase = new SignupUseCase(this.authRepository, this.passwordHashingService);
|
||||
this.logoutUseCase = new LogoutUseCase(this.identitySessionPort);
|
||||
}
|
||||
@Inject(USER_REPOSITORY_TOKEN) private userRepository: IUserRepository,
|
||||
@Inject(LOGIN_USE_CASE_TOKEN) private readonly loginUseCase: LoginUseCase,
|
||||
@Inject(SIGNUP_USE_CASE_TOKEN) private readonly signupUseCase: SignupUseCase,
|
||||
@Inject(LOGOUT_USE_CASE_TOKEN) private readonly logoutUseCase: LogoutUseCase,
|
||||
private readonly authSessionPresenter: AuthSessionPresenter,
|
||||
private readonly commandResultPresenter: CommandResultPresenter,
|
||||
) {}
|
||||
|
||||
private mapUserToAuthenticatedUserDTO(user: User): AuthenticatedUserDTO {
|
||||
return {
|
||||
@@ -44,74 +37,109 @@ export class AuthService {
|
||||
};
|
||||
}
|
||||
|
||||
private mapToCoreAuthenticatedUserDTO(apiDto: AuthenticatedUserDTO): CoreAuthenticatedUserDTO {
|
||||
|
||||
private buildAuthSessionDTO(token: string, user: AuthenticatedUserDTO): AuthSessionDTO {
|
||||
return {
|
||||
id: apiDto.userId,
|
||||
displayName: apiDto.displayName,
|
||||
email: apiDto.email,
|
||||
token,
|
||||
user: {
|
||||
userId: user.userId,
|
||||
email: user.email,
|
||||
displayName: user.displayName,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async getCurrentSession(): Promise<AuthSessionPresenter | null> {
|
||||
async getCurrentSession(): Promise<AuthSessionDTO | null> {
|
||||
this.logger.debug('[AuthService] Attempting to get current session.');
|
||||
const coreSession = await this.identitySessionPort.getCurrentSession();
|
||||
if (!coreSession) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const user = await this.userRepository.findById(coreSession.user.id); // Use userRepository to fetch full user
|
||||
const user = await this.userRepository.findById(coreSession.user.id);
|
||||
if (!user) {
|
||||
// If session exists but user doesn't in DB, perhaps clear session?
|
||||
this.logger.warn(`[AuthService] Session found for user ID ${coreSession.user.id}, but user not found in repository.`);
|
||||
await this.identitySessionPort.clearSession(); // Clear potentially stale session
|
||||
this.logger.warn(
|
||||
`[AuthService] Session found for user ID ${coreSession.user.id}, but user not found in repository.`,
|
||||
);
|
||||
await this.identitySessionPort.clearSession();
|
||||
return null;
|
||||
}
|
||||
|
||||
const authenticatedUserDTO = this.mapUserToAuthenticatedUserDTO(User.fromStored(user));
|
||||
const apiSession = this.buildAuthSessionDTO(coreSession.token, authenticatedUserDTO);
|
||||
|
||||
const presenter = new AuthSessionPresenter();
|
||||
presenter.present({ token: coreSession.token, user: authenticatedUserDTO });
|
||||
return presenter;
|
||||
return apiSession;
|
||||
}
|
||||
|
||||
async signupWithEmail(params: SignupParams): Promise<AuthSessionPresenter> {
|
||||
async signupWithEmail(params: SignupParams): Promise<AuthSessionDTO> {
|
||||
this.logger.debug(`[AuthService] Attempting signup for email: ${params.email}`);
|
||||
const user = await this.signupUseCase.execute(params.email, params.password, params.displayName);
|
||||
|
||||
// Create session after successful signup
|
||||
const authenticatedUserDTO = this.mapUserToAuthenticatedUserDTO(user);
|
||||
const coreDto = this.mapToCoreAuthenticatedUserDTO(authenticatedUserDTO);
|
||||
const session = await this.identitySessionPort.createSession(coreDto);
|
||||
const input: SignupInput = {
|
||||
email: params.email,
|
||||
password: params.password,
|
||||
displayName: params.displayName,
|
||||
};
|
||||
|
||||
const presenter = new AuthSessionPresenter();
|
||||
presenter.present({ token: session.token, user: authenticatedUserDTO });
|
||||
return presenter;
|
||||
}
|
||||
const result = await this.signupUseCase.execute(input);
|
||||
|
||||
async loginWithEmail(params: LoginParams): Promise<AuthSessionPresenter> {
|
||||
this.logger.debug(`[AuthService] Attempting login for email: ${params.email}`);
|
||||
try {
|
||||
const user = await this.loginUseCase.execute(params.email, params.password);
|
||||
// Create session after successful login
|
||||
const authenticatedUserDTO = this.mapUserToAuthenticatedUserDTO(user);
|
||||
const coreDto = this.mapToCoreAuthenticatedUserDTO(authenticatedUserDTO);
|
||||
const session = await this.identitySessionPort.createSession(coreDto);
|
||||
|
||||
const presenter = new AuthSessionPresenter();
|
||||
presenter.present({ token: session.token, user: authenticatedUserDTO });
|
||||
return presenter;
|
||||
} catch (error) {
|
||||
this.logger.error(`[AuthService] Login failed for email ${params.email}:`, error instanceof Error ? error : new Error(String(error)));
|
||||
throw new InternalServerErrorException('Login failed due to invalid credentials or server error.');
|
||||
if (result.isErr()) {
|
||||
const error = result.unwrapErr();
|
||||
throw new Error(error.details?.message ?? 'Signup failed');
|
||||
}
|
||||
|
||||
const userDTO = this.authSessionPresenter.getResponseModel();
|
||||
const coreUserDTO = {
|
||||
id: userDTO.userId,
|
||||
displayName: userDTO.displayName,
|
||||
email: userDTO.email,
|
||||
};
|
||||
const session = await this.identitySessionPort.createSession(coreUserDTO);
|
||||
|
||||
return {
|
||||
token: session.token,
|
||||
user: userDTO,
|
||||
};
|
||||
}
|
||||
|
||||
async loginWithEmail(params: LoginParams): Promise<AuthSessionDTO> {
|
||||
this.logger.debug(`[AuthService] Attempting login for email: ${params.email}`);
|
||||
|
||||
async logout(): Promise<CommandResultPresenter> {
|
||||
const input: LoginInput = {
|
||||
email: params.email,
|
||||
password: params.password,
|
||||
};
|
||||
|
||||
const result = await this.loginUseCase.execute(input);
|
||||
|
||||
if (result.isErr()) {
|
||||
const error = result.unwrapErr();
|
||||
throw new Error(error.details?.message ?? 'Login failed');
|
||||
}
|
||||
|
||||
const userDTO = this.authSessionPresenter.getResponseModel();
|
||||
const coreUserDTO = {
|
||||
id: userDTO.userId,
|
||||
displayName: userDTO.displayName,
|
||||
email: userDTO.email,
|
||||
};
|
||||
const session = await this.identitySessionPort.createSession(coreUserDTO);
|
||||
|
||||
return {
|
||||
token: session.token,
|
||||
user: userDTO,
|
||||
};
|
||||
}
|
||||
|
||||
async logout(): Promise<CommandResultDTO> {
|
||||
this.logger.debug('[AuthService] Attempting logout.');
|
||||
const presenter = new CommandResultPresenter();
|
||||
await this.logoutUseCase.execute();
|
||||
presenter.present({ success: true });
|
||||
return presenter;
|
||||
|
||||
const result = await this.logoutUseCase.execute();
|
||||
|
||||
if (result.isErr()) {
|
||||
const error = result.unwrapErr();
|
||||
throw new Error(error.details?.message ?? 'Logout failed');
|
||||
}
|
||||
|
||||
return this.commandResultPresenter.getResponseModel();
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user