21 lines
680 B
TypeScript
21 lines
680 B
TypeScript
|
|
import { ReactNode, useEffect } from 'react';
|
||
|
|
import { Navigate, useLocation } from 'react-router-dom';
|
||
|
|
import { useAuthStore } from '@/stores/authStore';
|
||
|
|
import { authApi } from '@/api/auth';
|
||
|
|
|
||
|
|
export default function RequireAuth({ children }: { children: ReactNode }) {
|
||
|
|
const { accessToken, profile, setProfile, clear } = useAuthStore();
|
||
|
|
const location = useLocation();
|
||
|
|
|
||
|
|
useEffect(() => {
|
||
|
|
if (accessToken && !profile) {
|
||
|
|
authApi.me().then(setProfile).catch(() => clear());
|
||
|
|
}
|
||
|
|
}, [accessToken, profile, setProfile, clear]);
|
||
|
|
|
||
|
|
if (!accessToken) {
|
||
|
|
return <Navigate to="/login" state={{ from: location.pathname }} replace />;
|
||
|
|
}
|
||
|
|
return <>{children}</>;
|
||
|
|
}
|