65 lines
2.3 KiB
TypeScript
65 lines
2.3 KiB
TypeScript
"use client"
|
||
|
||
import { useAuth } from '@/hooks/useAuth'
|
||
import { useEffect, useState, useRef } from 'react'
|
||
import { AuthFlow } from './auth/auth-flow'
|
||
|
||
interface AuthGuardProps {
|
||
children: React.ReactNode
|
||
fallback?: React.ReactNode
|
||
}
|
||
|
||
export function AuthGuard({ children, fallback }: AuthGuardProps) {
|
||
const { isAuthenticated, isLoading, checkAuth, user } = useAuth()
|
||
const [isChecking, setIsChecking] = useState(true)
|
||
const initRef = useRef(false) // Защита от повторных инициализаций
|
||
|
||
useEffect(() => {
|
||
const initAuth = async () => {
|
||
if (initRef.current) {
|
||
console.log('AuthGuard - Already initialized, skipping')
|
||
return
|
||
}
|
||
|
||
initRef.current = true
|
||
console.log('AuthGuard - Initializing auth check')
|
||
await checkAuth()
|
||
setIsChecking(false)
|
||
console.log('AuthGuard - Auth check completed, authenticated:', isAuthenticated, 'user:', !!user)
|
||
}
|
||
|
||
initAuth()
|
||
}, [checkAuth, isAuthenticated, user]) // Добавляем зависимости как требует линтер
|
||
|
||
// Дополнительное логирование состояний
|
||
useEffect(() => {
|
||
console.log('AuthGuard - State update:', {
|
||
isChecking,
|
||
isLoading,
|
||
isAuthenticated,
|
||
hasUser: !!user
|
||
})
|
||
}, [isChecking, isLoading, isAuthenticated, user])
|
||
|
||
// Показываем лоадер пока проверяем авторизацию
|
||
if (isChecking || isLoading) {
|
||
return (
|
||
<div className="min-h-screen 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('AuthGuard - User not authenticated, showing auth flow')
|
||
return fallback || <AuthFlow />
|
||
}
|
||
|
||
// Если авторизован, показываем защищенный контент
|
||
console.log('AuthGuard - User authenticated, showing dashboard')
|
||
return <>{children}</>
|
||
}
|