Files
bakery-ia/frontend/src/api/services/authService.ts

91 lines
2.2 KiB
TypeScript
Raw Normal View History

2025-07-22 07:37:51 +02:00
// src/api/auth/authService.ts
2025-07-22 08:50:18 +02:00
import { tokenManager } from '../auth/tokenManager';
2025-07-22 07:37:51 +02:00
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<UserProfile> {
// OAuth2 password flow
const formData = new URLSearchParams();
formData.append('username', credentials.email);
formData.append('password', credentials.password);
formData.append('grant_type', 'password');
2025-07-22 10:17:41 +02:00
const response = await fetch('/auth/login', {
2025-07-22 07:37:51 +02:00
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<UserProfile> {
const response = await apiClient.post('/auth/register', data);
return response;
}
async logout(): Promise<void> {
try {
await apiClient.post('/auth/logout');
} finally {
tokenManager.clearTokens();
window.location.href = '/login';
}
}
async getCurrentUser(): Promise<UserProfile> {
return apiClient.get('/auth/me');
}
async updateProfile(updates: Partial<UserProfile>): Promise<UserProfile> {
return apiClient.patch('/auth/profile', updates);
}
async changePassword(currentPassword: string, newPassword: string): Promise<void> {
await apiClient.post('/auth/change-password', {
current_password: currentPassword,
new_password: newPassword
});
}
isAuthenticated(): boolean {
return tokenManager.isAuthenticated();
}
}
export const authService = new AuthService();