import { AxiosError } from "axios"; import { ACCESS_TOKEN, AUTH_USER_ID, CLAIM_NAME, ENDPOINT, JWT_EXPIRATION_TIME, } from "@/shared/config"; import { tokenManager } from "../lib/token-manager"; import type { ILogin, LoginService } from "../model/login-interface"; export class LoginApiService implements LoginService { private static instance: LoginApiService; private constructor() {} public static getInstance(): LoginApiService { if (!LoginApiService.instance) { LoginApiService.instance = new LoginApiService(); } return LoginApiService.instance; } public async login(payload: ILogin): Promise { try { const response = await fetch(`/api/proxy${ENDPOINT.USER_SERVICE.LOGIN}`, { method: "POST", body: JSON.stringify({ userId: payload.userId, password: payload.password, }), }); const data = await response.json(); console.log("data ", data); const accessToken = data[ACCESS_TOKEN]; const tokenId = data[AUTH_USER_ID]; if (!accessToken || !tokenId) { if (data.message == "Invalid Credentials") { throw new Error("아이디와 비밀번호가 일치하지 않습니다."); } else if (data.message == "User not found") { throw new Error("존재하지 않는 아이디입니다."); } else if (data.message == "User is not active") { throw new Error("활성화되지 않은 계정입니다."); } else if (data.message == "User is not verified") { throw new Error("이메일 인증이 필요합니다."); } else { throw new Error(data.message); } } tokenManager.setToken(CLAIM_NAME, accessToken); tokenManager.setToken(AUTH_USER_ID, tokenId); tokenManager.setupRefreshTimer(() => this.silentRefresh(), JWT_EXPIRATION_TIME); } catch (error) { if (error instanceof AxiosError) { throw new Error(`Login 실패 ${error.response?.data?.message}`); } throw new Error(`Login 실패 ${error}`); } } public async silentRefresh(): Promise { try { const response = await fetch(`/api/proxy${ENDPOINT.USER_SERVICE.SILENT_REFRESH}`, { method: "PUT", }); const data = await response.json(); const accessToken = data[ACCESS_TOKEN]; const tokenId = data[AUTH_USER_ID]; if (!accessToken || !tokenId) { throw new Error("Missing required authentication tokens"); } tokenManager.setToken(CLAIM_NAME, accessToken); tokenManager.setToken(AUTH_USER_ID, tokenId); } catch (error) { tokenManager.clearAuthToken(); if (error instanceof AxiosError) { throw new Error(`Silent refresh failed: ${error.response?.data?.message}`); } throw new Error(`Silent refresh failed: ${error}`); } } } export const LoginApi = LoginApiService.getInstance();