Files
post-hub-platform-k7m2xq9wnp/devops-view/src/hooks/useDevopsGuestAuth.ts
2026-03-20 19:31:54 +01:00

59 lines
1.6 KiB
TypeScript

import { useState, useEffect, useRef } from "react";
import type { AuthResponse } from "../types";
interface AuthState {
token: string | null;
isLoading: boolean;
error: string | null;
}
const MAX_RETRIES = 3;
const RETRY_DELAY_MS = 3000;
export function useDevopsGuestAuth(): AuthState {
const [token, setToken] = useState<string | null>(null);
const [isLoading, setIsLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const attemptsRef = useRef(0);
const timerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
useEffect(() => {
let cancelled = false;
async function fetchToken() {
try {
const res = await fetch("/api/auth/devops-guest-token", {
method: "POST",
});
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const data = (await res.json()) as AuthResponse;
if (!cancelled) {
setToken(data.payload.token);
setIsLoading(false);
setError(null);
}
} catch (err) {
if (cancelled) return;
attemptsRef.current += 1;
if (attemptsRef.current < MAX_RETRIES) {
timerRef.current = setTimeout(fetchToken, RETRY_DELAY_MS);
} else {
setIsLoading(false);
setError(
err instanceof Error ? err.message : "Authentication failed"
);
}
}
}
fetchToken();
return () => {
cancelled = true;
if (timerRef.current !== null) clearTimeout(timerRef.current);
};
}, []);
return { token, isLoading, error };
}