ai-vue3-admin/src/permission.js
2025-12-09 10:52:00 +08:00

121 lines
3.0 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/*
*
* ┏┓   ┏┓
* ┏┛┻━━━┛┻┓
* ┃       ┃
* ┃   ━   ┃
* ┃ >   < ┃
* ┃       ┃
* ┃... ⌒ ... ┃
* ┃       ┃
* ┗━┓   ┏━┛
* ┃   ┃
* ┃   ┃
* ┃   ┃
* ┃   ┃ 神兽保佑
* ┃   ┃ 代码无bug
* ┃   ┃
* ┃   ┗━━━┓
* ┃       ┣┓
* ┃       ┏┛
* ┗┓┓┏━┳┓┏┛
* ┃┫┫ ┃┫┫
* ┗┻┛ ┗┻┛
*
* @Descripttion:
* @version:
* @Date: 2021-04-20 11:06:21
* @LastEditors: huzhushan@126.com
* @LastEditTime: 2022-09-27 16:35:06
* @Author: huzhushan@126.com
* @HomePage: https://huzhushan.gitee.io/vue3-element-admin
* @Github: https://github.com/huzhushan/vue3-element-admin
* @Donate: https://huzhushan.gitee.io/vue3-element-admin/donate/
*/
import { ElLoading } from 'element-plus'
import router from '@/router'
import { TOKEN } from './pinia/modules/app'
import { nextTick } from 'vue'
import { useApp } from './pinia/modules/app'
import { useAccount } from './pinia/modules/account'
import { useMenus } from './pinia/modules/menu'
const getPageTitle = title => {
const { title: appTitle } = useApp()
return title ? `${title} - ${appTitle}` : appTitle
}
// 白名单
const WhiteList = ['login', 'lock']
let loadingInstance = null
router.beforeEach(async to => {
// 1. 白名单直接放行
if (WhiteList.includes(to.name)) return true
// 2. 未登录强制跳转登录页
if (!window.localStorage[TOKEN]) {
return {
name: 'login',
query: { redirect: to.fullPath },
replace: true,
}
}
const { userinfo, getUserinfo } = useAccount()
// 3. 首次加载:获取用户信息
if (!userinfo) {
try {
await getUserinfo()
} catch {
loadingInstance?.close()
return false
}
// 获取完用户信息后,如果当前不是 /chat_view强制跳转
// 这里的 to 可能是登录页(带 redirect或其他页面
if (to.path !== '/chat_view') {
return '/chat_view'
}
return true // 已在目标页,直接放行
}
// 4. 生成动态菜单(如有)
const { menus, generateMenus } = useMenus()
if (menus.length <= 0) {
try {
await generateMenus()
return to.fullPath // 生成后重新触发导航
} catch {
loadingInstance?.close()
return false
}
}
// 5. 锁屏检查
if (to.name !== 'lock') {
const { authorization } = useApp()
if (authorization?.screenCode) {
return {
name: 'lock',
query: { redirect: to.path },
replace: true,
}
}
}
// 6. 已登录且非首次,允许自由访问
return true
})
router.afterEach(to => {
loadingInstance?.close()
if (router.currentRoute.value.name === to.name) {
nextTick(() => {
document.title = getPageTitle(to.meta?.truetitle)
})
}
})