Fix token refresh issues

This commit is contained in:
2025-03-02 22:41:43 -05:00
parent 7c3b462651
commit 91800574e4
2 changed files with 45 additions and 18 deletions

View File

@@ -30,39 +30,50 @@ export function AuthProvider({
children
}: AuthProviderProps){
const [ jwt, setJwt ] = useState<string | null>(null);
const [ expiration, setExpiration ] = useState<Date | null>(null)
const [ expiration, setExpiration ] = useState<Date | null>(null);
const [ firstFetch, setFirstFetch ] = useState(true);
const fetchToken = useCallback(async () => {
console.log("Fetching token");
try{
const response = await api.get("/auth/refresh");
//If the token is retrieved
if((response.status === 200) && (!response.data.errors)){
setJwt(response.data.token);
setExpiration(new Date(atob(response.data.token.split(".")[1])));
setExpiration(new Date(JSON.parse(atob(response.data.token.split(".")[1])).exp * 1000));
setFirstFetch(false);
return response.data.token;
}
//If the token cannot be retrieved
else{
setJwt(null);
setExpiration(null);
setFirstFetch(false);
}
}
//If the token cannot be retrieved
catch{
setJwt(null);
setExpiration(null);
setFirstFetch(false);
}
}, [ setJwt, setExpiration ]);
}, [ setJwt, setExpiration, setFirstFetch ]);
//Add the token to all queries
useLayoutEffect(() => {
if((expiration) && (expiration < new Date())){
fetchToken();
}
const authInterceptor = api.interceptors.request.use(async (config) => {
if(config.url?.endsWith("/auth/refresh")){
return config;
}
let currentJwt = jwt;
if((expiration) && (expiration < new Date()) && (!config.url?.endsWith("/auth/refresh"))){
currentJwt = await fetchToken();
config.headers.Authorization = jwt ? `Bearer ${currentJwt}` : config.headers.Authorization;
}
config.headers.Authorization = jwt ? `Bearer ${currentJwt}` : config.headers.Authorization;
const authInterceptor = api.interceptors.request.use(config => {
config.headers.Authorization = jwt ? `Bearer ${jwt}` : config.headers.Authorization;
return config;
});
@@ -83,6 +94,15 @@ export function AuthProvider({
}), [ jwt, setJwt, expiration, setExpiration ]);
//TODO: Return a spinner while the first token is being fetched
if(firstFetch){
return (
<main
className="text-4xl"
>
Loading...
</main>
);
}
return (