55 lines
1.4 KiB
TypeScript
55 lines
1.4 KiB
TypeScript
import type { OrderData } from './types';
|
|
|
|
const API_URL = import.meta.env.VITE_API_URL || '/api';
|
|
|
|
export const login = async (email: string, password: string): Promise<boolean> => {
|
|
try {
|
|
const response = await fetch(`${API_URL}/login`, {
|
|
method: 'POST',
|
|
headers: {
|
|
'Content-Type': 'application/json',
|
|
},
|
|
body: JSON.stringify({ email, password }),
|
|
});
|
|
|
|
if (response.ok) {
|
|
const data = await response.json();
|
|
localStorage.setItem('auth_token', data.token);
|
|
return true;
|
|
}
|
|
return false;
|
|
} catch (error) {
|
|
console.error('Login failed', error);
|
|
return false;
|
|
}
|
|
};
|
|
|
|
export const logout = () => {
|
|
localStorage.removeItem('auth_token');
|
|
window.location.href = '/#/login';
|
|
};
|
|
|
|
export const isAuthenticated = (): boolean => {
|
|
return !!localStorage.getItem('auth_token');
|
|
};
|
|
|
|
export const fetchData = async (): Promise<OrderData[]> => {
|
|
try {
|
|
const token = localStorage.getItem('auth_token');
|
|
const response = await fetch(`${API_URL}/data`, {
|
|
headers: {
|
|
'Authorization': `Bearer ${token}`
|
|
}
|
|
});
|
|
if (response.status === 401 || response.status === 403) {
|
|
logout();
|
|
return [];
|
|
}
|
|
if (!response.ok) return [];
|
|
return await response.json();
|
|
} catch (error) {
|
|
console.error("Fetch failed", error);
|
|
return [];
|
|
}
|
|
};
|