File size: 1,515 Bytes
05ec3fd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f490278
 
 
 
a1d42fd
05ec3fd
a1d42fd
05ec3fd
 
 
fe90915
05ec3fd
 
fe90915
 
 
 
05ec3fd
fe90915
 
 
 
 
 
 
05ec3fd
 
 
 
 
 
 
 
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
import axios from 'axios';

// Function to get the CSRF token from the cookie
function getCookie(name) {
  let cookieValue = null;
  if (document.cookie && document.cookie !== '') {
    const cookies = document.cookie.split(';');
    for (let i = 0; i < cookies.length; i++) {
      const cookie = cookies[i].trim();
      // Does this cookie string begin with the name we want?
      if (cookie.substring(0, name.length + 1) === (name + '=')) {
        cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
        break;
      }
    }
  }
  return cookieValue;
}

const runtimeDefaultBase = (typeof window !== 'undefined' && window.location && window.location.port === '3000')
  ? 'http://127.0.0.1:8000/api'
  : '/api';
const API_BASE_URL = process.env.REACT_APP_API_BASE_URL || runtimeDefaultBase;

const api = axios.create({
  baseURL: API_BASE_URL,
  withCredentials: true, // This is crucial for sending session cookies
});

// Add a request interceptor to include both CSRF token and Huggingface token
api.interceptors.request.use(
  (config) => {
    // Add CSRF token
    const csrfToken = getCookie('csrftoken');
    if (csrfToken) {
      config.headers['X-CSRFToken'] = csrfToken;
    }
    
    // Add Huggingface token if available
    const hfToken = localStorage.getItem('huggingfaceToken');
    if (hfToken) {
      config.headers['Authorization'] = `Bearer ${hfToken}`;
    }
    
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

export default api;