70 lines
1.8 KiB
TypeScript
70 lines
1.8 KiB
TypeScript
'use client';
|
|
|
|
import React, { useEffect, useState } from 'react';
|
|
import { useRouter, usePathname } from 'next/navigation';
|
|
import { ShieldAlert } from 'lucide-react';
|
|
import { useAuthStore } from '@/stores';
|
|
import { getCookie } from '@/lib/cookie';
|
|
|
|
const publicPaths = ['/login'];
|
|
|
|
export default function AuthGuard({ children }: { children: React.ReactNode }) {
|
|
const router = useRouter();
|
|
const pathname = usePathname();
|
|
const { isAuthenticated, fetchMe, tryRefresh, accessToken } = useAuthStore();
|
|
const [loading, setLoading] = useState(true);
|
|
|
|
useEffect(() => {
|
|
if (publicPaths.includes(pathname)) {
|
|
setLoading(false);
|
|
return;
|
|
}
|
|
|
|
const init = async () => {
|
|
const token = accessToken || localStorage.getItem('accessToken') || getCookie('accessToken');
|
|
|
|
if (!token) {
|
|
const hasRefresh = localStorage.getItem('refreshToken');
|
|
if (hasRefresh) {
|
|
const renewed = await tryRefresh();
|
|
if (renewed) {
|
|
await fetchMe().catch(() => {
|
|
router.replace('/login');
|
|
return;
|
|
});
|
|
setLoading(false);
|
|
return;
|
|
}
|
|
}
|
|
router.replace('/login');
|
|
return;
|
|
}
|
|
|
|
if (!isAuthenticated) {
|
|
await fetchMe().catch(() => {
|
|
router.replace('/login');
|
|
return;
|
|
});
|
|
}
|
|
setLoading(false);
|
|
};
|
|
|
|
init();
|
|
}, [pathname]);
|
|
|
|
if (publicPaths.includes(pathname)) return <>{children}</>;
|
|
|
|
if (loading) {
|
|
return (
|
|
<div className="h-screen flex items-center justify-center bg-canvas">
|
|
<div className="text-center">
|
|
<ShieldAlert className="w-10 h-10 text-primary mx-auto mb-3 animate-pulse" />
|
|
<p className="text-text-muted text-sm">인증 확인 중...</p>
|
|
</div>
|
|
</div>
|
|
);
|
|
}
|
|
|
|
return <>{children}</>;
|
|
}
|