feat: refresh token
Some checks failed
Dev Deploy / Explore-Gitea-Actions (push) Failing after 1m16s

This commit is contained in:
jinyaqiu 2025-07-18 16:31:03 +08:00
parent ddf37c26e9
commit 291df75086
5 changed files with 20 additions and 14 deletions

View File

@ -16,7 +16,7 @@ export default function HomeScreen() {
setIsLoading(true); setIsLoading(true);
checkAuthStatus(router, () => { checkAuthStatus(router, () => {
router.replace('/ask') router.replace('/ask')
}).then(() => { }, false).then(() => {
setIsLoading(false); setIsLoading(false);
}); });
}, []); }, []);

View File

@ -109,8 +109,6 @@ export default function OwnerPage() {
// 当用户选择发生变化时,重新获取排名 // 当用户选择发生变化时,重新获取排名
useEffect(() => { useEffect(() => {
console.log('selectedLocation', selectedLocation);
console.log('selectedClassify', selectedClassify);
if (selectedLocation?.length > 0 && selectedClassify?.length > 0) { if (selectedLocation?.length > 0 && selectedClassify?.length > 0) {
getRanking(); getRanking();
} }
@ -151,8 +149,6 @@ export default function OwnerPage() {
return item.name === JSON.parse(location || "").city return item.name === JSON.parse(location || "").city
}) || [], JSON.parse(location || "").district); }) || [], JSON.parse(location || "").district);
if (location) { if (location) {
console.log("xuhuiElement", xuhuiElement);
setSelectedLocation([xuhuiElement]); setSelectedLocation([xuhuiElement]);
} }
} }

View File

@ -23,7 +23,7 @@ const Ranking = ({ data }: { data: TitleRankings[] }) => {
data={data} data={data}
showsVerticalScrollIndicator={false} showsVerticalScrollIndicator={false}
contentContainerStyle={{ width: "100%" }} contentContainerStyle={{ width: "100%" }}
keyExtractor={(item) => item.display_name} keyExtractor={(item, index) => `${item.display_name}-${index}`}
renderItem={({ item }) => ( renderItem={({ item }) => (
<View style={styles.item}> <View style={styles.item}>
<ThemedText style={styles.rank}>No.{item.ranking}</ThemedText> <ThemedText style={styles.rank}>No.{item.ranking}</ThemedText>

View File

@ -1,7 +1,7 @@
import { useRouter } from 'expo-router'; import { useRouter } from 'expo-router';
import * as SecureStore from 'expo-secure-store'; import * as SecureStore from 'expo-secure-store';
import { Platform } from 'react-native'; import { Platform } from 'react-native';
import { API_ENDPOINT } from './server-api-util'; import { API_ENDPOINT, refreshAuthToken } from './server-api-util';
export async function identityCheck(token: string) { export async function identityCheck(token: string) {
@ -12,14 +12,18 @@ export async function identityCheck(token: string) {
}, },
}); });
const data = await res.json(); const data = await res.json();
if (data.code != 0) {
await refreshAuthToken("Token expired");
}
return data.code == 0; return data.code == 0;
} }
/** /**
* /login * /login
* @param onAuthed * @param onAuthed
* @param login
*/ */
export async function checkAuthStatus(router: ReturnType<typeof useRouter>, onAuthed?: () => Promise<void> | void) { export async function checkAuthStatus(router: ReturnType<typeof useRouter>, onAuthed?: () => Promise<void> | void, login: boolean = true) {
let token: string | null = ''; let token: string | null = '';
if (Platform.OS === 'web') { if (Platform.OS === 'web') {
token = localStorage.getItem('token') || ''; token = localStorage.getItem('token') || '';
@ -28,11 +32,11 @@ export async function checkAuthStatus(router: ReturnType<typeof useRouter>, onAu
} }
const loggedIn = !!token && await identityCheck(token); const loggedIn = !!token && await identityCheck(token);
if (!loggedIn) { if (!loggedIn && login) {
router.replace('/login'); router.replace('/login');
return false; return false;
} }
if (onAuthed) { if (onAuthed && loggedIn) {
await onAuthed(); await onAuthed();
} }
return true; return true;

View File

@ -64,15 +64,14 @@ export const refreshAuthToken = async<T>(message: string | null): Promise<User>
cookie = localStorage.getItem('user') ? JSON.parse(localStorage.getItem('user') || "")?.refresh_token || "" : ""; cookie = localStorage.getItem('user') ? JSON.parse(localStorage.getItem('user') || "")?.refresh_token || "" : "";
userId = localStorage.getItem('user') ? JSON.parse(localStorage.getItem('user') || "")?.user_id || "" : ""; userId = localStorage.getItem('user') ? JSON.parse(localStorage.getItem('user') || "")?.user_id || "" : "";
} else { } else {
await SecureStore.getItemAsync('user').then((user: User) => { await SecureStore.getItemAsync('user').then((user: string | null) => {
cookie = user?.refresh_token || ""; cookie = JSON.parse(user || "")?.refresh_token || "";
userId = user?.user_id || ""; userId = JSON.parse(user || "")?.user_id || "";
}) })
} }
// 退出刷新会重新填充数据 // 退出刷新会重新填充数据
let response; let response;
response = await fetch(`${API_ENDPOINT}/v1/iam/access-token-refresh`, { response = await fetch(`${API_ENDPOINT}/v1/iam/access-token-refresh`, {
method: "POST", method: "POST",
body: JSON.stringify({ body: JSON.stringify({
@ -97,6 +96,13 @@ export const refreshAuthToken = async<T>(message: string | null): Promise<User>
user: userData, user: userData,
token: userData.access_token token: userData.access_token
})); }));
if (Platform.OS === 'web') {
localStorage.setItem('user', JSON.stringify(userData));
localStorage.setItem('token', userData.access_token);
} else {
SecureStore.setItemAsync('user', JSON.stringify(userData));
SecureStore.setItemAsync('token', userData.access_token);
}
} }
return userData; return userData;