From f7823b73909264ae7c57d07df15f3f6cf8ba3c56 Mon Sep 17 00:00:00 2001 From: callmeyan Date: Wed, 5 Feb 2025 11:44:20 +0800 Subject: [PATCH] =?UTF-8?q?fixed:=20=E7=99=BB=E5=BD=95token=E5=A4=B1?= =?UTF-8?q?=E6=95=88=E5=90=8E=E9=AA=8C=E8=AF=81=E5=A4=B1=E6=95=88?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- package.json | 2 +- src/contexts/auth/index.tsx | 40 ++++++++++++++++++++++++++++--------- 2 files changed, 32 insertions(+), 10 deletions(-) diff --git a/package.json b/package.json index e425b58..919ef93 100644 --- a/package.json +++ b/package.json @@ -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", diff --git a/src/contexts/auth/index.tsx b/src/contexts/auth/index.tsx index 5c0a689..ef0dc1d 100644 --- a/src/contexts/auth/index.tsx +++ b/src/contexts/auth/index.tsx @@ -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' } }