- Created admin authentication system with useIsAdmin hook - Added AdminProtected component for route protection - Added prominent 'Edit Card (Admin)' button on card detail pages - Protected all admin routes (/admin/*) with authentication - Added admin navigation item to main layout sidebar - Updated auth verification API to return mock admin user - Integrated admin edit button that redirects to card editor with card ID - Added proper access denied page for non-admin users - Admin-only features now show/hide based on user role - Seamless workflow: spot incorrect card → click edit → fix immediately
88 lines
No EOL
1.9 KiB
JavaScript
88 lines
No EOL
1.9 KiB
JavaScript
import { createContext, useContext, useState, useEffect } from 'react';
|
|
|
|
// Create admin context
|
|
const AdminContext = createContext();
|
|
|
|
export function AdminProvider({ children }) {
|
|
const [user, setUser] = useState(null);
|
|
const [loading, setLoading] = useState(true);
|
|
|
|
useEffect(() => {
|
|
checkAdminAuth();
|
|
}, []);
|
|
|
|
const checkAdminAuth = async () => {
|
|
try {
|
|
const response = await fetch('/api/auth/verify');
|
|
if (response.ok) {
|
|
const userData = await response.json();
|
|
setUser(userData);
|
|
} else {
|
|
setUser(null);
|
|
}
|
|
} catch (error) {
|
|
console.error('Auth check failed:', error);
|
|
setUser(null);
|
|
} finally {
|
|
setLoading(false);
|
|
}
|
|
};
|
|
|
|
const isAdmin = () => {
|
|
return user && user.role === 'admin';
|
|
};
|
|
|
|
const isAuthenticated = () => {
|
|
return user !== null;
|
|
};
|
|
|
|
const value = {
|
|
user,
|
|
loading,
|
|
isAdmin,
|
|
isAuthenticated,
|
|
checkAdminAuth
|
|
};
|
|
|
|
return (
|
|
<AdminContext.Provider value={value}>
|
|
{children}
|
|
</AdminContext.Provider>
|
|
);
|
|
}
|
|
|
|
export function useAdmin() {
|
|
const context = useContext(AdminContext);
|
|
if (!context) {
|
|
throw new Error('useAdmin must be used within an AdminProvider');
|
|
}
|
|
return context;
|
|
}
|
|
|
|
// Simple hook for checking admin status without context
|
|
export function useIsAdmin() {
|
|
const [isAdmin, setIsAdmin] = useState(false);
|
|
const [loading, setLoading] = useState(true);
|
|
|
|
useEffect(() => {
|
|
const checkAdmin = async () => {
|
|
try {
|
|
const response = await fetch('/api/auth/verify');
|
|
if (response.ok) {
|
|
const userData = await response.json();
|
|
setIsAdmin(userData.role === 'admin');
|
|
} else {
|
|
setIsAdmin(false);
|
|
}
|
|
} catch (error) {
|
|
setIsAdmin(false);
|
|
} finally {
|
|
setLoading(false);
|
|
}
|
|
};
|
|
|
|
checkAdmin();
|
|
}, []);
|
|
|
|
return { isAdmin, loading };
|
|
}
|