refactor(permission): ♻️ 优化路由权限模块,简化命名和职责分离
This commit is contained in:
@@ -2,16 +2,14 @@ import type { RouteRecordRaw } from "vue-router";
|
||||
import NProgress from "@/utils/nprogress";
|
||||
import router from "@/router";
|
||||
import { usePermissionStore, useUserStore } from "@/store";
|
||||
import { ROLE_ROOT } from "@/constants";
|
||||
|
||||
export function setupPermission() {
|
||||
const whiteList = ["/login"]; // 无需登录的页面
|
||||
const whiteList = ["/login"];
|
||||
|
||||
router.beforeEach(async (to, from, next) => {
|
||||
NProgress.start();
|
||||
|
||||
try {
|
||||
// 使用 store 暴露的登录态,便于后续扩展(如基于过期时间等)
|
||||
const isLoggedIn = useUserStore().isLoggedIn();
|
||||
|
||||
// 未登录处理
|
||||
@@ -25,18 +23,17 @@ export function setupPermission() {
|
||||
return;
|
||||
}
|
||||
|
||||
// 已登录且访问登录页,重定向到首页
|
||||
// 已登录登录页重定向
|
||||
if (to.path === "/login") {
|
||||
next({ path: "/" });
|
||||
return;
|
||||
}
|
||||
|
||||
// 已登录用户的正常访问
|
||||
const permissionStore = usePermissionStore();
|
||||
const userStore = useUserStore();
|
||||
|
||||
// 路由未生成则生成
|
||||
if (!permissionStore.isDynamicRoutesGenerated) {
|
||||
// 动态路由生成
|
||||
if (!permissionStore.isRouteGenerated) {
|
||||
if (!userStore.userInfo?.roles?.length) {
|
||||
await userStore.getUserInfo();
|
||||
}
|
||||
@@ -50,13 +47,13 @@ export function setupPermission() {
|
||||
return;
|
||||
}
|
||||
|
||||
// 检查路由是否存在
|
||||
// 路由404检查
|
||||
if (to.matched.length === 0) {
|
||||
next("/404");
|
||||
return;
|
||||
}
|
||||
|
||||
// 设置页面标题
|
||||
// 动态标题设置
|
||||
const title = (to.params.title as string) || (to.query.title as string);
|
||||
if (title) {
|
||||
to.meta.title = title;
|
||||
@@ -64,13 +61,9 @@ export function setupPermission() {
|
||||
|
||||
next();
|
||||
} catch (error) {
|
||||
console.error("❌ Route guard error:", error);
|
||||
// 出错时清理状态并重定向到登录页
|
||||
try {
|
||||
await useUserStore().resetAllState();
|
||||
} catch (resetError) {
|
||||
console.error("❌ Failed to reset user state:", resetError);
|
||||
}
|
||||
// 错误处理:重置状态并跳转登录
|
||||
console.error("Route guard error:", error);
|
||||
await useUserStore().resetAllState();
|
||||
next("/login");
|
||||
NProgress.done();
|
||||
}
|
||||
@@ -80,18 +73,3 @@ export function setupPermission() {
|
||||
NProgress.done();
|
||||
});
|
||||
}
|
||||
|
||||
/** 判断是否有权限 */
|
||||
export function hasAuth(value: string | string[], type: "button" | "role" = "button") {
|
||||
const { roles, perms } = useUserStore().userInfo;
|
||||
|
||||
// 超级管理员 拥有所有权限
|
||||
if (type === "button" && roles.includes(ROLE_ROOT)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
const auths = type === "button" ? perms : roles;
|
||||
return typeof value === "string"
|
||||
? auths.includes(value)
|
||||
: value.some((perm) => auths.includes(perm));
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user