refactor: simplify permission-guard

This commit is contained in:
张传龙 2022-07-30 22:11:53 +08:00
parent 7dad43d003
commit 9f9884759c

View File

@ -3,42 +3,40 @@ import { usePermissionStore } from '@/store/modules/permission'
import { NOT_FOUND_ROUTE } from '@/router/routes' import { NOT_FOUND_ROUTE } from '@/router/routes'
import { getToken, refreshAccessToken, removeToken } from '@/utils/token' import { getToken, refreshAccessToken, removeToken } from '@/utils/token'
import { toLogin } from '@/utils/auth' import { toLogin } from '@/utils/auth'
import { isNullOrWhitespace } from '@/utils/is'
const WHITE_LIST = ['/login', '/redirect'] const WHITE_LIST = ['/login', '/redirect']
export function createPermissionGuard(router) { export function createPermissionGuard(router) {
const userStore = useUserStore() const userStore = useUserStore()
const permissionStore = usePermissionStore() const permissionStore = usePermissionStore()
router.beforeEach(async (to, from, next) => { router.beforeEach(async (to) => {
const token = getToken() const token = getToken()
if (token) {
if (to.path === '/login') { /** 没有token的情况 */
next({ path: '/' }) if (isNullOrWhitespace(token)) {
} else { if (WHITE_LIST.includes(to.path)) return true
if (userStore.userId) { return { path: 'login', query: { ...to.query, redirect: to.path } }
}
/** 有token的情况 */
if (to.path === '/login') return { path: '/', replace: true }
// 已经拿到用户信息 // 已经拿到用户信息
if (userStore.userId) {
refreshAccessToken() refreshAccessToken()
next() return true
} else { }
await userStore.getUserInfo().catch((error) => { await userStore.getUserInfo().catch((error) => {
removeToken() removeToken()
toLogin() toLogin()
$message.error(error.message || '获取用户信息失败!') $message.error(error.message || '获取用户信息失败!')
return
}) })
const accessRoutes = permissionStore.generateRoutes(userStore.role) const accessRoutes = permissionStore.generateRoutes(userStore.role)
accessRoutes.forEach((route) => { accessRoutes.forEach((route) => {
!router.hasRoute(route.name) && router.addRoute(route) !router.hasRoute(route.name) && router.addRoute(route)
}) })
router.addRoute(NOT_FOUND_ROUTE) router.addRoute(NOT_FOUND_ROUTE)
next({ ...to, replace: true }) return { ...to, replace: true }
}
}
} else {
if (WHITE_LIST.includes(to.path)) {
next()
} else {
next({ path: '/login', query: { ...to.query, redirect: to.path } })
}
}
}) })
} }