deckhearth/lib/admin-auth.js

120 lines
2.8 KiB
JavaScript
Raw Permalink Normal View History

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 {
// 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 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 {
// 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();
setIsAdmin(userData.role === 'admin');
} else {
setIsAdmin(false);
// Clear invalid token
if (token) {
localStorage.removeItem('auth_token');
}
}
} catch (error) {
setIsAdmin(false);
} finally {
setLoading(false);
}
};
checkAdmin();
}, []);
return { isAdmin, loading };
}