2021-11-20 20:14:02 +08:00
|
|
|
import type { RouteLocationNormalized, NavigationGuardNext } from 'vue-router';
|
2021-11-29 20:34:56 +08:00
|
|
|
import { routeName } from '@/router';
|
|
|
|
|
import { getToken } from '@/utils';
|
2021-08-17 14:59:59 +08:00
|
|
|
|
2021-11-19 21:39:29 +08:00
|
|
|
type RouterAction = [boolean, () => void];
|
|
|
|
|
|
2021-11-20 20:14:02 +08:00
|
|
|
/** 处理页面的权限 */
|
|
|
|
|
export function handlePagePermission(
|
|
|
|
|
to: RouteLocationNormalized,
|
|
|
|
|
from: RouteLocationNormalized,
|
|
|
|
|
next: NavigationGuardNext
|
|
|
|
|
) {
|
2021-09-16 13:58:11 +08:00
|
|
|
const token = getToken();
|
2021-09-16 14:17:57 +08:00
|
|
|
const isLogin = Boolean(token);
|
|
|
|
|
const needLogin = Boolean(to.meta?.requiresAuth);
|
|
|
|
|
|
2021-11-19 21:39:29 +08:00
|
|
|
const routerAction: RouterAction[] = [
|
2021-09-16 13:58:11 +08:00
|
|
|
// 已登录状态跳转登录页,跳转至首页
|
|
|
|
|
[
|
2021-11-19 01:33:36 +08:00
|
|
|
isLogin && to.name === routeName('login'),
|
2021-09-16 13:58:11 +08:00
|
|
|
() => {
|
2021-11-19 01:33:36 +08:00
|
|
|
next({ name: routeName('root') });
|
2021-09-16 13:58:11 +08:00
|
|
|
}
|
|
|
|
|
],
|
2021-09-16 14:17:57 +08:00
|
|
|
// 不需要登录权限的页面直接通行
|
2021-09-16 13:58:11 +08:00
|
|
|
[
|
2021-09-16 14:17:57 +08:00
|
|
|
!needLogin,
|
2021-09-16 13:58:11 +08:00
|
|
|
() => {
|
|
|
|
|
next();
|
|
|
|
|
}
|
|
|
|
|
],
|
2021-09-16 14:17:57 +08:00
|
|
|
// 未登录状态进入需要登录权限的页面
|
|
|
|
|
[
|
|
|
|
|
!isLogin && needLogin,
|
|
|
|
|
() => {
|
2021-11-29 20:34:56 +08:00
|
|
|
const redirect = to.fullPath;
|
|
|
|
|
next({ name: routeName('login'), query: { redirect } });
|
2021-09-16 14:17:57 +08:00
|
|
|
}
|
|
|
|
|
],
|
|
|
|
|
// 登录状态进入需要登录权限的页面,直接通行
|
2021-09-16 13:58:11 +08:00
|
|
|
[
|
2021-09-16 18:43:52 +08:00
|
|
|
isLogin && needLogin,
|
2021-09-16 13:58:11 +08:00
|
|
|
() => {
|
2021-09-16 14:17:57 +08:00
|
|
|
next();
|
2021-09-16 13:58:11 +08:00
|
|
|
}
|
|
|
|
|
]
|
|
|
|
|
];
|
|
|
|
|
|
|
|
|
|
routerAction.some(item => {
|
2021-11-19 21:39:29 +08:00
|
|
|
const [flag, callback] = item;
|
2021-09-16 13:58:11 +08:00
|
|
|
if (flag) {
|
2021-11-19 21:39:29 +08:00
|
|
|
callback();
|
2021-09-16 13:58:11 +08:00
|
|
|
}
|
|
|
|
|
return flag;
|
|
|
|
|
});
|
|
|
|
|
}
|