import axios from 'axios'; import Cookies from 'js-cookie'; // Cookie keys export const ADMIN_TOKEN_KEY = 'admin_token'; export const GALLERY_TOKEN_KEY = 'gallery_token'; // Create axios instance export const api = axios.create({ baseURL: import.meta.env.VITE_API_URL || 'http://localhost:3002', headers: { 'Content-Type': 'application/json', }, }); // Request interceptor to add auth token api.interceptors.request.use( (config) => { // Check if it's an admin route or gallery route const isAdminRoute = config.url?.includes('/admin'); const token = isAdminRoute ? Cookies.get(ADMIN_TOKEN_KEY) : Cookies.get(GALLERY_TOKEN_KEY); if (token) { config.headers.Authorization = `Bearer ${token}`; } return config; }, (error) => { return Promise.reject(error); } ); // Response interceptor to handle errors api.interceptors.response.use( (response) => response, (error) => { if (error.response?.status === 401) { // Clear tokens on unauthorized Cookies.remove(ADMIN_TOKEN_KEY); Cookies.remove(GALLERY_TOKEN_KEY); // Redirect to appropriate login const isAdminRoute = error.config?.url?.includes('/admin'); if (isAdminRoute) { window.location.href = '/admin/login'; } else { // For gallery routes, redirect to the gallery password page const currentPath = window.location.pathname; const gallerySlug = currentPath.split('/')[2]; if (gallerySlug) { window.location.href = `/gallery/${gallerySlug}`; } } } return Promise.reject(error); } ); // Helper to set auth tokens export const setAuthToken = (token: string, isAdmin: boolean = false) => { const key = isAdmin ? ADMIN_TOKEN_KEY : GALLERY_TOKEN_KEY; Cookies.set(key, token, { expires: 1 }); // 1 day expiry }; // Helper to clear auth tokens export const clearAuthToken = (isAdmin: boolean = false) => { const key = isAdmin ? ADMIN_TOKEN_KEY : GALLERY_TOKEN_KEY; Cookies.remove(key); }; // Helper to get auth tokens export const getAuthToken = (isAdmin: boolean = false) => { const key = isAdmin ? ADMIN_TOKEN_KEY : GALLERY_TOKEN_KEY; return Cookies.get(key); };