106 lines
2.9 KiB
TypeScript
106 lines
2.9 KiB
TypeScript
import { AxiosError } from "axios";
|
|
|
|
import {
|
|
ACCESS_TOKEN,
|
|
AUTH_USER_ID,
|
|
CLAIM_NAME,
|
|
ENDPOINT,
|
|
} from "@/shared/config";
|
|
import { getCookie } from "@/shared/lib";
|
|
import { getRemainingMs } from "@common/auth";
|
|
|
|
import { clearAuthToken, setToken, setupRefreshTimer } from "../lib/token-manager";
|
|
import type { ILogin,LoginService } from "../model/login-interface";
|
|
|
|
import { clearTabStorePersist } from "@/store/tab-store";
|
|
|
|
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<void> {
|
|
try {
|
|
const response = await fetch(`/api/proxy${ENDPOINT.USER_SERVICE.LOGIN}`, {
|
|
method: "POST",
|
|
headers: { "Content-Type": "application/json" },
|
|
body: JSON.stringify(payload),
|
|
});
|
|
|
|
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");
|
|
}
|
|
|
|
const prevTokenId = getCookie(AUTH_USER_ID);
|
|
if (prevTokenId !== undefined && prevTokenId !== tokenId) {
|
|
clearTabStorePersist();
|
|
}
|
|
|
|
setToken(CLAIM_NAME, accessToken);
|
|
setToken(AUTH_USER_ID, tokenId);
|
|
|
|
const remainingMs = getRemainingMs(accessToken);
|
|
if (remainingMs > 0) {
|
|
setupRefreshTimer(
|
|
() => this.silentRefresh(),
|
|
remainingMs,
|
|
);
|
|
}
|
|
} catch (error) {
|
|
if (error instanceof AxiosError) {
|
|
throw new Error(`Login failed: ${error.response?.data?.message}`);
|
|
}
|
|
throw new Error(`Login failed: ${error}`);
|
|
}
|
|
}
|
|
|
|
public async silentRefresh(): Promise<void> {
|
|
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");
|
|
}
|
|
|
|
setToken(CLAIM_NAME, accessToken);
|
|
setToken(AUTH_USER_ID, tokenId);
|
|
|
|
const remainingMs = getRemainingMs(accessToken);
|
|
if (remainingMs > 0) {
|
|
setupRefreshTimer(
|
|
() => this.silentRefresh(),
|
|
remainingMs,
|
|
);
|
|
}
|
|
} catch (error) {
|
|
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();
|