feat: add secure login page with jwt authentication and button animation
This commit is contained in:
@@ -2,9 +2,49 @@ 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 response = await fetch(`${API_URL}/data`);
|
||||
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) {
|
||||
|
||||
Reference in New Issue
Block a user