Spaces:
Running
Running
File size: 2,519 Bytes
c69ce84 ba5edb0 c69ce84 ba5edb0 c69ce84 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 |
import React, { createContext, useState, useEffect } from 'react';
import type { ReactNode } from 'react';
interface AdminContextType {
isAuthenticated: boolean;
isLoading: boolean;
login: (password: string) => Promise<boolean>;
logout: () => void;
verifyToken: () => Promise<void>;
}
export const AdminContext = createContext<AdminContextType | undefined>(undefined);
interface AdminProviderProps {
children: ReactNode;
}
export const AdminProvider: React.FC<AdminProviderProps> = ({ children }) => {
const [isAuthenticated, setIsAuthenticated] = useState(false);
const [isLoading, setIsLoading] = useState(true);
const verifyToken = async () => {
const adminToken = localStorage.getItem('adminToken');
if (!adminToken) {
setIsAuthenticated(false);
setIsLoading(false);
return;
}
try {
const response = await fetch('/api/admin/verify', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${adminToken}`
}
});
if (response.ok) {
setIsAuthenticated(true);
} else {
// Token is invalid, remove it
localStorage.removeItem('adminToken');
setIsAuthenticated(false);
}
} catch (error) {
console.error('Error verifying admin token:', error);
localStorage.removeItem('adminToken');
setIsAuthenticated(false);
} finally {
setIsLoading(false);
}
};
const login = async (password: string): Promise<boolean> => {
try {
const response = await fetch('/api/admin/login', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ password })
});
if (response.ok) {
const data = await response.json();
localStorage.setItem('adminToken', data.access_token);
setIsAuthenticated(true);
return true;
} else {
return false;
}
} catch (error) {
console.error('Login error:', error);
return false;
}
};
const logout = () => {
localStorage.removeItem('adminToken');
setIsAuthenticated(false);
};
// Check authentication status on mount
useEffect(() => {
verifyToken();
}, []);
const value: AdminContextType = {
isAuthenticated,
isLoading,
login,
logout,
verifyToken
};
return (
<AdminContext.Provider value={value}>
{children}
</AdminContext.Provider>
);
};
|