Files
otunes/apps/mobile/components/convex-auth-recovery.tsx
T

115 lines
2.6 KiB
TypeScript

import { useConvexAuth as useLocalConvexAuth } from "@convex-dev/auth/react"
import { useConvexAuth as useServerConvexAuth } from "convex/react"
import {
Component,
useCallback,
useEffect,
useRef,
type ErrorInfo,
type ReactNode,
} from "react"
import { LoadingView } from "@/components/ui/primitives"
import { shouldInvalidateAuthSession } from "@/lib/auth-errors"
type ConvexAuthRecoveryProps = {
children: ReactNode
onInvalidate: () => Promise<void>
}
type ConvexAuthErrorBoundaryProps = {
children: ReactNode
sessionEstablished: boolean
onAuthError: () => void
}
type ConvexAuthErrorBoundaryState = {
error: Error | null
}
class ConvexAuthErrorBoundary extends Component<
ConvexAuthErrorBoundaryProps,
ConvexAuthErrorBoundaryState
> {
state: ConvexAuthErrorBoundaryState = { error: null }
static getDerivedStateFromError(error: Error): ConvexAuthErrorBoundaryState {
return { error }
}
componentDidCatch(error: Error, _errorInfo: ErrorInfo) {
if (shouldInvalidateAuthSession(error, this.props.sessionEstablished)) {
this.props.onAuthError()
}
}
render() {
const { error } = this.state
if (error) {
if (shouldInvalidateAuthSession(error, this.props.sessionEstablished)) {
return <LoadingView />
}
throw error
}
return this.props.children
}
}
export function ConvexAuthRecovery({ children, onInvalidate }: ConvexAuthRecoveryProps) {
const localAuth = useLocalConvexAuth()
const serverAuth = useServerConvexAuth()
const hadServerAuthRef = useRef(false)
const invalidatingRef = useRef(false)
if (serverAuth?.isAuthenticated) {
hadServerAuthRef.current = true
}
const invalidateOnce = useCallback(async () => {
if (invalidatingRef.current) {
return
}
invalidatingRef.current = true
try {
await onInvalidate()
} catch {
invalidatingRef.current = false
}
}, [onInvalidate])
useEffect(() => {
if (!hadServerAuthRef.current) {
return
}
if (!localAuth?.isAuthenticated) {
return
}
if (!serverAuth || serverAuth.isLoading || serverAuth.isRefreshing) {
return
}
if (serverAuth.isAuthenticated) {
return
}
void invalidateOnce()
}, [invalidateOnce, localAuth, serverAuth])
const sessionEstablished = Boolean(
serverAuth &&
!serverAuth.isLoading &&
!serverAuth.isRefreshing &&
serverAuth.isAuthenticated
)
return (
<ConvexAuthErrorBoundary
sessionEstablished={sessionEstablished}
onAuthError={() => void invalidateOnce()}
>
{children}
</ConvexAuthErrorBoundary>
)
}