Files
MikrotikManager/components/auth-guard.tsx

57 lines
1.5 KiB
TypeScript

"use client"
import { useEffect, useState, type ReactNode } from "react"
import { usePathname } from "next/navigation"
import {
can,
ensureAuthConfig,
getClaims,
getToken,
isAuthEnabled,
permissionForPath,
redirectToPortalLogin,
redirectToPortalLoginInteractive,
} from "@/lib/auth"
export function AuthGuard({ children }: { children: ReactNode }) {
const pathname = usePathname()
const [ready, setReady] = useState(false)
const permission = pathname ? permissionForPath(pathname) : null
useEffect(() => {
let cancelled = false
void (async () => {
await ensureAuthConfig()
if (cancelled) return
if (!isAuthEnabled()) {
setReady(true)
return
}
const claims = getClaims()
if (!getToken() || !claims) {
const ok = redirectToPortalLogin()
if (!ok) redirectToPortalLoginInteractive()
return
}
if (!claims.apps.includes("mm") || (permission && !can(permission))) {
window.location.assign("/access-denied")
return
}
setReady(true)
})()
return () => {
cancelled = true
}
}, [pathname, permission])
if (!ready || (isAuthEnabled() && (!getToken() || !getClaims()?.apps.includes("mm") || (permission && !can(permission))))) {
return (
<div className="text-muted-foreground flex min-h-svh items-center justify-center p-6 text-sm">
Проверка сессии…
</div>
)
}
return children
}