Phase 2 + 3 complete
This commit is contained in:
parent
9a3fc97a34
commit
6d24f3c112
25 changed files with 3275 additions and 98 deletions
46
hooks/useAuthenticatedFetch.ts
Normal file
46
hooks/useAuthenticatedFetch.ts
Normal file
|
|
@ -0,0 +1,46 @@
|
|||
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,
|
||||
};
|
||||
};
|
||||
Loading…
Add table
Add a link
Reference in a new issue