Skip to content

Commit

Permalink
Fix invalid token error message (#321)
Browse files Browse the repository at this point in the history
  • Loading branch information
heisbrot authored Feb 9, 2024
1 parent 3c60de4 commit f5059f4
Showing 1 changed file with 22 additions and 2 deletions.
24 changes: 22 additions & 2 deletions src/utils/api.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@ import {
useOidcIdToken,
} from "@axa-fr/react-oidc";
import loadConfig from "@utils/config";
import { sleep } from "@utils/helpers";
import { usePathname } from "next/navigation";
import { isExpired } from "react-jwt";
import useSWR from "swr";
import { useErrorBoundary } from "@/contexts/ErrorBoundary";

Expand Down Expand Up @@ -40,15 +42,30 @@ export function useNetBirdFetch() {
const tokenSource = config.tokenSource || "accessToken";
const { idToken } = useOidcIdToken();
const { accessToken } = useOidcAccessToken();
const token = tokenSource.toLowerCase() == "idtoken" ? idToken : accessToken;
const handleErrors = useApiErrorHandling();

const isTokenExpired = async () => {
let attempts = 20;
while (isExpired(token) && attempts > 0) {
await sleep(500);
attempts = attempts - 1;
}
return isExpired(token);
};

const nativeFetch = async (input: RequestInfo, init?: RequestInit) => {
const token =
tokenSource.toLowerCase() == "idtoken" ? idToken : accessToken;
const tokenExpired = await isTokenExpired();
if (tokenExpired) {
return handleErrors({ code: 401, message: "token expired" });
}

const headers = {
"Content-Type": "application/json",
Accept: "application/json",
Authorization: `Bearer ${token}`,
};

return fetch(input, {
...init,
headers,
Expand Down Expand Up @@ -122,6 +139,9 @@ export function useApiErrorHandling() {
if (err.code == 401 && err.message == "no valid authentication provided") {
return login(currentPath);
}
if (err.code == 401 && err.message == "token expired") {
return login(currentPath);
}
if (err.code == 401 && err.message == "token invalid") {
return setError(err);
}
Expand Down

0 comments on commit f5059f4

Please sign in to comment.