Files
sfera/src/components/admin/admin-guard.tsx

65 lines
2.3 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"use client"
import { useState, useEffect, useRef } from 'react'
import { useAdminAuth } from '@/hooks/useAdminAuth'
import { AdminLogin } from './admin-login'
interface AdminGuardProps {
children: React.ReactNode
fallback?: React.ReactNode
}
export function AdminGuard({ children, fallback }: AdminGuardProps) {
const { isAuthenticated, isLoading, checkAuth, admin } = useAdminAuth()
const [isChecking, setIsChecking] = useState(true)
const initRef = useRef(false) // Защита от повторных инициализаций
useEffect(() => {
const initAuth = async () => {
if (initRef.current) {
console.log('AdminGuard - Already initialized, skipping')
return
}
initRef.current = true
console.log('AdminGuard - Initializing admin auth check')
await checkAuth()
setIsChecking(false)
console.log('AdminGuard - Admin auth check completed, authenticated:', isAuthenticated, 'admin:', !!admin)
}
initAuth()
}, [checkAuth, isAuthenticated, admin])
// Дополнительное логирование состояний
useEffect(() => {
console.log('AdminGuard - State update:', {
isChecking,
isLoading,
isAuthenticated,
hasAdmin: !!admin
})
}, [isChecking, isLoading, isAuthenticated, admin])
// Показываем лоадер пока проверяем авторизацию
if (isChecking || isLoading) {
return (
<div className="min-h-screen bg-gradient-smooth flex items-center justify-center">
<div className="text-center text-white">
<div className="animate-spin rounded-full h-16 w-16 border-4 border-white border-t-transparent mx-auto mb-4"></div>
<p className="text-white/80">Проверяем авторизацию администратора...</p>
</div>
</div>
)
}
// Если не авторизован, показываем форму авторизации
if (!isAuthenticated) {
console.log('AdminGuard - Admin not authenticated, showing admin login')
return fallback || <AdminLogin />
}
// Если авторизован, показываем защищенный контент
console.log('AdminGuard - Admin authenticated, showing admin panel')
return <>{children}</>
}