presentercoach / apps /web /src /lib /hooks /useRequireAuth.ts
nathycodes's picture
Deploy Tech Presenter Coach
ec17af3
Raw History Blame Contribute Delete
1.03 kB
import { useEffect } from "react";
import { useRouter } from "next/navigation";
import { authApi } from "@/lib/api";
import { useAuthStore } from "@/store/useAuthStore";
export const useRequireAuth = () => {
const router = useRouter();
const bootstrap = useAuthStore((state) => state.bootstrap);
const bootstrapped = useAuthStore((state) => state.bootstrapped);
const userEmail = useAuthStore((state) => state.userEmail);
useEffect(() => {
let active = true;
bootstrap().then(async (authenticated) => {
if (!active || authenticated) return;
try {
const status = await authApi.setupStatus();
if (!active) return;
if (status.setup_required) {
router.replace("/setup");
return;
}
} catch {
// Fall back to login page
}
if (active) {
router.replace("/login");
}
});
return () => {
active = false;
};
}, [bootstrap, router]);
return {
ready: Boolean(bootstrapped && userEmail),
};
};