Files
dashboards/src/components/RequireStoreAuth.tsx
T

44 lines
1.0 KiB
TypeScript

"use client";
import { useEffect } from "react";
import { usePathname, useRouter } from "next/navigation";
import { useAuth } from "@/lib/auth";
const PUBLIC_PATHS = ["/login"];
export default function RequireStoreAuth({
children,
}: {
children: React.ReactNode;
}) {
const { user, loading } = useAuth();
const pathname = usePathname();
const router = useRouter();
const isPublic = PUBLIC_PATHS.some(
(p) => pathname === p || pathname.startsWith(`${p}/`),
);
useEffect(() => {
if (loading || isPublic) return;
if (!user) {
router.replace("/login");
return;
}
if (user.role === "CUSTOMER") {
router.replace("/login?as=customer");
}
}, [user, loading, isPublic, router]);
if (isPublic) return <>{children}</>;
if (loading) {
return (
<div className="flex min-h-dvh items-center justify-center text-sm text-muted">
در حال بارگذاری…
</div>
);
}
if (!user || user.role === "CUSTOMER") return null;
return <>{children}</>;
}