mirror of
https://github.com/kmc7468/arkvault.git
synced 2025-12-15 22:38:47 +00:00
Refresh Token 저장 방식 변경
This commit is contained in:
47
src/lib/hooks/callAPI.ts
Normal file
47
src/lib/hooks/callAPI.ts
Normal 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
3
src/lib/stores/auth.ts
Normal file
@@ -0,0 +1,3 @@
|
||||
import { writable } from "svelte/store";
|
||||
|
||||
export const accessToken = writable<string | null>(null);
|
||||
Reference in New Issue
Block a user