🐛 Fixed Authentication Problems: - Removed hardcoded mock admin user from collection detail page - Removed hardcoded mock user from collections page - Created proper useAuth hook to get current authenticated user - Added proper authentication checks and redirects 🔧 Authentication Flow Fixes: - Collection detail page now uses actual logged-in user (Alice, Bob, etc.) - Proper permission checks based on real user identity - Edit/Delete buttons now show correctly based on actual ownership - Authentication loading states handled properly 🛠️ Technical Improvements: - Created lib/use-auth.js hook for consistent auth handling - Added auth loading states to prevent flash of wrong content - Proper redirects to login page when not authenticated - Fixed token retrieval from localStorage ('auth_token') ✅ User Experience: - Alice and Bob now see their own collections correctly - Edit/Delete permissions work based on actual collection ownership - No more authentication errors when editing owned collections - Consistent user identity across all pages The authentication system now works correctly with the demo users! 🎯
55 lines
No EOL
1.2 KiB
JavaScript
55 lines
No EOL
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
|
|
};
|
|
}
|