diff --git a/src/router/guard.ts b/src/router/guard.ts index 6b81550..952ba51 100644 --- a/src/router/guard.ts +++ b/src/router/guard.ts @@ -22,18 +22,34 @@ function setupCommonGuard(router: Router) { router.beforeEach(async (to) => { const accountStore = useAccountStore() - // 首次导航时验证 token 有效性(检查持久化的 token 是否过期) - // await accountStore.initAuth() - // 已登录用户访问公开路由(如登录页),直接跳转首页 - if (accountStore.isLoggedIn() && isPublicPath(to.path)) { + if (!!accountStore.accessToken && isPublicPath(to.path)) { return '/' } - // 未登录用户访问非公开路由,跳转登录页 - if (!accountStore.isLoggedIn() && !isPublicPath(to.path)) { - // 将原本要访问的路径作为 redirect 参数传递,登录后可跳回 - return { path: '/auth/login', query: { redirect: to.fullPath } } + // accessToken 检查 + if (!accountStore.accessToken) { + // 明确声明忽略权限访问权限,则可以访问 + if (to.meta.ignoreAccess) { + return true + } + + // 未登录用户访问非公开路由,跳转登录页 + if (!isPublicPath(to.path)) { + // 将原本要访问的路径作为 redirect 参数传递,登录后可跳回 + return { path: '/auth/login', query: { redirect: to.fullPath }, replace: true } + } + + // 没有访问权限,跳转登录页面 + if (to.fullPath !== '/auth/login') { + return { + path: '/auth/login', + query: { redirect: to.fullPath }, + // 携带当前跳转的页面,登录后重新跳转该页面 + replace: true + } + } + return to } return true diff --git a/src/stores/modules/account.ts b/src/stores/modules/account.ts index 0dafcd6..edbb6a0 100644 --- a/src/stores/modules/account.ts +++ b/src/stores/modules/account.ts @@ -39,42 +39,6 @@ export const useAccountStore = defineStore( /** 是否已完成初始验证(防止重复请求) */ const isInitialized = ref(false) - /** - * 判断当前是否已登录 - * token 存在且已验证有效才算已登录 - */ - const isLoggedIn = () => isTokenValid.value - - /** - * 初始化认证状态 - * - * 用持久化的 Access Token 向服务端验证是否仍然有效。 - * 只会在首次调用时真正发请求,后续调用直接跳过。 - * - * - 无 token → 无操作 - * - token 有效 → 拉取用户信息,标记已登录 - * - token 过期 → requestClient 拦截器自动调用 refreshAccessToken() 刷新后重试, - * 若刷新也失败则抛出异常,此处 catch 后清除认证状态 - */ - const initAuth = async () => { - console.log('initAuth', isInitialized.value) - // 已验证过,跳过 - if (isInitialized.value) return - isInitialized.value = true - - // 没有持久化的 Access Token - if (!accessToken.value) return - - try { - await fetchUserInfo() - // 成功获取用户信息,token 有效 - isTokenValid.value = true - } catch { - // 请求失败(包括自动刷新也失败),清除认证状态 - clearAuth() - } - } - /** * 用户登录 * 调用登录 API,成功后存储双 Token 并获取用户信息 @@ -150,12 +114,12 @@ export const useAccountStore = defineStore( isInitialized.value = false } + console.log('useAccountStore', accessToken.value) + return { accountInfo, accessToken, refreshToken, - isLoggedIn, - initAuth, login, register, logout,