Refresh Token 저장 방식 변경

This commit is contained in:
static
2024-12-26 18:54:31 +09:00
parent a42f26bab1
commit b6fbd83d6f
5 changed files with 76 additions and 23 deletions

47
src/lib/hooks/callAPI.ts Normal file
View File

@@ -0,0 +1,47 @@
import { accessToken } from "$lib/stores/auth";
const refreshToken = async () => {
const res = await fetch("/api/auth/refreshtoken", {
method: "POST",
credentials: "same-origin",
});
if (!res.ok) {
accessToken.set(null);
throw new Error("Failed to refresh token");
}
const data = await res.json();
const token = data.accessToken as string;
accessToken.set(token);
return token;
};
const callAPIInternal = async (
input: RequestInfo,
init?: RequestInit,
token?: string | null,
retryIfUnauthorized = true,
): Promise<Response> => {
if (token === null) {
token = await refreshToken();
retryIfUnauthorized = false;
}
const res = await fetch(input, {
...init,
headers: {
...init?.headers,
Authorization: `Bearer ${token}`,
},
});
if (res.status === 401 && retryIfUnauthorized) {
return await callAPIInternal(input, init, null, false);
}
return res;
};
export const callAPI = async (input: RequestInfo, init?: RequestInit, token?: string | null) => {
return await callAPIInternal(input, init, token);
};

3
src/lib/stores/auth.ts Normal file
View File

@@ -0,0 +1,3 @@
import { writable } from "svelte/store";
export const accessToken = writable<string | null>(null);