29 lines
899 B
TypeScript
29 lines
899 B
TypeScript
import React, { useEffect } from 'react'
|
|
import { useAuth } from '../lib/auth-context'
|
|
import { useNavigate, useLocation } from '@tanstack/react-router'
|
|
|
|
export function ProtectedRoute({ children }: { children: React.ReactNode }) {
|
|
const { isAuthenticated, isLoading } = useAuth()
|
|
const navigate = useNavigate()
|
|
const location = useLocation()
|
|
|
|
useEffect(() => {
|
|
if (isLoading) return
|
|
if (isAuthenticated) return
|
|
|
|
sessionStorage.setItem('auth_redirect', location.pathname)
|
|
navigate({ to: '/login', search: { redirect: location.pathname } })
|
|
}, [isAuthenticated, isLoading])
|
|
|
|
if (isLoading) {
|
|
return (
|
|
<div className="flex min-h-screen items-center justify-center">
|
|
<div className="h-8 w-8 animate-spin rounded-full border-4 border-brand-500 border-t-transparent" />
|
|
</div>
|
|
)
|
|
}
|
|
|
|
if (!isAuthenticated) return null
|
|
|
|
return <>{children}</>
|
|
}
|