Files
hr-assessment-system/components/protected-route.tsx
2025-09-25 12:30:25 +08:00

49 lines
1.1 KiB
TypeScript

"use client"
import type React from "react"
import { useEffect } from "react"
import { useRouter } from "next/navigation"
import { useAuth } from "@/lib/hooks/use-auth"
interface ProtectedRouteProps {
children: React.ReactNode
adminOnly?: boolean
}
export function ProtectedRoute({ children, adminOnly = false }: ProtectedRouteProps) {
const { user, isLoading } = useAuth()
const router = useRouter()
useEffect(() => {
if (!isLoading) {
if (!user) {
router.push("/login")
return
}
if (adminOnly && user.role !== "admin") {
router.push("/dashboard")
return
}
}
}, [user, isLoading, adminOnly, router])
if (isLoading) {
return (
<div className="min-h-screen bg-background flex items-center justify-center">
<div className="text-center">
<div className="w-8 h-8 border-4 border-primary border-t-transparent rounded-full animate-spin mx-auto mb-4"></div>
<p className="text-muted-foreground">...</p>
</div>
</div>
)
}
if (!user || (adminOnly && user.role !== "admin")) {
return null
}
return <>{children}</>
}