File size: 6,925 Bytes
4854e2b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
/**
 * 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<RegisterResponse> {
    const response = await this.client.post<RegisterResponse>('/api/auth/register', data);
    return response.data;
  }

  async login(data: LoginRequest): Promise<AuthResponse> {
    const response = await this.client.post<AuthResponse>('/api/auth/login', data);
    return response.data;
  }

  async refreshToken(refreshToken: string): Promise<AuthResponse> {
    const response = await this.client.post<AuthResponse>('/api/auth/refresh', {
      refresh_token: refreshToken,
    });
    return response.data;
  }

  async getCurrentUser(): Promise<User> {
    const response = await this.client.get<User>('/api/auth/me');
    return response.data;
  }

  // Face endpoints
  async registerFace(formData: FormData): Promise<FaceEmbedding> {
    const response = await this.client.post<FaceEmbedding>(
      '/api/face/register',
      formData,
      {
        headers: {
          'Content-Type': 'multipart/form-data',
        },
      }
    );
    return response.data;
  }

  async recognizeFace(formData: FormData): Promise<import('../types').FaceRecognitionResult> {
    const response = await this.client.post<import('../types').FaceRecognitionResult>(
      '/api/face/recognize',
      formData,
      {
        headers: {
          'Content-Type': 'multipart/form-data',
        },
      }
    );
    return response.data;
  }

  async listEmbeddings(personId?: string, skip: number = 0, limit: number = 100): Promise<FaceEmbedding[]> {
    const params = { skip, limit };
    if (personId) {
      (params as any).person_id = personId;
    }
    const response = await this.client.get<FaceEmbedding[]>(
      '/api/face/embeddings',
      { params }
    );
    return response.data;
  }

  async listRecognitionLogs(skip: number = 0, limit: number = 100): Promise<RecognitionLog[]> {
    const response = await this.client.get<RecognitionLog[]>(
      '/api/face/logs',
      { params: { skip, limit } }
    );
    return response.data;
  }

  async deleteEmbedding(embeddingId: string): Promise<void> {
    await this.client.delete(`/api/face/embeddings/${embeddingId}`);
  }

  // Admin endpoints
  async getAnalytics(): Promise<AdminAnalytics> {
    const response = await this.client.get<AdminAnalytics>('/api/admin/analytics');
    return response.data;
  }

  async listUsers(skip: number = 0, limit: number = 100): Promise<User[]> {
    const response = await this.client.get<User[]>(
      '/api/admin/users',
      { params: { skip, limit } }
    );
    return response.data;
  }

  async deleteUser(userId: string): Promise<void> {
    await this.client.delete(`/api/admin/users/${userId}`);
  }

  async listApiKeys(): Promise<APIKey[]> {
    const response = await this.client.get<APIKey[]>('/api/admin/api-keys');
    return response.data;
  }

  async createApiKey(keyName: string): Promise<APIKeyCreateResponse> {
    const response = await this.client.post<APIKeyCreateResponse>('/api/admin/api-keys', {
      key_name: keyName,
    });
    return response.data;
  }

  async revokeApiKey(apiKeyId: string): Promise<APIKey> {
    const response = await this.client.delete<APIKey>(`/api/admin/api-keys/${apiKeyId}`);
    return response.data;
  }

  async listMyApiKeys(): Promise<APIKey[]> {
    const response = await this.client.get<APIKey[]>('/api/keys');
    return response.data;
  }

  async createMyApiKey(keyName: string): Promise<APIKeyCreateResponse> {
    const response = await this.client.post<APIKeyCreateResponse>('/api/keys', {
      key_name: keyName,
    });
    return response.data;
  }

  async revokeMyApiKey(apiKeyId: string): Promise<APIKey> {
    const response = await this.client.delete<APIKey>(`/api/keys/${apiKeyId}`);
    return response.data;
  }

  async getUsage(period?: string): Promise<UsageMeter> {
    const response = await this.client.get<UsageMeter>('/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();