devops
This commit is contained in:
58
devops-view/src/hooks/useDevopsGuestAuth.ts
Normal file
58
devops-view/src/hooks/useDevopsGuestAuth.ts
Normal file
@@ -0,0 +1,58 @@
|
||||
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 };
|
||||
}
|
||||
Reference in New Issue
Block a user