feat(frontend): implement center auth session flow with route guard
This commit is contained in:
34
src/auth/ProtectedRoute.tsx
Normal file
34
src/auth/ProtectedRoute.tsx
Normal file
@@ -0,0 +1,34 @@
|
||||
import { Navigate } from 'react-router-dom'
|
||||
import { useAuth } from './auth-context'
|
||||
import type { PropsWithChildren } from 'react'
|
||||
import { useEffect, useState } from 'react'
|
||||
|
||||
export default function ProtectedRoute({ children }: PropsWithChildren) {
|
||||
const { isAuthed, ensureFreshToken, logout } = useAuth()
|
||||
const [ready, setReady] = useState(false)
|
||||
|
||||
useEffect(() => {
|
||||
let active = true
|
||||
;(async () => {
|
||||
if (!isAuthed) {
|
||||
if (active) setReady(true)
|
||||
return
|
||||
}
|
||||
try {
|
||||
await ensureFreshToken()
|
||||
} catch {
|
||||
await logout()
|
||||
} finally {
|
||||
if (active) setReady(true)
|
||||
}
|
||||
})()
|
||||
|
||||
return () => {
|
||||
active = false
|
||||
}
|
||||
}, [isAuthed, ensureFreshToken, logout])
|
||||
|
||||
if (!ready) return null
|
||||
if (!isAuthed) return <Navigate to="/login" replace />
|
||||
return <>{children}</>
|
||||
}
|
||||
Reference in New Issue
Block a user