37 lines
1.1 KiB
TypeScript
37 lines
1.1 KiB
TypeScript
"use client"
|
|
|
|
import { usePathname, useRouter } from "next/navigation"
|
|
import { useEffect } from "react"
|
|
import { ownerLinks, playerLinks } from "@/components/dashboard-sidebar"
|
|
import type { UserRole } from "@/lib/types"
|
|
import { useAuthStore } from "@/store/auth"
|
|
|
|
const dashboardRoutes: Record<string, readonly { href: string }[]> = {
|
|
player: playerLinks,
|
|
owner: ownerLinks,
|
|
}
|
|
|
|
export function canAccessDashboard(role: UserRole, pathname: string) {
|
|
const routes = dashboardRoutes[role]
|
|
if (!routes) return false
|
|
return routes.some((link) => pathname === link.href || pathname.startsWith(link.href + "/"))
|
|
}
|
|
|
|
export function RoleGuard({ children }: { children: React.ReactNode }) {
|
|
const currentRole = useAuthStore((state) => state.currentRole)
|
|
const pathname = usePathname()
|
|
const router = useRouter()
|
|
|
|
const allowed = canAccessDashboard(currentRole, pathname)
|
|
|
|
useEffect(() => {
|
|
if (!allowed) {
|
|
router.replace(currentRole === "consumer" ? "/" : "/dashboard")
|
|
}
|
|
}, [allowed, currentRole, pathname, router])
|
|
|
|
if (!allowed) return null
|
|
|
|
return <>{children}</>
|
|
}
|