import React from "react";
import { useAuth } from "~/contexts/auth-context";
import { Navigate, useLocation } from "react-router";
import toast from "react-hot-toast";
import { LoadingPage } from "~/components/ui/loading";
interface ProtectedRouteProps {
children: React.ReactNode;
fallback?: React.ReactNode;
requireAuth?: boolean;
redirectTo?: string;
}
export function ProtectedRoute({
children,
fallback,
requireAuth = true,
redirectTo = "/login",
}: ProtectedRouteProps) {
const { isAuthenticated, isLoading, token, user } = useAuth();
const location = useLocation();
// Show loading while checking authentication
if (isLoading) {
return (
fallback || (
در حال بررسی احراز هویت...
لطفاً منتظر بمانید
)
);
}
// If authentication is required but user is not authenticated
if (requireAuth && !isAuthenticated) {
toast.error("برای دسترسی به این صفحه باید وارد شوید");
// Save the current location so we can redirect back after login
const currentPath = location.pathname + location.search;
const loginPath = `${redirectTo}?returnTo=${encodeURIComponent(currentPath)}`;
return ;
}
// If authentication is required but token is missing/invalid
if (requireAuth && isAuthenticated && (!token || !token.accessToken)) {
toast.error("جلسه کاری شما منقضی شده است. لطفاً دوباره وارد شوید");
// Clear any stored authentication data
localStorage.removeItem("auth_user");
localStorage.removeItem("auth_token");
return ;
}
// If user is authenticated but trying to access login page
if (!requireAuth && isAuthenticated && location.pathname === "/login") {
return ;
}
// If all checks pass, render the protected content
return <>{children}>;
}
// Helper component for public routes
export function PublicRoute({ children }: { children: React.ReactNode }) {
return {children};
}