Files
AnchorOS/lib/auth/context.tsx
Marco Gallegos 8fc9d3717e docs: add comprehensive code comments, update README and TASKS, create training and troubleshooting guides
- Add JSDoc comments to API routes and business logic functions
- Update README.md with Phase 2 status and deployment/production notes
- Enhance TASKS.md with estimated timelines and dependencies
- Create docs/STAFF_TRAINING.md for team onboarding
- Create docs/CLIENT_ONBOARDING.md for customer experience
- Create docs/OPERATIONAL_PROCEDURES.md for daily operations
- Create docs/TROUBLESHOOTING.md for common setup issues
- Fix TypeScript errors in hq/page.tsx
2026-01-16 18:42:45 -06:00

87 lines
2.2 KiB
TypeScript

'use client'
import { createContext, useContext, useEffect, useState, ReactNode } from 'react'
import { User, Session } from '@supabase/supabase-js'
import { supabase } from '@/lib/supabase/client'
type AuthContextType = {
user: User | null
session: Session | null
loading: boolean
signIn: (email: string) => Promise<{ error: any }>
signOut: () => Promise<void>
}
const AuthContext = createContext<AuthContextType | undefined>(undefined)
/**
* AuthProvider component that manages authentication state and provides it to children.
*/
export function AuthProvider({ children }: { children: ReactNode }) {
const [user, setUser] = useState<User | null>(null)
const [session, setSession] = useState<Session | null>(null)
const [loading, setLoading] = useState(true)
useEffect(() => {
const getSession = async () => {
const { data: { session }, error } = await supabase.auth.getSession()
if (error) {
console.error('Error getting session:', error)
}
setSession(session)
setUser(session?.user ?? null)
setLoading(false)
}
getSession()
const { data: { subscription } } = supabase.auth.onAuthStateChange(
async (event, session) => {
console.log('Auth state change:', event, session?.user?.email)
setSession(session)
setUser(session?.user ?? null)
setLoading(false)
}
)
return () => subscription.unsubscribe()
}, [])
const signIn = async (email: string) => {
const { error } = await supabase.auth.signInWithOtp({
email,
options: {
emailRedirectTo: `${window.location.origin}/booking`,
},
})
return { error }
}
const signOut = async () => {
const { error } = await supabase.auth.signOut()
if (error) {
console.error('Error signing out:', error)
}
}
const value = {
user,
session,
loading,
signIn,
signOut,
}
return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>
}
/**
* useAuth hook that returns the current authentication context.
*/
export function useAuth() {
const context = useContext(AuthContext)
if (context === undefined) {
throw new Error('useAuth must be used within an AuthProvider')
}
return context
}