import { useRouter } from 'expo-router'; import * as SecureStore from 'expo-secure-store'; import { Platform } from 'react-native'; import { API_ENDPOINT, refreshAuthToken } 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(); if (data.code != 0) { await refreshAuthToken("Token expired"); } return data.code == 0; } /** * 检查登录态,未登录自动跳转到 /login,已登录可执行回调。 * @param onAuthed 已登录时的回调(可选) * @param login 是否跳转登录页(可选) */ export async function checkAuthStatus(router: ReturnType, onAuthed?: () => Promise | void, login: boolean = true) { 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 && login) { router.replace('/login'); return false; } if (onAuthed && loggedIn) { await onAuthed(); } return true; }