2024-03-24 23:41:23 +01:00
|
|
|
import type { User } from "../entities/User"
|
|
|
|
import { UserLoginSchema, UserRegisterSchema } from "../entities/User"
|
2024-03-22 23:41:51 +01:00
|
|
|
import type { AuthenticationRepository } from "../repositories/Authentication"
|
|
|
|
|
|
|
|
export interface AuthenticationUseCaseDependencyOptions {
|
|
|
|
authenticationRepository: AuthenticationRepository
|
|
|
|
}
|
|
|
|
|
|
|
|
export class AuthenticationUseCase
|
|
|
|
implements AuthenticationUseCaseDependencyOptions
|
|
|
|
{
|
|
|
|
public authenticationRepository: AuthenticationRepository
|
|
|
|
|
|
|
|
public constructor(options: AuthenticationUseCaseDependencyOptions) {
|
|
|
|
this.authenticationRepository = options.authenticationRepository
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Register a new user.
|
|
|
|
* @throws {ZodError} if the data is invalid.
|
|
|
|
* @throws {Error} if user already exists.
|
|
|
|
* @param data
|
|
|
|
* @returns
|
|
|
|
*/
|
|
|
|
public async register(data: unknown): Promise<User> {
|
|
|
|
const userData = await UserRegisterSchema.parseAsync(data)
|
|
|
|
return await this.authenticationRepository.register(userData)
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Login a user.
|
|
|
|
* @throws {ZodError} if the data is invalid.
|
|
|
|
* @throws {Error} if invalid credentials.
|
|
|
|
* @param data
|
|
|
|
* @returns
|
|
|
|
*/
|
|
|
|
public async login(data: unknown): Promise<User> {
|
|
|
|
const userData = await UserLoginSchema.parseAsync(data)
|
|
|
|
return await this.authenticationRepository.login(userData)
|
|
|
|
}
|
|
|
|
|
2024-03-24 23:41:23 +01:00
|
|
|
public logout: AuthenticationRepository["logout"] = async () => {
|
2024-03-22 23:41:51 +01:00
|
|
|
return await this.authenticationRepository.logout()
|
|
|
|
}
|
|
|
|
|
2024-03-24 23:41:23 +01:00
|
|
|
public getUser: AuthenticationRepository["getUser"] = async () => {
|
|
|
|
return await this.authenticationRepository.getUser()
|
2024-03-22 23:41:51 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
public onUserStateChange: AuthenticationRepository["onUserStateChange"] =
|
2024-03-24 23:41:23 +01:00
|
|
|
async (callback) => {
|
|
|
|
return this.authenticationRepository.onUserStateChange(callback)
|
2024-03-22 23:41:51 +01:00
|
|
|
}
|
|
|
|
}
|