Files
imphnen-frontend-service/libs/service/src/api/hackathon.ts
T
Maulana SodiqinandClaude da8b08cd73 fix: allow unauthenticated users to view certificates
- Updated API error interceptor to skip redirect on certificate pages
- Prevents 401 errors from redirecting to login on public certificate pages
- Certificate pages can now be viewed without authentication

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-12-10 22:01:37 +07:00

63 lines
1.9 KiB
TypeScript

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();
if (session?.token?.access_token) {
config.headers.Authorization = `Bearer ${session.token.access_token}`;
}
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
// But skip redirect if already on auth pages or certificate pages (to avoid reload on login failure)
if (error.response?.status === 401) {
const isAuthPage = globalThis.window !== undefined && globalThis.location.pathname.startsWith('/auth');
const isCertificatePage = globalThis.window !== undefined && globalThis.location.pathname.startsWith('/certificate/');
// Only clear session and redirect if not on auth page or certificate page
if (!isAuthPage && !isCertificatePage) {
useAuthStore.getState().clearSession();
if (globalThis.window !== undefined) {
globalThis.location.href = '/auth/login';
}
}
}
// 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;
}