/** * API Client Service for Face Inference Platform */ import axios, { AxiosInstance } from 'axios'; import { AuthResponse, RegisterResponse, LoginRequest, RegisterRequest, FaceEmbedding, RecognitionLog, AdminAnalytics, User, APIKey, APIKeyCreateResponse, UsageMeter, } from '../types'; const API_BASE_URL = import.meta.env.VITE_API_URL || 'http://localhost:8000'; class APIClient { private client: AxiosInstance; private accessToken: string | null = null; constructor() { this.client = axios.create({ baseURL: API_BASE_URL, headers: { 'Content-Type': 'application/json', }, }); // Restore token from localStorage this.accessToken = localStorage.getItem('access_token'); this.updateAuthHeader(); // Request interceptor this.client.interceptors.request.use((config) => { if (this.accessToken) { config.headers.Authorization = `Bearer ${this.accessToken}`; } return config; }); // Response interceptor this.client.interceptors.response.use( (response) => response, async (error) => { const originalRequest = error.config; // Handle 401 - try refresh token if (error.response?.status === 401 && !originalRequest._retry) { originalRequest._retry = true; const refreshToken = localStorage.getItem('refresh_token'); if (refreshToken) { try { const response = await this.refreshToken(refreshToken); this.setTokens(response.access_token, response.refresh_token); return this.client(originalRequest); } catch (refreshError) { // Refresh failed, logout this.logout(); window.location.href = '/login'; } } } return Promise.reject(error); } ); } // Auth endpoints async register(data: RegisterRequest): Promise { const response = await this.client.post('/api/auth/register', data); return response.data; } async login(data: LoginRequest): Promise { const response = await this.client.post('/api/auth/login', data); return response.data; } async refreshToken(refreshToken: string): Promise { const response = await this.client.post('/api/auth/refresh', { refresh_token: refreshToken, }); return response.data; } async getCurrentUser(): Promise { const response = await this.client.get('/api/auth/me'); return response.data; } // Face endpoints async registerFace(formData: FormData): Promise { const response = await this.client.post( '/api/face/register', formData, { headers: { 'Content-Type': 'multipart/form-data', }, } ); return response.data; } async recognizeFace(formData: FormData): Promise { const response = await this.client.post( '/api/face/recognize', formData, { headers: { 'Content-Type': 'multipart/form-data', }, } ); return response.data; } async listEmbeddings(personId?: string, skip: number = 0, limit: number = 100): Promise { const params = { skip, limit }; if (personId) { (params as any).person_id = personId; } const response = await this.client.get( '/api/face/embeddings', { params } ); return response.data; } async listRecognitionLogs(skip: number = 0, limit: number = 100): Promise { const response = await this.client.get( '/api/face/logs', { params: { skip, limit } } ); return response.data; } async deleteEmbedding(embeddingId: string): Promise { await this.client.delete(`/api/face/embeddings/${embeddingId}`); } // Admin endpoints async getAnalytics(): Promise { const response = await this.client.get('/api/admin/analytics'); return response.data; } async listUsers(skip: number = 0, limit: number = 100): Promise { const response = await this.client.get( '/api/admin/users', { params: { skip, limit } } ); return response.data; } async deleteUser(userId: string): Promise { await this.client.delete(`/api/admin/users/${userId}`); } async listApiKeys(): Promise { const response = await this.client.get('/api/admin/api-keys'); return response.data; } async createApiKey(keyName: string): Promise { const response = await this.client.post('/api/admin/api-keys', { key_name: keyName, }); return response.data; } async revokeApiKey(apiKeyId: string): Promise { const response = await this.client.delete(`/api/admin/api-keys/${apiKeyId}`); return response.data; } async listMyApiKeys(): Promise { const response = await this.client.get('/api/keys'); return response.data; } async createMyApiKey(keyName: string): Promise { const response = await this.client.post('/api/keys', { key_name: keyName, }); return response.data; } async revokeMyApiKey(apiKeyId: string): Promise { const response = await this.client.delete(`/api/keys/${apiKeyId}`); return response.data; } async getUsage(period?: string): Promise { const response = await this.client.get('/api/admin/usage', { params: period ? { period } : undefined, }); return response.data; } // Token management setTokens(accessToken: string, refreshToken: string): void { this.accessToken = accessToken; localStorage.setItem('access_token', accessToken); localStorage.setItem('refresh_token', refreshToken); this.updateAuthHeader(); } private updateAuthHeader(): void { if (this.accessToken) { this.client.defaults.headers.common['Authorization'] = `Bearer ${this.accessToken}`; } else { delete this.client.defaults.headers.common['Authorization']; } } logout(): void { this.accessToken = null; localStorage.removeItem('access_token'); localStorage.removeItem('refresh_token'); this.updateAuthHeader(); } getAccessToken(): string | null { return this.accessToken; } isAuthenticated(): boolean { return !!this.accessToken; } // Health check async healthCheck(): Promise<{ status: string }> { const response = await this.client.get('/health'); return response.data; } } export default new APIClient();