2026-06-02 01:50:35 -04:00
|
|
|
import { useState, useEffect, useCallback } from 'react';
|
|
|
|
|
|
|
|
|
|
async function verifyAuthFromStorage() {
|
|
|
|
|
const token = localStorage.getItem('auth_token');
|
|
|
|
|
|
|
|
|
|
const headers = {
|
|
|
|
|
'Content-Type': 'application/json',
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
if (token) {
|
|
|
|
|
headers.Authorization = `Bearer ${token}`;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
try {
|
|
|
|
|
const response = await fetch('/api/auth/verify', { headers });
|
|
|
|
|
if (response.ok) {
|
|
|
|
|
return await response.json();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (token) {
|
|
|
|
|
localStorage.removeItem('auth_token');
|
|
|
|
|
}
|
|
|
|
|
return null;
|
|
|
|
|
} catch (error) {
|
|
|
|
|
console.error('Auth check failed:', error);
|
|
|
|
|
return null;
|
|
|
|
|
}
|
|
|
|
|
}
|
2025-07-26 23:23:31 -04:00
|
|
|
|
|
|
|
|
export function useAuth() {
|
|
|
|
|
const [user, setUser] = useState(null);
|
|
|
|
|
const [loading, setLoading] = useState(true);
|
|
|
|
|
|
|
|
|
|
useEffect(() => {
|
2026-06-02 01:50:35 -04:00
|
|
|
let active = true;
|
2025-07-26 23:23:31 -04:00
|
|
|
|
2026-06-02 01:50:35 -04:00
|
|
|
void (async () => {
|
|
|
|
|
const verifiedUser = await verifyAuthFromStorage();
|
|
|
|
|
if (!active) return;
|
|
|
|
|
setUser(verifiedUser);
|
2025-07-26 23:23:31 -04:00
|
|
|
setLoading(false);
|
2026-06-02 01:50:35 -04:00
|
|
|
})();
|
|
|
|
|
|
|
|
|
|
return () => {
|
|
|
|
|
active = false;
|
|
|
|
|
};
|
|
|
|
|
}, []);
|
|
|
|
|
|
|
|
|
|
const refreshAuth = useCallback(async () => {
|
|
|
|
|
const verifiedUser = await verifyAuthFromStorage();
|
|
|
|
|
setUser(verifiedUser);
|
|
|
|
|
setLoading(false);
|
|
|
|
|
}, []);
|
2025-07-26 23:23:31 -04:00
|
|
|
|
|
|
|
|
const logout = () => {
|
|
|
|
|
localStorage.removeItem('auth_token');
|
|
|
|
|
setUser(null);
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
return {
|
|
|
|
|
user,
|
|
|
|
|
loading,
|
|
|
|
|
logout,
|
2026-06-02 01:50:35 -04:00
|
|
|
refreshAuth,
|
2025-07-26 23:23:31 -04:00
|
|
|
};
|
2026-06-02 01:50:35 -04:00
|
|
|
}
|