Files
sfera/src/components/auth-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 { 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}</>
}