feat(环境配置): 添加环境配置文件标识并优化权限检查代码

在环境配置文件中添加 VITE_APP_CONFIG_FILE 变量标识当前环境配置文件
同时在权限检查模块中优化代码格式和逻辑结构
This commit is contained in:
2025-11-15 23:15:29 +08:00
parent feb53ffad8
commit 55a048725b
6 changed files with 32 additions and 23 deletions

View File

@@ -1,2 +1,3 @@
VITE_APP_CONFIG_FILE=.env.dev
VITE_APP_ENV=开发环境
VITE_API_URL=http://localhost:8080

View File

@@ -1,2 +1,3 @@
VITE_APP_CONFIG_FILE=.env.prod
VITE_APP_ENV=生产环境
VITE_API_URL=http://localhost:8080

View File

@@ -1,2 +1,3 @@
VITE_APP_CONFIG_FILE=.env.test
VITE_APP_ENV=测试环境
VITE_API_URL=http://localhost:8080

View File

@@ -13,28 +13,30 @@ const userStore = useUserStore();
* @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 "";
}
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);
@@ -44,7 +46,7 @@ router.beforeEach(async (to, from, next) => {
await userStore.getLoginUser();
loginUser = userStore.loginUser;
}
// 检查是否需要权限访问
const redirectUrl = redirectWithAccess(to, loginUser);
if (redirectUrl) {

View File

@@ -2,8 +2,10 @@
interface EnvironmentVariables {
APP_ENV: string;
API_BASE_URL: string;
APP_CONFIG_FILE: string;
}
export const ENV: EnvironmentVariables = {
APP_ENV: import.meta.env.VITE_APP_ENV,
API_BASE_URL: import.meta.env.VITE_API_URL,
APP_CONFIG_FILE: import.meta.env.VITE_APP_CONFIG_FILE,
};

View File

@@ -6,6 +6,8 @@ import path from "path";
export default defineConfig(({ command, mode }) => {
const env = loadEnv(mode, process.cwd(), "");
console.log("当前环境:", env.VITE_APP_ENV);
console.log("使用的环境配置文件为:", env.VITE_APP_CONFIG_FILE);
console.log("当前环境 API 基础 URL:", env.VITE_API_URL);
return {
define: {
__APP_ENV__: JSON.stringify(env.VITE_APP_ENV),