// src/api/auth/authService.ts import { tokenManager } from '../auth/tokenManager'; import { apiClient } from '../base/apiClient'; export interface LoginCredentials { email: string; password: string; } export interface RegisterData { email: string; password: string; full_name: string; tenant_name?: string; } export interface UserProfile { id: string; email: string; full_name: string; tenant_id: string; role: string; is_active: boolean; created_at: string; } class AuthService { async login(credentials: LoginCredentials): Promise { // OAuth2 password flow const formData = new URLSearchParams(); formData.append('username', credentials.email); formData.append('password', credentials.password); formData.append('grant_type', 'password'); const response = await fetch('/api/auth/token', { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded', }, body: formData }); if (!response.ok) { const error = await response.json(); throw new Error(error.detail || 'Login failed'); } const tokenResponse = await response.json(); await tokenManager.storeTokens(tokenResponse); // Get user profile return this.getCurrentUser(); } async register(data: RegisterData): Promise { const response = await apiClient.post('/auth/register', data); // Auto-login after registration await this.login({ email: data.email, password: data.password }); return response; } async logout(): Promise { try { await apiClient.post('/auth/logout'); } finally { tokenManager.clearTokens(); window.location.href = '/login'; } } async getCurrentUser(): Promise { return apiClient.get('/auth/me'); } async updateProfile(updates: Partial): Promise { return apiClient.patch('/auth/profile', updates); } async changePassword(currentPassword: string, newPassword: string): Promise { await apiClient.post('/auth/change-password', { current_password: currentPassword, new_password: newPassword }); } isAuthenticated(): boolean { return tokenManager.isAuthenticated(); } } export const authService = new AuthService();