2025-12-04 21:19:07 +03:00
|
|
|
|
import { useContext, useEffect } from "react";
|
2025-03-08 19:01:08 +03:00
|
|
|
|
import { Navigate, Outlet } from "react-router-dom";
|
|
|
|
|
|
import { AuthContext } from "@/context/auth-context";
|
|
|
|
|
|
import ActivityIndicator from "../indicators/activity-indicator";
|
2025-12-04 21:19:07 +03:00
|
|
|
|
import {
|
|
|
|
|
|
isRedirectingToLogin,
|
|
|
|
|
|
setRedirectingToLogin,
|
|
|
|
|
|
} from "@/api/auth-redirect";
|
2025-03-08 19:01:08 +03:00
|
|
|
|
|
|
|
|
|
|
export default function ProtectedRoute({
|
|
|
|
|
|
requiredRoles,
|
|
|
|
|
|
}: {
|
2025-09-12 14:19:29 +03:00
|
|
|
|
requiredRoles: string[];
|
2025-03-08 19:01:08 +03:00
|
|
|
|
}) {
|
|
|
|
|
|
const { auth } = useContext(AuthContext);
|
|
|
|
|
|
|
2025-12-04 21:19:07 +03:00
|
|
|
|
// Redirect to login page when not authenticated
|
|
|
|
|
|
// don't use <Navigate> because we need a full page load to reset state
|
|
|
|
|
|
useEffect(() => {
|
|
|
|
|
|
if (
|
|
|
|
|
|
!auth.isLoading &&
|
|
|
|
|
|
auth.isAuthenticated &&
|
|
|
|
|
|
!auth.user &&
|
|
|
|
|
|
!isRedirectingToLogin()
|
|
|
|
|
|
) {
|
|
|
|
|
|
setRedirectingToLogin(true);
|
|
|
|
|
|
window.location.href = "/login";
|
|
|
|
|
|
}
|
|
|
|
|
|
}, [auth.isLoading, auth.isAuthenticated, auth.user]);
|
|
|
|
|
|
|
2025-03-08 19:01:08 +03:00
|
|
|
|
if (auth.isLoading) {
|
|
|
|
|
|
return (
|
|
|
|
|
|
<ActivityIndicator className="absolute left-1/2 top-1/2 -translate-x-1/2 -translate-y-1/2" />
|
|
|
|
|
|
);
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
// Unauthenticated mode
|
|
|
|
|
|
if (!auth.isAuthenticated) {
|
|
|
|
|
|
return <Outlet />;
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
// Authenticated mode (8971): require login
|
|
|
|
|
|
if (!auth.user) {
|
2025-12-04 21:19:07 +03:00
|
|
|
|
return (
|
|
|
|
|
|
<ActivityIndicator className="absolute left-1/2 top-1/2 -translate-x-1/2 -translate-y-1/2" />
|
|
|
|
|
|
);
|
2025-03-08 19:01:08 +03:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
// If role is null (shouldn’t happen if isAuthenticated, but type safety), fallback
|
|
|
|
|
|
// though isAuthenticated should catch this
|
|
|
|
|
|
if (auth.user.role === null) {
|
|
|
|
|
|
return <Outlet />;
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
if (!requiredRoles.includes(auth.user.role)) {
|
|
|
|
|
|
return <Navigate to="/unauthorized" replace />;
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
return <Outlet />;
|
|
|
|
|
|
}
|