* 增强路由状态管理 - 改进动态路由加载和混合路由模式支持 - 优化路由重置机制,保护基础路由 - 完善路由helper工具函数 * 提升标签页管理 - 集成安全导航机制,使用navigationGuard - 增强标签页关闭和跳转的错误处理 * 改进认证状态管理 - 优化登录流程和用户信息处理 - 更好的登录重定向逻辑 提升应用稳定性和用户体验
105 lines
2.9 KiB
TypeScript
105 lines
2.9 KiB
TypeScript
import { router } from '@/router'
|
||
import { fetchLogin, fetchLoginUserInfo } from '@/service/api/auth'
|
||
import { local } from '@/utils'
|
||
import { useRouteStore } from './router'
|
||
import { useTabStore } from './tab'
|
||
|
||
interface AuthStatus {
|
||
userInfo: Api.Login.Info | null
|
||
token: string
|
||
}
|
||
export const useAuthStore = defineStore('auth-store', {
|
||
state: (): AuthStatus => {
|
||
return {
|
||
userInfo: local.get('userInfo'),
|
||
token: local.get('accessToken') || '',
|
||
}
|
||
},
|
||
getters: {
|
||
/** 是否登录 */
|
||
isLogin(state) {
|
||
return Boolean(state.token)
|
||
},
|
||
},
|
||
actions: {
|
||
/* 登录退出,重置用户信息等 */
|
||
async logout() {
|
||
const route = unref(router.currentRoute)
|
||
// 清除本地缓存
|
||
this.clearAuthStorage()
|
||
// 清空路由、菜单等数据
|
||
const routeStore = useRouteStore()
|
||
routeStore.resetRouteStore()
|
||
// 清空标签栏数据
|
||
const tabStore = useTabStore()
|
||
tabStore.clearAllTabs()
|
||
// 重置当前存储库
|
||
this.$reset()
|
||
// 重定向到登录页
|
||
if (route.meta.requiresAuth) {
|
||
router.push({
|
||
name: 'login',
|
||
query: {
|
||
redirect: route.fullPath,
|
||
},
|
||
})
|
||
}
|
||
},
|
||
clearAuthStorage() {
|
||
local.remove('accessToken')
|
||
local.remove('refreshToken')
|
||
local.remove('userInfo')
|
||
},
|
||
|
||
/* 用户登录 */
|
||
async login(loginName: string, password: string, codeKey: string, securityCode: string, rememberMe = false) {
|
||
try {
|
||
const { isSuccess, data } = await fetchLogin({ loginName, password, codeKey, securityCode, rememberMe })
|
||
if (!isSuccess)
|
||
return
|
||
|
||
// 保存Token
|
||
local.set('accessToken', data.tokenValue)
|
||
this.token = data.tokenValue
|
||
|
||
// 获取用户信息
|
||
const userInfoResult = await fetchLoginUserInfo()
|
||
if (!userInfoResult.isSuccess)
|
||
return
|
||
|
||
// 处理登录信息
|
||
const userInfo = {
|
||
...userInfoResult.data,
|
||
accessToken: data.tokenValue,
|
||
refreshToken: data.tokenValue, // 如果后端没有单独的refreshToken,暂时使用相同值
|
||
}
|
||
await this.handleLoginInfo(userInfo as Api.Login.Info)
|
||
}
|
||
catch (e) {
|
||
console.warn('[Login Error]:', e)
|
||
}
|
||
},
|
||
|
||
/* 处理登录返回的数据 */
|
||
async handleLoginInfo(data: Api.Login.Info) {
|
||
// 将token和userInfo保存下来
|
||
local.set('userInfo', data)
|
||
local.set('accessToken', data.accessToken)
|
||
local.set('refreshToken', data.refreshToken)
|
||
this.token = data.accessToken
|
||
this.userInfo = data
|
||
|
||
// 添加路由和菜单
|
||
const routeStore = useRouteStore()
|
||
await routeStore.initAuthRoute()
|
||
|
||
// 进行重定向跳转
|
||
const route = unref(router.currentRoute)
|
||
const query = route.query as { redirect: string }
|
||
router.push({
|
||
path: query.redirect || '/',
|
||
})
|
||
},
|
||
},
|
||
})
|