From feb53ffad8dc9bd0f64ac042f72c34a73d9f1433 Mon Sep 17 00:00:00 2001 From: meowrain Date: Sat, 15 Nov 2025 20:28:13 +0800 Subject: [PATCH] =?UTF-8?q?feat(access):=20=E6=B7=BB=E5=8A=A0=E8=B7=AF?= =?UTF-8?q?=E7=94=B1=E6=9D=83=E9=99=90=E6=A3=80=E6=9F=A5=E5=8A=9F=E8=83=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 实现路由守卫的权限检查逻辑,根据用户角色和路由meta配置决定是否允许访问或重定向 --- src/access/index.ts | 50 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) diff --git a/src/access/index.ts b/src/access/index.ts index c981526..397c363 100644 --- a/src/access/index.ts +++ b/src/access/index.ts @@ -1,6 +1,56 @@ +/** src/access/index.ts */ +import type { RouteLocationNormalizedGeneric } from "vue-router"; import router from "../router/router"; +import type { LoginUesr } from "../store/types"; import { useUserStore } from "../store/user"; import ACCESS_ENUM from "./accessEnum"; import checkAccess from "./checkAccess"; +const userStore = useUserStore(); +/** + * 检查是否需要权限访问 + * @param to 要访问的路由 + * @param loginUser 当前登录用户 + * @returns 如果需要权限访问且权限不足,返回重定向路径;否则返回空字符串 + */ +const redirectWithAccess = (to: RouteLocationNormalizedGeneric,loginUser: LoginUesr):string =>{ + // 获取要访问的路由的权限 + const needAccess: string = to.meta?.access ?? ACCESS_ENUM.NOT_LOGIN; //?? 运算符, 如果 to.meta?.access 为 undefined 或 null, + // 则使用 ACCESS_ENUM.NOT_LOGIN 作为默认值 + // 必须要登录才能访问的页面 + if (needAccess !== ACCESS_ENUM.NOT_LOGIN) { + // 如果说当前是未登录状态 那直接给他跳登录页面去 + if ( + !loginUser || + !loginUser.userRole || + loginUser.userRole === ACCESS_ENUM.NOT_LOGIN + ) { + return `/user/login?redirect=${to.fullPath}`; + } + // 权限不足,跳到无权限页面 + if (!checkAccess(loginUser, needAccess)) { + return "/noAuth"; + } + } + return ""; +} +// 这里接收异步函数,是因为下面要调用 userStore.getLoginUser() +router.beforeEach(async (to, from, next) => { + console.log("登陆用户信息", userStore.loginUser); + let loginUser = userStore.loginUser; + // 如果之前没登陆过,自动登录 + if (!loginUser || !loginUser.userRole) { + await userStore.getLoginUser(); + loginUser = userStore.loginUser; + } + + // 检查是否需要权限访问 + const redirectUrl = redirectWithAccess(to, loginUser); + if (redirectUrl) { + next(redirectUrl); + return; + } + // 未重定向时,继续导航 + next(); +});