Initial commit
This commit is contained in:
48
components/protected-route.tsx
Normal file
48
components/protected-route.tsx
Normal file
@@ -0,0 +1,48 @@
|
||||
"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}</>
|
||||
}
|
Reference in New Issue
Block a user