go-tell/ui/app/src/auth.tsx

47 lines
1.6 KiB
TypeScript
Raw Normal View History

import { createContext, useCallback, useContext, useEffect, useMemo, useState, type ReactNode } from 'react'
2026-09-19 16:45:24 +02:00
import { requestSession } from './api'
2026-09-19 16:45:24 +02:00
// There is no sign-in or sign-out: the upstream SSO proxy decides whether the
// current request carries the owner's identity.
type AuthState = {
loading: boolean
2026-09-19 16:45:24 +02:00
authenticated: boolean
canEdit: boolean
error: string | null
2026-09-19 16:45:24 +02:00
refresh: () => Promise<void>
}
const AuthContext = createContext<AuthState | undefined>(undefined)
export function AuthProvider({ children }: { children: ReactNode }) {
2026-09-19 16:45:24 +02:00
const [authenticated, setAuthenticated] = useState(false)
const [canEdit, setCanEdit] = useState(false)
const [loading, setLoading] = useState(true)
const [error, setError] = useState<string | null>(null)
const refresh = useCallback(async () => {
try {
setError(null)
const session = await requestSession()
2026-09-19 16:45:24 +02:00
setAuthenticated(session?.authenticated === true)
setCanEdit(session?.canEdit === true)
} catch (err) {
2026-09-19 16:45:24 +02:00
setAuthenticated(false)
setCanEdit(false)
setError(err instanceof Error ? err.message : 'Unable to check your SSO session.')
} finally {
setLoading(false)
}
}, [])
useEffect(() => { void refresh() }, [refresh])
2026-09-19 16:45:24 +02:00
const value = useMemo(() => ({ loading, authenticated, canEdit, error, refresh }), [loading, authenticated, canEdit, error, refresh])
return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>
}
export function useAuth() {
const context = useContext(AuthContext)
if (!context) throw new Error('useAuth must be used inside AuthProvider')
return context
2026-09-19 16:45:24 +02:00
}