2025-11-28 13:09:53 +07:00
|
|
|
import axios from 'axios';
|
|
|
|
|
import { useAuthStore } from '../hooks/auth';
|
|
|
|
|
|
|
|
|
|
// Hackathon Backend API Base URL
|
|
|
|
|
const HACKATHON_API_URL = 'https://api.hackathon.imphnen.dev/api/v1';
|
|
|
|
|
|
|
|
|
|
// Create axios instance for hackathon backend
|
|
|
|
|
export const hackathonApi = axios.create({
|
|
|
|
|
baseURL: HACKATHON_API_URL,
|
|
|
|
|
headers: {
|
|
|
|
|
'Content-Type': 'application/json',
|
|
|
|
|
},
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
// Add auth token interceptor
|
|
|
|
|
hackathonApi.interceptors.request.use(
|
|
|
|
|
(config) => {
|
|
|
|
|
const { session } = useAuthStore.getState();
|
2025-11-28 17:40:34 +07:00
|
|
|
if (session?.token?.access_token) {
|
|
|
|
|
config.headers.Authorization = `Bearer ${session.token.access_token}`;
|
2025-11-28 13:09:53 +07:00
|
|
|
}
|
|
|
|
|
return config;
|
|
|
|
|
},
|
|
|
|
|
(error) => {
|
|
|
|
|
return Promise.reject(new Error(error.message || 'Request failed'));
|
|
|
|
|
}
|
|
|
|
|
);
|
|
|
|
|
|
|
|
|
|
// Error handling interceptor
|
|
|
|
|
hackathonApi.interceptors.response.use(
|
|
|
|
|
(response) => response,
|
|
|
|
|
(error) => {
|
|
|
|
|
// Handle 401 - clear session and redirect to login
|
2025-12-10 22:01:37 +07:00
|
|
|
// But skip redirect if already on auth pages or certificate pages (to avoid reload on login failure)
|
2025-11-28 13:09:53 +07:00
|
|
|
if (error.response?.status === 401) {
|
2025-11-29 11:24:23 +07:00
|
|
|
const isAuthPage = globalThis.window !== undefined && globalThis.location.pathname.startsWith('/auth');
|
2025-12-10 22:01:37 +07:00
|
|
|
const isCertificatePage = globalThis.window !== undefined && globalThis.location.pathname.startsWith('/certificate/');
|
2025-11-29 11:24:23 +07:00
|
|
|
|
2025-12-10 22:01:37 +07:00
|
|
|
// Only clear session and redirect if not on auth page or certificate page
|
|
|
|
|
if (!isAuthPage && !isCertificatePage) {
|
2025-11-29 11:24:23 +07:00
|
|
|
useAuthStore.getState().clearSession();
|
|
|
|
|
if (globalThis.window !== undefined) {
|
|
|
|
|
globalThis.location.href = '/auth/login';
|
|
|
|
|
}
|
2025-11-28 13:09:53 +07:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// If backend sends a message, use it
|
|
|
|
|
const backendMsg = error?.response?.data?.message;
|
|
|
|
|
if (backendMsg && typeof backendMsg === 'string') {
|
|
|
|
|
return Promise.reject(new Error(backendMsg));
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return Promise.reject(new Error(error.message || 'Request failed'));
|
|
|
|
|
}
|
|
|
|
|
);
|
|
|
|
|
|
|
|
|
|
// API Response wrapper type
|
|
|
|
|
export interface HackathonApiResponse<T> {
|
|
|
|
|
data: T;
|
|
|
|
|
message?: string;
|
|
|
|
|
}
|