ปรับ frontend
This commit is contained in:
23
frontend/app/_auth/useAuthGuard.jsx
Normal file
23
frontend/app/_auth/useAuthGuard.jsx
Normal file
@@ -0,0 +1,23 @@
|
||||
//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;
|
||||
}
|
||||
Reference in New Issue
Block a user