refactor(dashboard): extract RoleGuard and unify mobile nav with Button

This commit is contained in:
zetaloop
2026-02-25 15:18:20 +08:00
parent f8659b5ebc
commit 37d83d8805
5 changed files with 86 additions and 51 deletions
+36
View File
@@ -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}</>
}