refactor(dashboard): extract RoleGuard and unify mobile nav with Button
This commit is contained in:
@@ -0,0 +1,36 @@
|
||||
"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}</>
|
||||
}
|
||||
Reference in New Issue
Block a user