|
| 1 | +let __globalTokenRefresher: undefined | Promise<string> = undefined; |
| 2 | + |
| 3 | +export async function authFetch( |
| 4 | + P: { |
| 5 | + url: string; |
| 6 | + } & ( |
| 7 | + | { method: "POST"; body?: any } |
| 8 | + | { method: "GET"; body?: { [k: string]: string } } |
| 9 | + ), |
| 10 | + accessTokenNew: string | undefined = undefined |
| 11 | +) { |
| 12 | + const { |
| 13 | + public: { serverAddress }, |
| 14 | + } = useRuntimeConfig(); |
| 15 | + |
| 16 | + const { url, method, body } = P; |
| 17 | + |
| 18 | + const accessToken = accessTokenNew |
| 19 | + ? accessTokenNew |
| 20 | + : localStorage.getItem(ACCESS_TOKEN_KEY); |
| 21 | + |
| 22 | + const endUrl = `${serverAddress}${url}`; |
| 23 | + |
| 24 | + const res = await fetch( |
| 25 | + method == "GET" && body != undefined |
| 26 | + ? `${endUrl}?${Object.entries(body) |
| 27 | + .map(([k, v]) => `${encodeURIComponent(k)}=${encodeURIComponent(v)}`) |
| 28 | + .join("&")}` |
| 29 | + : endUrl, |
| 30 | + { |
| 31 | + method, |
| 32 | + body: method == "POST" ? body : undefined, |
| 33 | + headers: { |
| 34 | + ...(method == "POST" ? { "Content-Type": "application/json" } : {}), |
| 35 | + Authorization: `Bearer ${accessToken}`, |
| 36 | + }, |
| 37 | + } |
| 38 | + ); |
| 39 | + |
| 40 | + if (res.status == 403) { |
| 41 | + if (__globalTokenRefresher == undefined) { |
| 42 | + __globalTokenRefresher = refreshToken(serverAddress); |
| 43 | + } |
| 44 | + |
| 45 | + const newAccessToken = await __globalTokenRefresher; |
| 46 | + localStorage.setItem(ACCESS_TOKEN_KEY, newAccessToken); |
| 47 | + __globalTokenRefresher = undefined; |
| 48 | + |
| 49 | + return await authFetch(P, newAccessToken); |
| 50 | + } else return res; |
| 51 | +} |
| 52 | + |
| 53 | +async function refreshToken(serverAddress: string) { |
| 54 | + console.info(` --- fetching new access token ...`); |
| 55 | + |
| 56 | + const refreshToken = localStorage.getItem(REFRESH_TOKEN_KEY); |
| 57 | + |
| 58 | + const url = `${serverAddress}/main/main/refresh?token=${refreshToken}`; |
| 59 | + |
| 60 | + const res = await fetch(url, { method: "POST" }); |
| 61 | + |
| 62 | + if (res.ok) { |
| 63 | + console.info(` --- access token fetched!`); |
| 64 | + return (await res.json()).data.access; |
| 65 | + } else if (res.status == 403) { |
| 66 | + throw new NotLoggedInError(); |
| 67 | + } else { |
| 68 | + throw new Error( |
| 69 | + `refresh-token-err, status=${res.status}, text=${await res.text()}` |
| 70 | + ); |
| 71 | + } |
| 72 | +} |
| 73 | + |
| 74 | +export class NotLoggedInError extends Error { |
| 75 | + constructor() { |
| 76 | + super(); |
| 77 | + |
| 78 | + this.name = "NotLoggedInError"; |
| 79 | + } |
| 80 | +} |
0 commit comments