Spaces:
Running
Running
| 'use client' | |
| import { createContext, useContext, useEffect, useState } from 'react' | |
| import { useRouter } from 'next/navigation' | |
| const Context = createContext(undefined) | |
| export function AuthProvider({ children, supabase, accessToken }) { | |
| const [user, setUser] = useState(null) | |
| const [session, setSession] = useState(null) | |
| const [loading, setLoading] = useState(true) | |
| const router = useRouter() | |
| useEffect(() => { | |
| const getSession = async () => { | |
| const { data: { session } } = await supabase.auth.getSession() | |
| setSession(session) | |
| setUser(session?.user ?? null) | |
| setLoading(false) | |
| } | |
| getSession() | |
| const { data: { subscription } } = supabase.auth.onAuthStateChange((event, session) => { | |
| if (event === 'SIGNED_IN') { | |
| setSession(session) | |
| setUser(session?.user) | |
| router.refresh() | |
| } else if (event === 'SIGNED_OUT') { | |
| setSession(null) | |
| setUser(null) | |
| router.push('/auth/login') | |
| } | |
| }) | |
| return () => subscription.unsubscribe() | |
| }, []) | |
| const value = { | |
| session, | |
| user, | |
| loading, | |
| signOut: () => supabase.auth.signOut(), | |
| } | |
| return <Context.Provider value={value}>{!loading && children}</Context.Provider> | |
| } | |
| export const useAuth = () => { | |
| const context = useContext(Context) | |
| if (context === undefined) { | |
| throw new Error('useAuth must be used within an AuthProvider') | |
| } | |
| return context | |
| } |