55 lines
1.2 KiB
JavaScript
55 lines
1.2 KiB
JavaScript
|
|
import { useState, useEffect } from 'react';
|
||
|
|
|
||
|
|
export function useAuth() {
|
||
|
|
const [user, setUser] = useState(null);
|
||
|
|
const [loading, setLoading] = useState(true);
|
||
|
|
|
||
|
|
useEffect(() => {
|
||
|
|
checkAuth();
|
||
|
|
}, []);
|
||
|
|
|
||
|
|
const checkAuth = async () => {
|
||
|
|
try {
|
||
|
|
// Get token from localStorage
|
||
|
|
const token = localStorage.getItem('auth_token');
|
||
|
|
|
||
|
|
const headers = {
|
||
|
|
'Content-Type': 'application/json',
|
||
|
|
};
|
||
|
|
|
||
|
|
// Add authorization header if token exists
|
||
|
|
if (token) {
|
||
|
|
headers.Authorization = `Bearer ${token}`;
|
||
|
|
}
|
||
|
|
|
||
|
|
const response = await fetch('/api/auth/verify', { headers });
|
||
|
|
if (response.ok) {
|
||
|
|
const userData = await response.json();
|
||
|
|
setUser(userData);
|
||
|
|
} else {
|
||
|
|
setUser(null);
|
||
|
|
// Clear invalid token
|
||
|
|
if (token) {
|
||
|
|
localStorage.removeItem('auth_token');
|
||
|
|
}
|
||
|
|
}
|
||
|
|
} catch (error) {
|
||
|
|
console.error('Auth check failed:', error);
|
||
|
|
setUser(null);
|
||
|
|
} finally {
|
||
|
|
setLoading(false);
|
||
|
|
}
|
||
|
|
};
|
||
|
|
|
||
|
|
const logout = () => {
|
||
|
|
localStorage.removeItem('auth_token');
|
||
|
|
setUser(null);
|
||
|
|
};
|
||
|
|
|
||
|
|
return {
|
||
|
|
user,
|
||
|
|
loading,
|
||
|
|
logout,
|
||
|
|
refreshAuth: checkAuth
|
||
|
|
};
|
||
|
|
}
|