Add user setup config

This commit is contained in:
Joey Yakimowich-Payne 2026-01-13 16:18:46 -07:00
commit 342ff60b70
No known key found for this signature in database
GPG key ID: 6BFE655FA5ABD1E1
7 changed files with 230 additions and 18 deletions

View file

@ -6,35 +6,70 @@ const API_URL = import.meta.env.VITE_API_URL || 'http://localhost:3001';
export const useAuthenticatedFetch = () => {
const auth = useAuth();
const isTokenExpired = useCallback(() => {
if (!auth.user?.expires_at) return true;
const expiresAt = auth.user.expires_at * 1000;
const now = Date.now();
const bufferMs = 60 * 1000;
return now >= expiresAt - bufferMs;
}, [auth.user?.expires_at]);
const ensureValidToken = useCallback(async (): Promise<string> => {
if (!auth.user?.access_token) {
throw new Error('Not authenticated');
}
if (isTokenExpired()) {
try {
const user = await auth.signinSilent();
if (user?.access_token) {
return user.access_token;
}
} catch {
auth.signinRedirect();
throw new Error('Session expired, redirecting to login');
}
}
return auth.user.access_token;
}, [auth, isTokenExpired]);
const authFetch = useCallback(
async (path: string, options: RequestInit = {}): Promise<Response> => {
if (!auth.user?.access_token) {
throw new Error('Not authenticated');
}
const token = await ensureValidToken();
const url = path.startsWith('http') ? path : `${API_URL}${path}`;
const response = await fetch(url, {
...options,
headers: {
...options.headers,
Authorization: `Bearer ${auth.user.access_token}`,
Authorization: `Bearer ${token}`,
'Content-Type': 'application/json',
},
});
if (response.status === 401) {
try {
await auth.signinSilent();
const user = await auth.signinSilent();
if (user?.access_token) {
return fetch(url, {
...options,
headers: {
...options.headers,
Authorization: `Bearer ${user.access_token}`,
'Content-Type': 'application/json',
},
});
}
} catch {
auth.signinRedirect();
}
throw new Error('Token expired, please retry');
throw new Error('Session expired, redirecting to login');
}
return response;
},
[auth]
[auth, ensureValidToken]
);
return {