前端页面权限管控-高阶组件
一般开发项目时,都会遇到要求做页面权限管控的需求,例如,某某环境(开发/测试/预发/生产)某人的级别权限只看某些菜单。
一般这种需求直接封装组件最干净,且复用性强。
假设接口请求配置
export async function queryIsAuthorized(authCode: string, currentEnv: string) {// 传入当前环境(currentEnv), 线下环境可不校验权限if ([ENV.DEV, ENV.LOCAL, ENV.STABLE].includes(currentEnv as ENV)) return true;const res = await baseRequest('/queryIsAuthorized', {method: 'get',params: { authCode },});return res?.model;
}
组件 withAuth.jsx
import { queryIsAuthorized } from '@/common/request';
import { CURRENT_ENV } from '@/insiopweb-common'; // 环境配置,根据实际需求项目匹配=MOCK = "mock", LOCAL = "local", STABLE = "stable",DEV = "dev",TEST = "test", PRE = "pre", PROD = "prod",
import { useRequest } from 'ahooks';
import React from 'react';const withAuth = (Component: () => React.JSX.Element, code: string) => () => {const { data: hasEditAuth } = useRequest(async () => {try {const res = await queryIsAuthorized(code, CURRENT_ENV);if (!res) {window.location.href = `${window.location.origin}/exception/403?code=${code}`;}return res;} catch (error) {console.log('获取权限失败', error);window.location.href = `${window.location.origin}/exception/403?code=${code}`;}});if (hasEditAuth) {return <Component />;}return null;
};export default withAuth;
实际项目引入
const ExperienceAUTH= () => {}
export default withAuth(ExperienceAUTH, VIEAuthXX);
这样以来没有权限的就看不到页面了,如果有其他需求,例如去404或申请权限则需要根据实际情况去布局页面了。一般后端会配置。