File size: 1,293 Bytes
f56a29b | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 |
import { useEffect, useState, ReactNode } from 'react';
import { AccessCodeModal } from '@/components/access-code-modal';
export function AccessCodeGuard({ children }: { children: ReactNode }) {
const [status, setStatus] = useState<{
enabled: boolean;
authenticated: boolean;
loading: boolean;
}>({ enabled: false, authenticated: false, loading: true });
useEffect(() => {
let cancelled = false;
fetch('/api/access-code/status')
.then((res) => res.json())
.then((data) => {
if (!cancelled) {
setStatus({
enabled: data.enabled,
authenticated: data.authenticated,
loading: false,
});
}
})
.catch(() => {
if (!cancelled) {
// Default to requiring auth on error — safer than silently disabling
setStatus({ enabled: true, authenticated: false, loading: false });
}
});
return () => {
cancelled = true;
};
}, []);
const needsAuth = !status.loading && status.enabled && !status.authenticated;
return (
<>
{needsAuth && (
<AccessCodeModal
open={true}
onSuccess={() => setStatus((s) => ({ ...s, authenticated: true }))}
/>
)}
{children}
</>
);
}
|