|
| 1 | +"use client"; |
| 2 | + |
| 3 | +import { createContext, useState, useEffect, useCallback, type ReactNode } from "react"; |
| 4 | + |
| 5 | +export interface AuthUser { |
| 6 | + id: string; |
| 7 | + email: string; |
| 8 | + name: string; |
| 9 | + picture: string; |
| 10 | +} |
| 11 | + |
| 12 | +export interface AuthContextValue { |
| 13 | + user: AuthUser | null; |
| 14 | + loading: boolean; |
| 15 | + isAuthenticated: boolean; |
| 16 | + refresh: () => Promise<void>; |
| 17 | + logout: () => Promise<void>; |
| 18 | +} |
| 19 | + |
| 20 | +export const AuthContext = createContext<AuthContextValue>({ |
| 21 | + user: null, |
| 22 | + loading: true, |
| 23 | + isAuthenticated: false, |
| 24 | + refresh: async () => {}, |
| 25 | + logout: async () => {}, |
| 26 | +}); |
| 27 | + |
| 28 | +export function AuthProvider({ children }: { children: ReactNode }) { |
| 29 | + const [user, setUser] = useState<AuthUser | null>(null); |
| 30 | + const [loading, setLoading] = useState(true); |
| 31 | + |
| 32 | + const fetchSession = useCallback(async () => { |
| 33 | + try { |
| 34 | + setLoading(true); |
| 35 | + const res = await fetch("/api/auth/session", { |
| 36 | + credentials: "include", |
| 37 | + }); |
| 38 | + if (res.ok) { |
| 39 | + const data = await res.json(); |
| 40 | + setUser(data.user ?? null); |
| 41 | + } else { |
| 42 | + setUser(null); |
| 43 | + } |
| 44 | + } catch { |
| 45 | + setUser(null); |
| 46 | + } finally { |
| 47 | + setLoading(false); |
| 48 | + } |
| 49 | + }, []); |
| 50 | + |
| 51 | + useEffect(() => { |
| 52 | + fetchSession(); |
| 53 | + }, [fetchSession]); |
| 54 | + |
| 55 | + const logout = useCallback(async () => { |
| 56 | + try { |
| 57 | + await fetch("/api/auth/logout", { |
| 58 | + method: "POST", |
| 59 | + credentials: "include", |
| 60 | + }); |
| 61 | + } catch { |
| 62 | + // Ignore network errors — still clear local state |
| 63 | + } |
| 64 | + setUser(null); |
| 65 | + window.location.href = "/"; |
| 66 | + }, []); |
| 67 | + |
| 68 | + return ( |
| 69 | + <AuthContext.Provider |
| 70 | + value={{ |
| 71 | + user, |
| 72 | + loading, |
| 73 | + isAuthenticated: !!user, |
| 74 | + refresh: fetchSession, |
| 75 | + logout, |
| 76 | + }} |
| 77 | + > |
| 78 | + {children} |
| 79 | + </AuthContext.Provider> |
| 80 | + ); |
| 81 | +} |
0 commit comments