Spaces:
Paused
Paused
shanshel6 commited on
Commit ·
bcdbc4e
1
Parent(s): c8a4ec0
Bump version to 1.0.6, fix login failure, and enhance admin settings for Google Play review
Browse files- capacitor.config.ts +1 -1
- server/index.js +20 -4
- src/pages/Login.tsx +15 -7
- src/pages/VerifyOTP.tsx +31 -1
- src/services/api.ts +142 -23
capacitor.config.ts
CHANGED
|
@@ -8,7 +8,7 @@ const config: CapacitorConfig = {
|
|
| 8 |
// When using a physical device, the app cannot reach 10.0.2.2 (which is only for emulators).
|
| 9 |
// For production/physical device testing, we should use the local dist files.
|
| 10 |
// In dev mode with 'npx cap run android', the CLI will automatically handle live reload URLs if configured.
|
| 11 |
-
androidScheme: '
|
| 12 |
cleartext: true
|
| 13 |
},
|
| 14 |
plugins: {
|
|
|
|
| 8 |
// When using a physical device, the app cannot reach 10.0.2.2 (which is only for emulators).
|
| 9 |
// For production/physical device testing, we should use the local dist files.
|
| 10 |
// In dev mode with 'npx cap run android', the CLI will automatically handle live reload URLs if configured.
|
| 11 |
+
androidScheme: 'http',
|
| 12 |
cleartext: true
|
| 13 |
},
|
| 14 |
plugins: {
|
server/index.js
CHANGED
|
@@ -227,7 +227,7 @@ io.on('connection', (socket) => {
|
|
| 227 |
});
|
| 228 |
});
|
| 229 |
|
| 230 |
-
const PORT = process.env.PORT ||
|
| 231 |
const JWT_SECRET = process.env.JWT_SECRET || 'c2hhbnNoYWw2Ni1teS1zaG9wLWJhY2tlbmQtc2VjcmV0LTIwMjY=';
|
| 232 |
|
| 233 |
// --- Normalization Helpers ---
|
|
@@ -426,7 +426,18 @@ const authenticateToken = async (req, res, next) => {
|
|
| 426 |
try {
|
| 427 |
// Try Supabase Auth first
|
| 428 |
console.log('[Auth] Checking Supabase token...');
|
| 429 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 430 |
|
| 431 |
if (supabaseUser) {
|
| 432 |
console.log('[Auth] Supabase user found:', supabaseUser.email);
|
|
@@ -514,8 +525,13 @@ const authenticateToken = async (req, res, next) => {
|
|
| 514 |
return res.status(401).json({ error: 'Invalid or expired token' });
|
| 515 |
}
|
| 516 |
} catch (error) {
|
| 517 |
-
console.error('[Auth] Unexpected error:', error
|
| 518 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 519 |
}
|
| 520 |
};
|
| 521 |
|
|
|
|
| 227 |
});
|
| 228 |
});
|
| 229 |
|
| 230 |
+
const PORT = process.env.PORT || 5001;
|
| 231 |
const JWT_SECRET = process.env.JWT_SECRET || 'c2hhbnNoYWw2Ni1teS1zaG9wLWJhY2tlbmQtc2VjcmV0LTIwMjY=';
|
| 232 |
|
| 233 |
// --- Normalization Helpers ---
|
|
|
|
| 426 |
try {
|
| 427 |
// Try Supabase Auth first
|
| 428 |
console.log('[Auth] Checking Supabase token...');
|
| 429 |
+
let supabaseUser = null;
|
| 430 |
+
let supabaseError = null;
|
| 431 |
+
|
| 432 |
+
try {
|
| 433 |
+
// Only try Supabase if it looks like a Supabase token or if we want to be safe
|
| 434 |
+
// Supabase tokens are usually very long JWTs
|
| 435 |
+
const result = await supabase.auth.getUser(token);
|
| 436 |
+
supabaseUser = result.data?.user;
|
| 437 |
+
supabaseError = result.error;
|
| 438 |
+
} catch (sbErr) {
|
| 439 |
+
console.log('[Auth] Supabase getUser threw error (probably not a Supabase token):', sbErr.message);
|
| 440 |
+
}
|
| 441 |
|
| 442 |
if (supabaseUser) {
|
| 443 |
console.log('[Auth] Supabase user found:', supabaseUser.email);
|
|
|
|
| 525 |
return res.status(401).json({ error: 'Invalid or expired token' });
|
| 526 |
}
|
| 527 |
} catch (error) {
|
| 528 |
+
console.error('[Auth] Unexpected error during authentication:', error);
|
| 529 |
+
if (error.stack) console.error(error.stack);
|
| 530 |
+
return res.status(401).json({
|
| 531 |
+
error: 'Authentication failed',
|
| 532 |
+
details: error.message,
|
| 533 |
+
stack: process.env.NODE_ENV === 'development' ? error.stack : undefined
|
| 534 |
+
});
|
| 535 |
}
|
| 536 |
};
|
| 537 |
|
src/pages/Login.tsx
CHANGED
|
@@ -14,7 +14,7 @@ const Login: React.FC = () => {
|
|
| 14 |
const showToast = useToastStore((state) => state.showToast);
|
| 15 |
|
| 16 |
const [method, setMethod] = useState<'phone' | 'email'>('phone');
|
| 17 |
-
const [countryCode, setCountryCode] = useState('+
|
| 18 |
const [phoneNumber, setPhoneNumber] = useState('');
|
| 19 |
const [email, setEmail] = useState('');
|
| 20 |
const [password, setPassword] = useState('');
|
|
@@ -177,19 +177,27 @@ const Login: React.FC = () => {
|
|
| 177 |
|
| 178 |
if (testAccount) {
|
| 179 |
// Simulate successful login for test accounts
|
| 180 |
-
const token = 'test-token-' + Date.now();
|
| 181 |
const user = {
|
| 182 |
id: 'reviewer-' + Date.now(),
|
| 183 |
phone: testAccount.phone,
|
| 184 |
name: testAccount.name,
|
| 185 |
email: testAccount.email,
|
| 186 |
-
role:
|
| 187 |
};
|
| 188 |
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
showToast('تم
|
| 192 |
-
navigate('/'
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 193 |
return true;
|
| 194 |
}
|
| 195 |
return false;
|
|
|
|
| 14 |
const showToast = useToastStore((state) => state.showToast);
|
| 15 |
|
| 16 |
const [method, setMethod] = useState<'phone' | 'email'>('phone');
|
| 17 |
+
const [countryCode, setCountryCode] = useState('+1');
|
| 18 |
const [phoneNumber, setPhoneNumber] = useState('');
|
| 19 |
const [email, setEmail] = useState('');
|
| 20 |
const [password, setPassword] = useState('');
|
|
|
|
| 177 |
|
| 178 |
if (testAccount) {
|
| 179 |
// Simulate successful login for test accounts
|
| 180 |
+
const token = 'test-token-' + normalizedPhone + '-' + Date.now();
|
| 181 |
const user = {
|
| 182 |
id: 'reviewer-' + Date.now(),
|
| 183 |
phone: testAccount.phone,
|
| 184 |
name: testAccount.name,
|
| 185 |
email: testAccount.email,
|
| 186 |
+
role: normalizedPhone.includes('1987654321') ? 'ADMIN' : 'USER'
|
| 187 |
};
|
| 188 |
|
| 189 |
+
// Simulation for Google Play reviewers
|
| 190 |
+
// Navigate to verify-otp with a special flag
|
| 191 |
+
showToast('تم إرسال كود التحقق (للمراجعة: 123456)', 'info', 5000);
|
| 192 |
+
navigate('/verify-otp', {
|
| 193 |
+
state: {
|
| 194 |
+
phone: normalizedPhone,
|
| 195 |
+
type: 'login',
|
| 196 |
+
isTestAccount: true,
|
| 197 |
+
testUser: user,
|
| 198 |
+
testToken: token
|
| 199 |
+
}
|
| 200 |
+
});
|
| 201 |
return true;
|
| 202 |
}
|
| 203 |
return false;
|
src/pages/VerifyOTP.tsx
CHANGED
|
@@ -67,9 +67,32 @@ const VerifyOTP: React.FC = () => {
|
|
| 67 |
return;
|
| 68 |
}
|
| 69 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 70 |
setLoading(true);
|
| 71 |
try {
|
| 72 |
-
const state = location.state as { phone?: string; fullName?: string; type?: 'login' | 'signup' };
|
| 73 |
const { token, user } = await verifyWhatsAppOTP(phone, otpCode, state?.fullName);
|
| 74 |
|
| 75 |
if (token && user) {
|
|
@@ -116,6 +139,13 @@ const VerifyOTP: React.FC = () => {
|
|
| 116 |
لقد أرسلنا كود التحقق إلى <br />
|
| 117 |
<span className="font-bold text-slate-900 dark:text-white" dir="ltr">{phone}</span>
|
| 118 |
</p>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 119 |
</div>
|
| 120 |
|
| 121 |
{/* OTP Input Section */}
|
|
|
|
| 67 |
return;
|
| 68 |
}
|
| 69 |
|
| 70 |
+
const state = location.state as {
|
| 71 |
+
phone?: string;
|
| 72 |
+
fullName?: string;
|
| 73 |
+
type?: 'login' | 'signup';
|
| 74 |
+
isTestAccount?: boolean;
|
| 75 |
+
testUser?: any;
|
| 76 |
+
testToken?: string;
|
| 77 |
+
};
|
| 78 |
+
|
| 79 |
+
// Special handling for test accounts - check BEFORE setting loading
|
| 80 |
+
if (state?.isTestAccount) {
|
| 81 |
+
if (otpCode === '123456') {
|
| 82 |
+
if (state.testToken && state.testUser) {
|
| 83 |
+
setAuth(state.testToken, state.testUser);
|
| 84 |
+
showToast('تم تسجيل الدخول كمراجع تجريبي', 'success');
|
| 85 |
+
navigate('/');
|
| 86 |
+
return;
|
| 87 |
+
}
|
| 88 |
+
} else {
|
| 89 |
+
showToast('كود التحقق غير صحيح', 'error');
|
| 90 |
+
return;
|
| 91 |
+
}
|
| 92 |
+
}
|
| 93 |
+
|
| 94 |
setLoading(true);
|
| 95 |
try {
|
|
|
|
| 96 |
const { token, user } = await verifyWhatsAppOTP(phone, otpCode, state?.fullName);
|
| 97 |
|
| 98 |
if (token && user) {
|
|
|
|
| 139 |
لقد أرسلنا كود التحقق إلى <br />
|
| 140 |
<span className="font-bold text-slate-900 dark:text-white" dir="ltr">{phone}</span>
|
| 141 |
</p>
|
| 142 |
+
{(location.state as any)?.isTestAccount && (
|
| 143 |
+
<div className="mt-4 p-3 bg-blue-50 dark:bg-blue-900/30 border border-blue-200 dark:border-blue-800 rounded-xl animate-bounce">
|
| 144 |
+
<p className="text-blue-700 dark:text-blue-300 text-sm font-bold text-center">
|
| 145 |
+
كود التحقق للمراجعة هو: <span className="text-lg">123456</span>
|
| 146 |
+
</p>
|
| 147 |
+
</div>
|
| 148 |
+
)}
|
| 149 |
</div>
|
| 150 |
|
| 151 |
{/* OTP Input Section */}
|
src/services/api.ts
CHANGED
|
@@ -7,36 +7,43 @@ export const getBaseDomain = () => {
|
|
| 7 |
const envApiUrl = import.meta.env.VITE_API_URL;
|
| 8 |
if (envApiUrl) return envApiUrl;
|
| 9 |
|
| 10 |
-
// 2. Production
|
| 11 |
-
// For production builds, we should always default to the production server
|
| 12 |
-
// unless we are explicitly testing on an emulator.
|
| 13 |
if (import.meta.env.PROD) {
|
| 14 |
-
//
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 15 |
return 'https://shanshal66-my-shop-backend.hf.space';
|
| 16 |
}
|
| 17 |
|
| 18 |
-
// 3.
|
| 19 |
const isCapacitor = window.hasOwnProperty('Capacitor');
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
|
|
|
|
|
|
| 23 |
if (isAndroid) {
|
| 24 |
-
//
|
| 25 |
-
return 'http://10.0.2.2:5000';
|
| 26 |
}
|
| 27 |
-
|
| 28 |
-
// If the hostname is an IP, use it
|
| 29 |
-
if (/^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$/.test(window.location.hostname)) {
|
| 30 |
-
return `http://${window.location.hostname}:5000`;
|
| 31 |
-
}
|
| 32 |
-
|
| 33 |
-
// Fallback for mobile development: use the machine IP
|
| 34 |
-
return 'http://192.168.2.200:5000';
|
| 35 |
}
|
| 36 |
|
| 37 |
// 4. Default local development (Browser)
|
| 38 |
if (window.location.hostname === 'localhost') {
|
| 39 |
-
return 'http://localhost:
|
| 40 |
}
|
| 41 |
|
| 42 |
return 'https://shanshal66-my-shop-backend.hf.space';
|
|
@@ -232,7 +239,8 @@ export function getAuthHeaders() {
|
|
| 232 |
// Base fetch wrapper with caching and retry logic
|
| 233 |
export async function request(endpoint: string, options: any = {}, retries = 2) {
|
| 234 |
const isGet = !options.method || options.method === 'GET';
|
| 235 |
-
const
|
|
|
|
| 236 |
const cacheKey = endpoint;
|
| 237 |
const skipMaintenanceTrigger = options.skipMaintenanceTrigger || false;
|
| 238 |
|
|
@@ -244,6 +252,8 @@ export async function request(endpoint: string, options: any = {}, retries = 2)
|
|
| 244 |
}
|
| 245 |
}
|
| 246 |
|
|
|
|
|
|
|
| 247 |
const executeRequest = async (attempt: number): Promise<any> => {
|
| 248 |
// Priority: 1. options.token, 2. localStorage
|
| 249 |
let token = (options.token || localStorage.getItem('auth_token'))?.trim();
|
|
@@ -252,6 +262,97 @@ export async function request(endpoint: string, options: any = {}, retries = 2)
|
|
| 252 |
if (token === 'null' || token === 'undefined') {
|
| 253 |
token = null;
|
| 254 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 255 |
|
| 256 |
// For admin routes, if token is missing, try to wait a bit or check store
|
| 257 |
if (!token && endpoint.startsWith('/admin')) {
|
|
@@ -261,14 +362,14 @@ export async function request(endpoint: string, options: any = {}, retries = 2)
|
|
| 261 |
const headers: Record<string, string> = {
|
| 262 |
'Accept': 'application/json',
|
| 263 |
'Content-Type': 'application/json',
|
| 264 |
-
...(token ? { 'Authorization': `Bearer ${token}` } : {}),
|
| 265 |
};
|
| 266 |
|
| 267 |
if (options.headers) {
|
| 268 |
Object.assign(headers, options.headers);
|
| 269 |
}
|
| 270 |
|
| 271 |
-
const fullUrl = `${
|
| 272 |
|
| 273 |
try {
|
| 274 |
if (import.meta.env.DEV) {
|
|
@@ -314,6 +415,12 @@ export async function request(endpoint: string, options: any = {}, retries = 2)
|
|
| 314 |
const currentToken = localStorage.getItem('auth_token')?.trim();
|
| 315 |
const requestToken = headers['Authorization']?.replace('Bearer ', '')?.trim();
|
| 316 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 317 |
if (currentToken && currentToken !== requestToken) {
|
| 318 |
console.warn('[API] Detected 401 from old token, retrying with new token...');
|
| 319 |
// Retry once with the current token
|
|
@@ -368,6 +475,18 @@ export async function request(endpoint: string, options: any = {}, retries = 2)
|
|
| 368 |
error.message.includes('Load failed');
|
| 369 |
|
| 370 |
if (attempt < retries && isNetworkError) {
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 371 |
const delay = Math.pow(2, attempt) * 1000;
|
| 372 |
console.warn(`[API Network Error] Retrying ${endpoint} in ${delay}ms... (Attempt ${attempt + 1})`);
|
| 373 |
await new Promise(resolve => setTimeout(resolve, delay));
|
|
@@ -399,7 +518,7 @@ export function clearCache() {
|
|
| 399 |
// Authentication functions using our server
|
| 400 |
export async function fetchMe() {
|
| 401 |
try {
|
| 402 |
-
const user = await request('/auth/me', { skipMaintenanceTrigger: true });
|
| 403 |
if (user && !user.name) {
|
| 404 |
// If server returned user but no name, try to get it from Supabase
|
| 405 |
const { data: { user: sbUser } } = await supabase.auth.getUser();
|
|
|
|
| 7 |
const envApiUrl = import.meta.env.VITE_API_URL;
|
| 8 |
if (envApiUrl) return envApiUrl;
|
| 9 |
|
| 10 |
+
// 2. Production Check (Highest priority for released apps)
|
|
|
|
|
|
|
| 11 |
if (import.meta.env.PROD) {
|
| 12 |
+
// If we're in a PROD build, we should generally use the production backend
|
| 13 |
+
// EXCEPT if we are on an emulator and want to test the prod build against a local backend
|
| 14 |
+
const isCapacitor = window.hasOwnProperty('Capacitor');
|
| 15 |
+
const userAgent = navigator.userAgent.toLowerCase();
|
| 16 |
+
const isAndroid = /android/i.test(userAgent);
|
| 17 |
+
|
| 18 |
+
// Check if we are actually on the production domain or if it's a capacitor app that should connect to prod
|
| 19 |
+
if (window.location.hostname.includes('shanshal66') || window.location.hostname.includes('hf.space') || (isCapacitor && !window.location.hostname.includes('10.0.2.2'))) {
|
| 20 |
+
return 'https://shanshal66-my-shop-backend.hf.space';
|
| 21 |
+
}
|
| 22 |
+
|
| 23 |
+
// If we are in PROD build but running on emulator (10.0.2.2), allow local connection
|
| 24 |
+
if (isAndroid && (window.location.hostname === 'localhost' || window.location.hostname === '10.0.2.2')) {
|
| 25 |
+
return 'http://10.0.2.2:5001';
|
| 26 |
+
}
|
| 27 |
+
|
| 28 |
return 'https://shanshal66-my-shop-backend.hf.space';
|
| 29 |
}
|
| 30 |
|
| 31 |
+
// 3. Mobile / Emulator Check (For development)
|
| 32 |
const isCapacitor = window.hasOwnProperty('Capacitor');
|
| 33 |
+
const userAgent = navigator.userAgent.toLowerCase();
|
| 34 |
+
const isAndroid = /android/i.test(userAgent);
|
| 35 |
+
|
| 36 |
+
if (isCapacitor || isAndroid) {
|
| 37 |
+
// If we're on an Android emulator
|
| 38 |
if (isAndroid) {
|
| 39 |
+
return 'http://10.0.2.2:5001';
|
|
|
|
| 40 |
}
|
| 41 |
+
return 'http://192.168.2.228:5001';
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 42 |
}
|
| 43 |
|
| 44 |
// 4. Default local development (Browser)
|
| 45 |
if (window.location.hostname === 'localhost') {
|
| 46 |
+
return 'http://localhost:5001';
|
| 47 |
}
|
| 48 |
|
| 49 |
return 'https://shanshal66-my-shop-backend.hf.space';
|
|
|
|
| 239 |
// Base fetch wrapper with caching and retry logic
|
| 240 |
export async function request(endpoint: string, options: any = {}, retries = 2) {
|
| 241 |
const isGet = !options.method || options.method === 'GET';
|
| 242 |
+
const isAuthMe = endpoint.includes('/auth/me');
|
| 243 |
+
const skipCache = options.skipCache || isAuthMe || false;
|
| 244 |
const cacheKey = endpoint;
|
| 245 |
const skipMaintenanceTrigger = options.skipMaintenanceTrigger || false;
|
| 246 |
|
|
|
|
| 252 |
}
|
| 253 |
}
|
| 254 |
|
| 255 |
+
let currentBaseUrl = API_BASE_URL;
|
| 256 |
+
|
| 257 |
const executeRequest = async (attempt: number): Promise<any> => {
|
| 258 |
// Priority: 1. options.token, 2. localStorage
|
| 259 |
let token = (options.token || localStorage.getItem('auth_token'))?.trim();
|
|
|
|
| 262 |
if (token === 'null' || token === 'undefined') {
|
| 263 |
token = null;
|
| 264 |
}
|
| 265 |
+
|
| 266 |
+
// Handle test tokens for Google Play reviewers
|
| 267 |
+
if (token?.startsWith('test-token-')) {
|
| 268 |
+
const isAdmin = token.includes('1987654321');
|
| 269 |
+
|
| 270 |
+
if (endpoint.includes('/auth/me')) {
|
| 271 |
+
return {
|
| 272 |
+
id: 'reviewer-id-' + (isAdmin ? 'admin' : 'user'),
|
| 273 |
+
phone: isAdmin ? '+1987654321' : '+1234567890',
|
| 274 |
+
name: isAdmin ? 'Admin Reviewer' : 'Google Play Reviewer',
|
| 275 |
+
email: isAdmin ? 'admin@example.com' : 'reviewer@example.com',
|
| 276 |
+
role: isAdmin ? 'ADMIN' : 'USER'
|
| 277 |
+
};
|
| 278 |
+
}
|
| 279 |
+
if (endpoint.includes('/auth/sync-supabase-user')) {
|
| 280 |
+
return {
|
| 281 |
+
success: true,
|
| 282 |
+
user: {
|
| 283 |
+
id: 'reviewer-id-' + (isAdmin ? 'admin' : 'user'),
|
| 284 |
+
phone: isAdmin ? '+1987654321' : '+1234567890',
|
| 285 |
+
name: isAdmin ? 'Admin Reviewer' : 'Google Play Reviewer',
|
| 286 |
+
role: isAdmin ? 'ADMIN' : 'USER'
|
| 287 |
+
}
|
| 288 |
+
};
|
| 289 |
+
}
|
| 290 |
+
|
| 291 |
+
// Handle admin endpoints for test admin account
|
| 292 |
+
if (isAdmin && endpoint.startsWith('/admin')) {
|
| 293 |
+
if (endpoint.includes('/stats')) {
|
| 294 |
+
return {
|
| 295 |
+
stats: {
|
| 296 |
+
totalOrders: 15,
|
| 297 |
+
totalRevenue: 2500000,
|
| 298 |
+
totalUsers: 42,
|
| 299 |
+
totalProducts: 120,
|
| 300 |
+
recentActivity: [],
|
| 301 |
+
orderStats: {
|
| 302 |
+
pending: 5,
|
| 303 |
+
processing: 3,
|
| 304 |
+
shipped: 4,
|
| 305 |
+
delivered: 3
|
| 306 |
+
},
|
| 307 |
+
revenueStats: [
|
| 308 |
+
{ date: '2026-01-20', amount: 150000 },
|
| 309 |
+
{ date: '2026-01-21', amount: 200000 },
|
| 310 |
+
{ date: '2026-01-22', amount: 180000 },
|
| 311 |
+
{ date: '2026-01-23', amount: 300000 },
|
| 312 |
+
{ date: '2026-01-24', amount: 250000 },
|
| 313 |
+
{ date: '2026-01-25', amount: 400000 }
|
| 314 |
+
]
|
| 315 |
+
}
|
| 316 |
+
};
|
| 317 |
+
}
|
| 318 |
+
if (endpoint.includes('/users')) return { users: [], totalPages: 1, total: 0 };
|
| 319 |
+
if (endpoint.includes('/products')) return { products: [], totalPages: 1, total: 0 };
|
| 320 |
+
if (endpoint.includes('/orders')) return { orders: [], totalPages: 1, total: 0 };
|
| 321 |
+
if (endpoint.includes('/coupons')) return [];
|
| 322 |
+
if (endpoint.includes('/settings')) return {
|
| 323 |
+
airShippingRate: 15400,
|
| 324 |
+
seaShippingRate: 182000,
|
| 325 |
+
airShippingMinFloor: 0,
|
| 326 |
+
currency: 'د.ع',
|
| 327 |
+
storeName: 'My Shop (Review Mode)',
|
| 328 |
+
contactEmail: 'admin@example.com',
|
| 329 |
+
contactPhone: '+1987654321',
|
| 330 |
+
footerText: 'Google Play Review Version',
|
| 331 |
+
socialLinks: {}
|
| 332 |
+
};
|
| 333 |
+
}
|
| 334 |
+
|
| 335 |
+
// Return empty results for auth-protected endpoints to prevent 401s for reviewers
|
| 336 |
+
if (endpoint.includes('/coupons')) return [];
|
| 337 |
+
if (endpoint.includes('/orders')) return [];
|
| 338 |
+
if (endpoint.includes('/notifications')) return [];
|
| 339 |
+
if (endpoint.includes('/addresses')) return [];
|
| 340 |
+
if (endpoint.includes('/favorites')) return [];
|
| 341 |
+
if (endpoint.includes('/cart')) return [];
|
| 342 |
+
if (endpoint.includes('/profile')) return {};
|
| 343 |
+
|
| 344 |
+
if (endpoint.includes('/auth/verify-otp')) {
|
| 345 |
+
return {
|
| 346 |
+
token: token,
|
| 347 |
+
user: {
|
| 348 |
+
id: 'reviewer-id-' + (token.includes('1987654321') ? 'admin' : 'user'),
|
| 349 |
+
phone: token.includes('1987654321') ? '+1987654321' : '+1234567890',
|
| 350 |
+
name: token.includes('1987654321') ? 'Admin Reviewer' : 'Google Play Reviewer',
|
| 351 |
+
role: token.includes('1987654321') ? 'ADMIN' : 'USER'
|
| 352 |
+
}
|
| 353 |
+
};
|
| 354 |
+
}
|
| 355 |
+
}
|
| 356 |
|
| 357 |
// For admin routes, if token is missing, try to wait a bit or check store
|
| 358 |
if (!token && endpoint.startsWith('/admin')) {
|
|
|
|
| 362 |
const headers: Record<string, string> = {
|
| 363 |
'Accept': 'application/json',
|
| 364 |
'Content-Type': 'application/json',
|
| 365 |
+
...(token && !token.startsWith('test-token-') ? { 'Authorization': `Bearer ${token}` } : {}),
|
| 366 |
};
|
| 367 |
|
| 368 |
if (options.headers) {
|
| 369 |
Object.assign(headers, options.headers);
|
| 370 |
}
|
| 371 |
|
| 372 |
+
const fullUrl = endpoint.startsWith('http') ? endpoint : `${currentBaseUrl}${endpoint}`;
|
| 373 |
|
| 374 |
try {
|
| 375 |
if (import.meta.env.DEV) {
|
|
|
|
| 415 |
const currentToken = localStorage.getItem('auth_token')?.trim();
|
| 416 |
const requestToken = headers['Authorization']?.replace('Bearer ', '')?.trim();
|
| 417 |
|
| 418 |
+
// Don't log out if it's a test token
|
| 419 |
+
if (requestToken?.startsWith('test-token-')) {
|
| 420 |
+
console.warn('[API] 401 from test token, ignoring logout');
|
| 421 |
+
throw new Error(`Test token unauthorized: ${endpoint}`);
|
| 422 |
+
}
|
| 423 |
+
|
| 424 |
if (currentToken && currentToken !== requestToken) {
|
| 425 |
console.warn('[API] Detected 401 from old token, retrying with new token...');
|
| 426 |
// Retry once with the current token
|
|
|
|
| 475 |
error.message.includes('Load failed');
|
| 476 |
|
| 477 |
if (attempt < retries && isNetworkError) {
|
| 478 |
+
// Fallback logic for Android emulators
|
| 479 |
+
const userAgent = navigator.userAgent.toLowerCase();
|
| 480 |
+
const isAndroid = /android/i.test(userAgent);
|
| 481 |
+
|
| 482 |
+
if (isAndroid && currentBaseUrl.includes('10.0.2.2')) {
|
| 483 |
+
console.warn(`[API Fallback] 10.0.2.2 failed, trying host IP 192.168.2.228...`);
|
| 484 |
+
currentBaseUrl = 'http://192.168.2.228:5001/api';
|
| 485 |
+
} else if (isAndroid && currentBaseUrl.includes('192.168.2.228')) {
|
| 486 |
+
console.warn(`[API Fallback] 192.168.2.228 failed, trying localhost...`);
|
| 487 |
+
currentBaseUrl = 'http://localhost:5001/api';
|
| 488 |
+
}
|
| 489 |
+
|
| 490 |
const delay = Math.pow(2, attempt) * 1000;
|
| 491 |
console.warn(`[API Network Error] Retrying ${endpoint} in ${delay}ms... (Attempt ${attempt + 1})`);
|
| 492 |
await new Promise(resolve => setTimeout(resolve, delay));
|
|
|
|
| 518 |
// Authentication functions using our server
|
| 519 |
export async function fetchMe() {
|
| 520 |
try {
|
| 521 |
+
const user = await request('/auth/me', { skipMaintenanceTrigger: true, skipCache: true });
|
| 522 |
if (user && !user.name) {
|
| 523 |
// If server returned user but no name, try to get it from Supabase
|
| 524 |
const { data: { user: sbUser } } = await supabase.auth.getUser();
|