* Make authenticated API request
(endpoint, options = {})
| 9 | * Make authenticated API request |
| 10 | */ |
| 11 | async function apiRequest(endpoint, options = {}) { |
| 12 | const config = { |
| 13 | ...options, |
| 14 | credentials: 'include', // Send cookies for session authentication |
| 15 | headers: { |
| 16 | 'Content-Type': 'application/json', |
| 17 | ...options.headers, |
| 18 | }, |
| 19 | }; |
| 20 | |
| 21 | try { |
| 22 | const response = await fetch(`${API_BASE}${endpoint}`, config); |
| 23 | |
| 24 | // Handle authentication errors |
| 25 | if (response.status === 401) { |
| 26 | // Redirect to login if unauthorized |
| 27 | window.location.href = '/login'; |
| 28 | throw new Error('Unauthorized - please log in'); |
| 29 | } |
| 30 | |
| 31 | const data = await response.json(); |
| 32 | |
| 33 | if (!response.ok) { |
| 34 | const error = new Error(data.error || data.message || 'Request failed'); |
| 35 | error.status = response.status; |
| 36 | error.data = data; |
| 37 | throw error; |
| 38 | } |
| 39 | |
| 40 | return data; |
| 41 | } catch (error) { |
| 42 | console.error('API Request Error:', error); |
| 43 | throw error; |
| 44 | } |
| 45 | } |
| 46 | |
| 47 | // ==================== AUTH ENDPOINTS ==================== |
| 48 |