Download src/hooks/useAuth.ts from HonzaH/Letschat: direct link, hf CLI and curl.
- Browser
- Download file 1.42 kB
-
https://huggingface.co/spaces/HonzaH/Letschat/resolve/main/src/hooks/useAuth.ts
- Command line
-
hf download hf://spaces/HonzaH/Letschat/src/hooks/useAuth.ts
-
curl -L -o useAuth.ts https://huggingface.co/spaces/HonzaH/Letschat/resolve/main/src/hooks/useAuth.ts
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 } | |
| } | |