File size: 1,415 Bytes
5a7302b dff8593 b00f0f1 5a7302b b283b34 5a7302b b00f0f1 5a7302b b283b34 7447362 b283b34 5a7302b b283b34 5a7302b b283b34 dff8593 5a7302b b283b34 5a7302b | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 | 'use client'
import { useEffect, useState } from 'react'
type AuthUser = { id: string; email?: string | null }
const AUTH_EVENT = 'letschat-auth-refresh'
export const emitAuthChanged = () => {
if (typeof window !== 'undefined') {
window.dispatchEvent(new Event(AUTH_EVENT))
}
}
export function useAuth() {
const [user, setUser] = useState<AuthUser | null>(null)
const [loading, setLoading] = useState(true)
const refresh = async () => {
try {
// include Authorization header from localStorage fallback if present
const headers: Record<string, string> = { 'Content-Type': 'application/json' }
if (typeof window !== 'undefined') {
const fallback = window.localStorage.getItem('letschat_session')
if (fallback) headers['Authorization'] = `Bearer ${fallback}`
}
const res = await fetch('/api/auth/me', { cache: 'no-store', credentials: 'include', headers })
const data = await res.json().catch(() => ({}))
setUser(data?.user ? { id: data.user.id, email: data.user.email } : null)
} catch {
setUser(null)
} finally {
setLoading(false)
}
}
useEffect(() => {
refresh()
const listener = () => {
setLoading(true)
refresh()
}
window.addEventListener(AUTH_EVENT, listener)
return () => window.removeEventListener(AUTH_EVENT, listener)
}, [])
return { user, loading, refresh }
}
|