Spaces:
Sleeping
Sleeping
File size: 1,857 Bytes
6c6fa5f 3299552 6c6fa5f 3299552 6c6fa5f 3299552 6c6fa5f 3299552 6c6fa5f 3299552 6c6fa5f 3299552 6c6fa5f 3299552 6c6fa5f 3299552 6c6fa5f 3299552 6c6fa5f 3299552 6c6fa5f 3299552 6c6fa5f |
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 |
import axios from 'axios';
// Replace with your actual HF Space backend URL
const API_BASE_URL = process.env.REACT_APP_API_URL || 'https://humblebeeai-al-ghazali-rag-retrieval-api.hf.space';
const api = axios.create({
baseURL: API_BASE_URL,
headers: {
'Content-Type': 'application/json',
},
});
// Helper to get tokens from localStorage
function getAuthTokens() {
const tokens = localStorage.getItem('authTokens');
return tokens ? JSON.parse(tokens) : null;
}
// Request interceptor to add auth token
api.interceptors.request.use(
(config) => {
const tokens = getAuthTokens();
if (tokens?.access) {
config.headers['Authorization'] = `Bearer ${tokens.access}`;
}
return config;
},
(error) => Promise.reject(error)
);
// Response interceptor to handle token refresh
api.interceptors.response.use(
(response) => response,
async (error) => {
const originalRequest = error.config;
if (error.response && error.response.status === 401 && !originalRequest._retry) {
originalRequest._retry = true;
try {
const tokens = getAuthTokens();
if (!tokens?.refresh) throw new Error('No refresh token');
const response = await axios.post(`${API_BASE_URL}/refresh`, {
refresh_token: tokens.refresh
});
const newTokens = {
access: response.data.access_token,
refresh: response.data.refresh_token
};
localStorage.setItem('authTokens', JSON.stringify(newTokens));
originalRequest.headers['Authorization'] = `Bearer ${newTokens.access}`;
return api(originalRequest);
} catch (refreshError) {
localStorage.removeItem('authTokens');
window.location.href = '/';
return Promise.reject(refreshError);
}
}
return Promise.reject(error);
}
);
export default api; |