feat: upgrade authentication to JWT with refresh tokens
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
@@ -3,55 +3,42 @@ import axios from "axios";
|
||||
const api = axios.create({
|
||||
baseURL: import.meta.env.VITE_API_BASE_URL,
|
||||
timeout: 15000,
|
||||
withCredentials: true,
|
||||
});
|
||||
|
||||
export default api;
|
||||
|
||||
|
||||
//Ejemplo con fetch
|
||||
const API_BASE_URL = 'http://localhost:4000/api';
|
||||
|
||||
export async function createProduct(data) {
|
||||
try {
|
||||
const response = await fetch(`${API_BASE_URL}/products`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify(data),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error('Failed to save product');
|
||||
}
|
||||
|
||||
return await response.json();
|
||||
} catch (error) {
|
||||
console.error('API error:', error);
|
||||
throw error;
|
||||
// Request interceptor: attach access token
|
||||
api.interceptors.request.use((config) => {
|
||||
const token = sessionStorage.getItem('accessToken');
|
||||
if (token) {
|
||||
config.headers.Authorization = `Bearer ${token}`;
|
||||
}
|
||||
}
|
||||
return config;
|
||||
});
|
||||
|
||||
export async function fetchProducts() {
|
||||
const res = await fetch(`${API_BASE_URL}/products`);
|
||||
if (!res.ok) throw new Error('Error fetching products');
|
||||
return await res.json();
|
||||
}
|
||||
|
||||
export async function fetchInventoryProducts() {
|
||||
const res = await fetch(`${API_BASE_URL}/inventory-products`);
|
||||
if (!res.ok) throw new Error('Error fetching inventory products');
|
||||
// forma esperada: objeto, ej: { "PILLOWS": { unitCost: 300, tax: "IVA 16%" }, ... }
|
||||
return await res.json();
|
||||
}
|
||||
|
||||
export async function createExpense(payload) {
|
||||
const res = await fetch(`${API_BASE_URL}/expenses`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
if (!res.ok) throw new Error('Error creating expense');
|
||||
return await res.json();
|
||||
}
|
||||
// Response interceptor: handle 401 and auto-refresh
|
||||
api.interceptors.response.use(
|
||||
(response) => response,
|
||||
async (error) => {
|
||||
const originalRequest = error.config;
|
||||
if (error.response?.status === 401 && error.response?.data?.code === 'TOKEN_EXPIRED' && !originalRequest._retry) {
|
||||
originalRequest._retry = true;
|
||||
try {
|
||||
const { data } = await axios.post(
|
||||
`${import.meta.env.VITE_API_BASE_URL}/auth/refresh`,
|
||||
{},
|
||||
{ withCredentials: true }
|
||||
);
|
||||
sessionStorage.setItem('accessToken', data.accessToken);
|
||||
originalRequest.headers.Authorization = `Bearer ${data.accessToken}`;
|
||||
return api(originalRequest);
|
||||
} catch (refreshError) {
|
||||
sessionStorage.removeItem('accessToken');
|
||||
window.location.href = '/';
|
||||
return Promise.reject(refreshError);
|
||||
}
|
||||
}
|
||||
return Promise.reject(error);
|
||||
}
|
||||
);
|
||||
|
||||
export default api;
|
||||
|
||||
Reference in New Issue
Block a user