|
4 | 4 | useOidcIdToken,
|
5 | 5 | } from "@axa-fr/react-oidc";
|
6 | 6 | import loadConfig from "@utils/config";
|
| 7 | +import { sleep } from "@utils/helpers"; |
7 | 8 | import { usePathname } from "next/navigation";
|
| 9 | +import { isExpired } from "react-jwt"; |
8 | 10 | import useSWR from "swr";
|
9 | 11 | import { useErrorBoundary } from "@/contexts/ErrorBoundary";
|
10 | 12 |
|
@@ -40,15 +42,30 @@ export function useNetBirdFetch() {
|
40 | 42 | const tokenSource = config.tokenSource || "accessToken";
|
41 | 43 | const { idToken } = useOidcIdToken();
|
42 | 44 | const { accessToken } = useOidcAccessToken();
|
| 45 | + const token = tokenSource.toLowerCase() == "idtoken" ? idToken : accessToken; |
| 46 | + const handleErrors = useApiErrorHandling(); |
| 47 | + |
| 48 | + const isTokenExpired = async () => { |
| 49 | + let attempts = 20; |
| 50 | + while (isExpired(token) && attempts > 0) { |
| 51 | + await sleep(500); |
| 52 | + attempts = attempts - 1; |
| 53 | + } |
| 54 | + return isExpired(token); |
| 55 | + }; |
43 | 56 |
|
44 | 57 | const nativeFetch = async (input: RequestInfo, init?: RequestInit) => {
|
45 |
| - const token = |
46 |
| - tokenSource.toLowerCase() == "idtoken" ? idToken : accessToken; |
| 58 | + const tokenExpired = await isTokenExpired(); |
| 59 | + if (tokenExpired) { |
| 60 | + return handleErrors({ code: 401, message: "token expired" }); |
| 61 | + } |
| 62 | + |
47 | 63 | const headers = {
|
48 | 64 | "Content-Type": "application/json",
|
49 | 65 | Accept: "application/json",
|
50 | 66 | Authorization: `Bearer ${token}`,
|
51 | 67 | };
|
| 68 | + |
52 | 69 | return fetch(input, {
|
53 | 70 | ...init,
|
54 | 71 | headers,
|
@@ -122,6 +139,9 @@ export function useApiErrorHandling() {
|
122 | 139 | if (err.code == 401 && err.message == "no valid authentication provided") {
|
123 | 140 | return login(currentPath);
|
124 | 141 | }
|
| 142 | + if (err.code == 401 && err.message == "token expired") { |
| 143 | + return login(currentPath); |
| 144 | + } |
125 | 145 | if (err.code == 401 && err.message == "token invalid") {
|
126 | 146 | return setError(err);
|
127 | 147 | }
|
|
0 commit comments