fixed: 登录token失效后验证失效

This commit is contained in:
LittleBoy 2025-02-05 11:44:20 +08:00 committed by Coding
parent 61426ace81
commit f7823b7390
2 changed files with 32 additions and 10 deletions

View File

@ -6,7 +6,7 @@
"description": "数字人直播间",
"scripts": {
"dev": "vite --host",
"dev-test": "set APP_LANGUAGE=en-US && vite --host --mode=test",
"dev-test": "vite --host --mode=test",
"dev-lang-en": "set APP_LANGUAGE=en-US && vite --host --mode=lang-en",
"build": "tsc && vite build",
"build-test": "tsc && vite build --mode=test",

View File

@ -1,8 +1,10 @@
import React, {createContext, useEffect, useReducer} from "react";
import Loader from "@/components/loader";
import {getAuthToken, setAuthToken} from "@/hooks/useAuth.ts";
import {clearAuth, getAuthToken, setAuthToken} from "@/hooks/useAuth.ts";
import {auth} from "@/service/api/user.ts";
import {getAllCategory} from "@/service/api/article.ts";
import {BizError} from "@/service/types.ts";
const UserRoleStorageKey = 'user-current-role';
@ -39,15 +41,35 @@ export const AuthProvider = ({children}: { children: React.ReactNode }) => {
if (token) {
const result = localStorage.getItem(AppConfig.AUTHED_PERSON_DATA_KEY)
if (result) {
const user = JSON.parse(result) as UserProfile
dispatch({
payload: {
isInitialized: true,
isLoggedIn: true,
user,
token
// 验证用户token是否正确
try{
// 获取一个分类接口进行验证token是否有效
await getAllCategory();
const user = JSON.parse(result) as UserProfile
dispatch({
payload: {
isInitialized: true,
isLoggedIn: true,
user,
token
}
})
}catch (e){
const err = e as BizError;
if(err.code == 1001){
// token失效
setAuthToken(null)
dispatch({
payload: {
isInitialized: true,
isLoggedIn: false,
user: null,
token: null
}
})
return 'token was invalid'
}
})
}
return 'initialized'
}
}