canina/frontend/application/lib/services/authService.ts

103 lines
2.7 KiB
TypeScript

import api from './api';
export interface User {
id: string;
firstName: string;
lastName: string;
email: string;
mobile: string | null;
role: string;
walletBalance: number;
charityDonationTotal: number;
createdAt: string;
updatedAt: string;
pets?: any[];
orders?: any[];
}
export interface AuthResponse {
success: boolean;
data: {
user: User;
accessToken: string;
};
}
export class AuthService {
private static instance: AuthService;
private constructor() {}
public static getInstance(): AuthService {
if (!AuthService.instance) {
AuthService.instance = new AuthService();
}
return AuthService.instance;
}
/**
* Send SMS verification code (OTP)
*/
public async sendOtp(phoneNumber: string): Promise<{ success: boolean; message: string }> {
try {
const response = await api.post('/auth/send-otp', { phoneNumber });
return response.data;
} catch (error: any) {
const message = error.response?.data?.message || 'خطا در ارسال کد تایید';
throw new Error(Array.isArray(message) ? message[0] : message);
}
}
/**
* Verify SMS verification code and login/register
*/
public async verifyOtp(phoneNumber: string, code: string): Promise<AuthResponse> {
try {
const response = await api.post('/auth/verify-otp', { phoneNumber, code });
const { data } = response.data;
if (data?.accessToken) {
localStorage.setItem('accessToken', data.accessToken);
}
return response.data;
} catch (error: any) {
const message = error.response?.data?.message || 'کد تایید نامعتبر است';
throw new Error(Array.isArray(message) ? message[0] : message);
}
}
/**
* Get current user profile
*/
public async getProfile(): Promise<User> {
try {
const response = await api.get('/users/profile');
return response.data;
} catch (error: any) {
const message = error.response?.data?.message || 'خطا در دریافت اطلاعات کاربری';
throw new Error(Array.isArray(message) ? message[0] : message);
}
}
/**
* Update current user profile
*/
public async updateProfile(profileData: Partial<User>): Promise<User> {
try {
const response = await api.patch('/users/profile', profileData);
return response.data;
} catch (error: any) {
const message = error.response?.data?.message || 'خطا در ویرایش اطلاعات کاربری';
throw new Error(Array.isArray(message) ? message[0] : message);
}
}
/**
* Logout user and clear tokens
*/
public logout(): void {
localStorage.removeItem('accessToken');
}
}
export const authService = AuthService.getInstance();