feat(auth): useAuth + ProtectedRoute + signUp dans auth-client (Sprint 1 étape 2)
This commit is contained in:
parent
107a37d197
commit
38777796aa
19 changed files with 2620 additions and 191 deletions
54
src/features/auth/hooks/useAuth.ts
Normal file
54
src/features/auth/hooks/useAuth.ts
Normal file
|
|
@ -0,0 +1,54 @@
|
|||
/**
|
||||
* 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,
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue