ui-nyla/src/providers/auth/ProtectedRoute.tsx
2026-05-08 11:49:24 +02:00

47 lines
1.3 KiB
TypeScript

import { Navigate, useLocation } from "react-router-dom";
import { ReactNode, useEffect, useState } from "react";
import { useLanguage } from "../language/LanguageContext";
interface ProtectedRouteProps {
children: ReactNode;
redirectPath?: string;
}
export const ProtectedRoute = ({
children,
redirectPath = "/login"
}: ProtectedRouteProps) => {
const { t } = useLanguage();
const location = useLocation();
const [isChecking, setIsChecking] = useState(true);
const [isAuthenticated, setIsAuthenticated] = useState(false);
useEffect(() => {
const authAuthority = sessionStorage.getItem('auth_authority');
setIsAuthenticated(!!authAuthority);
setIsChecking(false);
}, []);
useEffect(() => {
if (!isChecking) {
const recheckTimer = setTimeout(() => {
const authAuthority = sessionStorage.getItem('auth_authority');
const isAuth = !!authAuthority;
if (isAuth !== isAuthenticated) {
setIsAuthenticated(isAuth);
}
}, 300);
return () => clearTimeout(recheckTimer);
}
}, [isChecking, isAuthenticated]);
if (isChecking) {
return <div>{t('Authentifizierung wird geprüft…')}</div>;
}
if (!isAuthenticated) {
return <Navigate to={redirectPath} state={{ from: location }} replace />;
}
return <>{children}</>;
};