Files
taiji-pda-v0/components/auth-guard.tsx
T
xiaohei 23c0b4e930 feat: 完善超级管理员控制台API集成
- 删除资源管理中的假数据,改为从API获取
- 添加删除Agent和模型供应商功能
- 完善创建渠道、资源管理、审批申请等功能的API集成
- 修复计费统计功能,接入后端API
- 添加缺失API接口清单文档
- 优化API响应格式处理,支持多种响应结构
- 修复审批申请对话框,添加供应商申请审批功能
2025-12-25 09:31:26 +00:00

95 lines
2.6 KiB
TypeScript

"use client"
import { useEffect, useState } from "react"
import { useRouter, usePathname } from "next/navigation"
import { isAuthenticated, isAdminAuthenticated, isChannelAuthenticated } from "@/lib/auth"
interface AuthGuardProps {
children: React.ReactNode
requireAuth?: boolean
redirectTo?: string
}
export function AuthGuard({ children, requireAuth = true, redirectTo = "/login" }: AuthGuardProps) {
const router = useRouter()
const pathname = usePathname()
const [mounted, setMounted] = useState(false)
const [isAuth, setIsAuth] = useState(false)
// 检查是否是登录页面
const isLoginPage = pathname === "/login" || pathname === "/channel/login" || pathname === "/admin/login"
const isAdminPage = pathname.startsWith("/admin")
const isChannelPage = pathname.startsWith("/channel")
useEffect(() => {
setMounted(true)
// 根据页面类型检查对应的认证状态
let auth = false
if (isAdminPage) {
auth = isAdminAuthenticated()
} else if (isChannelPage) {
auth = isChannelAuthenticated()
} else {
auth = isAuthenticated()
}
setIsAuth(auth)
// 登录页面不需要认证
if (isLoginPage) {
// 如果已登录,重定向到对应的首页
if (auth) {
if (pathname === "/channel/login") {
router.push("/channel/dashboard")
} else if (pathname === "/admin/login") {
router.push("/admin/dashboard")
} else {
router.push("/")
}
}
return
}
// 需要认证的页面
if (requireAuth && !auth) {
// 根据路径判断重定向到哪个登录页
if (isChannelPage) {
router.push("/channel/login")
} else if (isAdminPage) {
router.push("/admin/login")
} else {
router.push(redirectTo)
}
}
}, [pathname, requireAuth, redirectTo, router, isLoginPage, isAdminPage, isChannelPage])
// 在客户端挂载前,返回一个占位符以避免 Hydration 错误
if (!mounted) {
// 登录页面在挂载前直接渲染
if (isLoginPage) {
return <>{children}</>
}
// 其他页面在挂载前返回 null(等待客户端检查)
return null
}
// 如果是登录页面且已登录,不渲染内容(等待重定向)
if (isLoginPage && isAuth) {
return null
}
// 如果是登录页面,直接渲染(不需要认证)
if (isLoginPage) {
return <>{children}</>
}
// 如果需要认证但未登录,不渲染内容(等待重定向)
if (requireAuth && !isAuth) {
return null
}
return <>{children}</>
}