164 lines
4.7 KiB
JavaScript
164 lines
4.7 KiB
JavaScript
import AsyncStorage from '@react-native-async-storage/async-storage';
|
|
import { API_CONFIG } from '../constants/api';
|
|
|
|
class AuthService {
|
|
async getStoredToken() {
|
|
try {
|
|
return await AsyncStorage.getItem('auth_token');
|
|
} catch (error) {
|
|
return null;
|
|
}
|
|
}
|
|
|
|
async makeRequest(endpoint, data, requiresAuth = false, method = 'POST') {
|
|
const fullUrl = `${API_CONFIG.BASE_URL}${endpoint}`;
|
|
const requestId = Math.random().toString(36).substr(2, 9);
|
|
|
|
try {
|
|
const headers = {
|
|
...API_CONFIG.HEADERS,
|
|
};
|
|
|
|
// Auto-include token for authenticated requests
|
|
if (requiresAuth) {
|
|
const token = await this.getStoredToken();
|
|
if (token) {
|
|
headers.Authorization = `Bearer ${token}`;
|
|
}
|
|
}
|
|
|
|
// Log request details
|
|
console.log(`\n🚀 [${requestId}] API REQUEST`);
|
|
console.log(`📍 URL: ${method} ${fullUrl}`);
|
|
console.log(`🔐 Auth Required: ${requiresAuth}`);
|
|
console.log(`📝 Headers:`, {
|
|
...headers,
|
|
Authorization: headers.Authorization ? `Bearer ${headers.Authorization.slice(-10)}...` : 'None'
|
|
});
|
|
if (data) {
|
|
console.log(`📦 Body:`, data);
|
|
}
|
|
console.log(`⏰ Time: ${new Date().toISOString()}`);
|
|
|
|
const startTime = Date.now();
|
|
|
|
const response = await fetch(fullUrl, {
|
|
method,
|
|
headers,
|
|
body: data ? JSON.stringify(data) : undefined,
|
|
});
|
|
|
|
const endTime = Date.now();
|
|
const duration = endTime - startTime;
|
|
|
|
const result = await response.json();
|
|
|
|
// Log response details
|
|
console.log(`\n✅ [${requestId}] API RESPONSE`);
|
|
console.log(`📊 Status: ${response.status} ${response.statusText}`);
|
|
console.log(`⏱️ Duration: ${duration}ms`);
|
|
console.log(`📄 Response:`, result);
|
|
|
|
if (!response.ok) {
|
|
console.log(`❌ [${requestId}] API ERROR`);
|
|
console.log(`🔴 Status: ${response.status}`);
|
|
console.log(`💬 Error Message:`, result.message || 'Unknown error');
|
|
|
|
// Handle token expiration
|
|
if (response.status === 401 && requiresAuth) {
|
|
console.log(`🔓 [${requestId}] TOKEN EXPIRED - Clearing storage`);
|
|
await AsyncStorage.removeItem('auth_token');
|
|
await AsyncStorage.removeItem('user_data');
|
|
throw new Error('Session expired. Please login again.');
|
|
}
|
|
throw new Error(result.message || 'An error occurred');
|
|
}
|
|
|
|
console.log(`✨ [${requestId}] REQUEST COMPLETED SUCCESSFULLY\n`);
|
|
return result;
|
|
} catch (error) {
|
|
console.log(`\n💥 [${requestId}] API REQUEST FAILED`);
|
|
console.log(`📍 URL: ${method} ${fullUrl}`);
|
|
console.log(`🔴 Error:`, error.message);
|
|
console.log(`📅 Time: ${new Date().toISOString()}\n`);
|
|
|
|
throw new Error(error.message || 'Network error');
|
|
}
|
|
}
|
|
|
|
async login(phone, password) {
|
|
return this.makeRequest(API_CONFIG.ENDPOINTS.AUTH.LOGIN, {
|
|
phone: parseInt(phone),
|
|
password,
|
|
});
|
|
}
|
|
|
|
async register(phone, name, password) {
|
|
return this.makeRequest(API_CONFIG.ENDPOINTS.AUTH.REGISTER, {
|
|
phone: parseInt(phone),
|
|
name,
|
|
password,
|
|
});
|
|
}
|
|
|
|
async verify(phone, code) {
|
|
return this.makeRequest(API_CONFIG.ENDPOINTS.AUTH.VERIFY, {
|
|
phone: parseInt(phone),
|
|
code: parseInt(code),
|
|
});
|
|
}
|
|
|
|
// Authenticated API methods
|
|
async getProfile() {
|
|
return this.makeRequest('/profile', null, true, 'GET');
|
|
}
|
|
|
|
async updateProfile(data) {
|
|
return this.makeRequest('/profile', data, true, 'POST');
|
|
}
|
|
|
|
async getTransactions(page = 1, limit = 20) {
|
|
return this.makeRequest(`/user/transactions?page=${page}&limit=${limit}`, null, true, 'GET');
|
|
}
|
|
|
|
async getBalance() {
|
|
return this.makeRequest('/user/balance', null, true, 'GET');
|
|
}
|
|
|
|
async transferMoney(data) {
|
|
return this.makeRequest('/user/transfer', data, true);
|
|
}
|
|
|
|
async payBill(data) {
|
|
return this.makeRequest('/user/pay-bill', data, true);
|
|
}
|
|
|
|
async getCards() {
|
|
return this.makeRequest('/user/cards', null, true, 'GET');
|
|
}
|
|
|
|
async addCard(data) {
|
|
return this.makeRequest('/user/cards', data, true);
|
|
}
|
|
|
|
async blockCard(cardId) {
|
|
return this.makeRequest(`/user/cards/${cardId}/block`, null, true);
|
|
}
|
|
|
|
async unblockCard(cardId) {
|
|
return this.makeRequest(`/user/cards/${cardId}/unblock`, null, true);
|
|
}
|
|
|
|
async changePassword(currentPassword, newPassword) {
|
|
return this.makeRequest('/user/change-password', {
|
|
current_password: currentPassword,
|
|
new_password: newPassword,
|
|
}, true);
|
|
}
|
|
|
|
async deleteAccount() {
|
|
return this.makeRequest('/user/delete-account', null, true, 'DELETE');
|
|
}
|
|
}
|
|
|
|
export default new AuthService();
|