46 lines
1.1 KiB
TypeScript
46 lines
1.1 KiB
TypeScript
import { useAuth } from 'react-oidc-context';
|
|
import { useCallback } from 'react';
|
|
|
|
const API_URL = import.meta.env.VITE_API_URL || 'http://localhost:3001';
|
|
|
|
export const useAuthenticatedFetch = () => {
|
|
const auth = useAuth();
|
|
|
|
const authFetch = useCallback(
|
|
async (path: string, options: RequestInit = {}): Promise<Response> => {
|
|
if (!auth.user?.access_token) {
|
|
throw new Error('Not authenticated');
|
|
}
|
|
|
|
const url = path.startsWith('http') ? path : `${API_URL}${path}`;
|
|
|
|
const response = await fetch(url, {
|
|
...options,
|
|
headers: {
|
|
...options.headers,
|
|
Authorization: `Bearer ${auth.user.access_token}`,
|
|
'Content-Type': 'application/json',
|
|
},
|
|
});
|
|
|
|
if (response.status === 401) {
|
|
try {
|
|
await auth.signinSilent();
|
|
} catch {
|
|
auth.signinRedirect();
|
|
}
|
|
throw new Error('Token expired, please retry');
|
|
}
|
|
|
|
return response;
|
|
},
|
|
[auth]
|
|
);
|
|
|
|
return {
|
|
authFetch,
|
|
isAuthenticated: auth.isAuthenticated,
|
|
isLoading: auth.isLoading,
|
|
user: auth.user,
|
|
};
|
|
};
|