54 lines
1.3 KiB
TypeScript
54 lines
1.3 KiB
TypeScript
/**
|
|
* Hook source de vérité pour l'état d'authentification dans toute l'app.
|
|
*
|
|
* Au mount : récupère la session courante depuis Supabase (cookie + localStorage).
|
|
* S'abonne ensuite à `onAuthStateChange` pour réagir aux login/logout/refresh
|
|
* token ; se désabonne au unmount.
|
|
*
|
|
* Consommé par `ProtectedRoute` (redirect si non authentifié) et par toute page
|
|
* qui a besoin du profil Supabase (ex. prénom affiché dans le header).
|
|
*/
|
|
|
|
import { useEffect, useState } from 'react'
|
|
import {
|
|
getCurrentSession,
|
|
subscribeToAuthChanges,
|
|
type User,
|
|
} from '@/shared/lib/auth-client'
|
|
|
|
interface UseAuthResult {
|
|
user: User | null
|
|
isLoading: boolean
|
|
isAuthenticated: boolean
|
|
}
|
|
|
|
export function useAuth(): UseAuthResult {
|
|
const [user, setUser] = useState<User | null>(null)
|
|
const [isLoading, setIsLoading] = useState(true)
|
|
|
|
useEffect(() => {
|
|
let cancelled = false
|
|
|
|
getCurrentSession().then((session) => {
|
|
if (cancelled) return
|
|
setUser(session?.user ?? null)
|
|
setIsLoading(false)
|
|
})
|
|
|
|
const unsubscribe = subscribeToAuthChanges((session) => {
|
|
setUser(session?.user ?? null)
|
|
setIsLoading(false)
|
|
})
|
|
|
|
return () => {
|
|
cancelled = true
|
|
unsubscribe()
|
|
}
|
|
}, [])
|
|
|
|
return {
|
|
user,
|
|
isLoading,
|
|
isAuthenticated: user !== null,
|
|
}
|
|
}
|