Letschat / src /hooks /useAuth.ts
HonzaH's picture
Upload 192 files
7447362 verified
Raw History Blame Contribute Delete
1.42 kB
'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 }
}