24 lines
722 B
JavaScript
Executable File
24 lines
722 B
JavaScript
Executable File
//File: frontend/app/_auth/useAuthGuard.jsx
|
|
'use client';
|
|
import { useEffect, useState } from 'react';
|
|
import { usePathname, useRouter } from 'next/navigation';
|
|
import Auth from './AuthDriver';
|
|
|
|
export default function UseAuthGuard({ children }) {
|
|
const [ok, setOk] = useState(false);
|
|
const router = useRouter();
|
|
const pathname = usePathname();
|
|
|
|
useEffect(() => {
|
|
let alive = true;
|
|
(async () => {
|
|
const me = await Auth.me().catch(() => ({ ok: false }));
|
|
if (alive && me?.ok) setOk(true);
|
|
else if (alive) router.replace(`/login?next=${encodeURIComponent(pathname || '/')}`);
|
|
})();
|
|
return () => { alive = false; };
|
|
}, [pathname, router]);
|
|
|
|
return ok ? <>{children}</> : null;
|
|
}
|