import { useRouter } from 'expo-router'; import * as SecureStore from 'expo-secure-store'; import { Platform } from 'react-native'; import { API_ENDPOINT } from './server-api-util'; export async function identityCheck(token: string) { const res = await fetch(`${API_ENDPOINT}/v1/iam/identity-check`, { method: 'POST', headers: { 'Authorization': `Bearer ${token}` }, }); const data = await res.json(); return data.code == 0; } /** * 检查登录态,未登录自动跳转到 /login,已登录可执行回调。 * @param onAuthed 已登录时的回调(可选) */ export async function checkAuthStatus(router: ReturnType, onAuthed?: () => Promise | void) { let token: string | null = ''; if (Platform.OS === 'web') { token = localStorage.getItem('token') || ''; } else { token = await SecureStore.getItemAsync('token') || ''; } const loggedIn = !!token && await identityCheck(token); if (!loggedIn) { router.replace('/login'); return false; } if (onAuthed) { await onAuthed(); } return true; }