|
| 1 | +'use client' |
| 2 | + |
| 3 | +import { useEffect, useState } from 'react' |
| 4 | +import { useRouter } from 'next/navigation' |
| 5 | +import useAuth from '@/utils/useAuth' |
| 6 | +import { backendFetch, ensureBackendSession } from '@/lib/backend-auth' |
| 7 | +import type { PlanProfile } from '@/components/plan-card' |
| 8 | + |
| 9 | +/** |
| 10 | + * Loads the signed-in user's account profile for authed pages (dashboard, plan). |
| 11 | + * |
| 12 | + * Right after OAuth sign-in, LoginRedirectIfAuthed navigates here on the |
| 13 | + * `onAuthStateChanged` event — which can fire *before* login-form's |
| 14 | + * `establishBackendSession` has set the API cookie. Calling `ensureBackendSession` |
| 15 | + * first mints/verifies that cookie from the Firebase user, so `/auth/me` doesn't |
| 16 | + * 401 → forceLogout → bounce the user straight back to /login. |
| 17 | + */ |
| 18 | +export function useAccountProfile(nextPath: string): { profile: PlanProfile | null } { |
| 19 | + const { user, loading } = useAuth(false) |
| 20 | + const router = useRouter() |
| 21 | + const [profile, setProfile] = useState<PlanProfile | null>(null) |
| 22 | + |
| 23 | + useEffect(() => { |
| 24 | + if (loading) return |
| 25 | + const toLogin = () => router.replace(`/login?next=${encodeURIComponent(nextPath)}`) |
| 26 | + if (!user) { |
| 27 | + toLogin() |
| 28 | + return |
| 29 | + } |
| 30 | + let cancelled = false |
| 31 | + ;(async () => { |
| 32 | + try { |
| 33 | + await ensureBackendSession(user) |
| 34 | + const res = await backendFetch('/api/backend/auth/me') |
| 35 | + if (cancelled) return |
| 36 | + if (!res.ok) { |
| 37 | + toLogin() |
| 38 | + return |
| 39 | + } |
| 40 | + setProfile(await res.json()) |
| 41 | + } catch { |
| 42 | + if (!cancelled) toLogin() |
| 43 | + } |
| 44 | + })() |
| 45 | + return () => { cancelled = true } |
| 46 | + }, [user, loading, router, nextPath]) |
| 47 | + |
| 48 | + return { profile } |
| 49 | +} |
0 commit comments