- 添加菜单权限控制

- url 权限控制
This commit is contained in:
sin 2019-03-01 18:15:12 +08:00
parent 814ca633aa
commit 21bacc19d8
14 changed files with 160 additions and 23 deletions

21
admin-web/mock/admin.js Normal file
View File

@ -0,0 +1,21 @@
import adminMenu from './geographic/admin-menu.json';
import adminMenuAll from './geographic/admin-menu-all.json';
import adminUrls from './geographic/admin-urls';
/* eslint-disable */
function getAdminMenu(req, res) {
return res.json(adminMenu);
}
function getAdminMenuAll(req, res) {
return res.json(adminMenuAll);
}
function getAdminUrls(req, res) {
return res.json(adminUrls);
}
export default {
'GET /admin-api/admin/resource/admin_menu_tree': getAdminMenuAll,
'GET /admin-api/admin/resource/admin_url_list': getAdminUrls,
};

View File

@ -0,0 +1,5 @@
{
"code": 0,
"message": "",
"data": "all"
}

View File

@ -0,0 +1,26 @@
{
"code": 0,
"message": "",
"data": [
{
"children": [
{
"handler": "/order/list1",
"id": 1,
"name": "商品管理1",
"pid": 1
},
{
"handler": "/order/list2",
"id": 1,
"name": "商品管理2",
"pid": 1
}
],
"handler": "/home",
"id": 1,
"name": "商品管理",
"pid": 1
}
]
}

View File

@ -0,0 +1,5 @@
{
"code": 0,
"data": ["/admin/source/add", "/admin/source/delete"],
"message": "string"
}

View File

@ -1,17 +1,17 @@
import React, { PureComponent } from 'react'; import React, { PureComponent } from 'react';
import GlobalAuthority from '../../layouts/GlobalAuthorityContext'; import UrlsContext from '../../layouts/UrlsContext';
// 用于控制权限 // 用于控制权限
class AuthorityControl extends PureComponent { class AuthorityControl extends PureComponent {
render() { render() {
const { authKey, children } = this.props; const { authKey, children } = this.props;
return ( return (
<GlobalAuthority.Consumer> <UrlsContext.Consumer>
{context => { {context => {
const { authList } = context; const { authList } = context;
return <div>{authList[authKey] ? children : '无权限'}</div>; return <div>{authList[authKey] ? children : '无权限'}</div>;
}} }}
</GlobalAuthority.Consumer> </UrlsContext.Consumer>
); );
} }
} }

View File

@ -6,6 +6,7 @@ import { getFlatMenuKeys } from './SiderMenuUtils';
const SiderMenuWrapper = React.memo(props => { const SiderMenuWrapper = React.memo(props => {
const { isMobile, menuData, collapsed, onCollapse } = props; const { isMobile, menuData, collapsed, onCollapse } = props;
const flatMenuKeys = getFlatMenuKeys(menuData); const flatMenuKeys = getFlatMenuKeys(menuData);
return isMobile ? ( return isMobile ? (
<Drawer <Drawer
visible={!collapsed} visible={!collapsed}

View File

@ -11,6 +11,7 @@ import logo from '../assets/logo.svg';
import Footer from './Footer'; import Footer from './Footer';
import Header from './Header'; import Header from './Header';
import Context from './MenuContext'; import Context from './MenuContext';
import UrlsContext from './UrlsContext';
import Exception403 from '../pages/Exception/403'; import Exception403 from '../pages/Exception/403';
import PageLoading from '@/components/PageLoading'; import PageLoading from '@/components/PageLoading';
import SiderMenu from '@/components/SiderMenu'; import SiderMenu from '@/components/SiderMenu';
@ -59,6 +60,10 @@ class BasicLayout extends React.Component {
dispatch({ dispatch({
type: 'setting/getSetting', type: 'setting/getSetting',
}); });
dispatch({
type: 'menu/getUrlsData',
payload: { routes, authority },
});
dispatch({ dispatch({
type: 'menu/getMenuData', type: 'menu/getMenuData',
payload: { routes, authority }, payload: { routes, authority },
@ -73,6 +78,13 @@ class BasicLayout extends React.Component {
}; };
} }
getUrlsContext() {
const { urlsData } = this.props;
return {
...urlsData,
};
}
getRouteAuthority = (pathname, routeData) => { getRouteAuthority = (pathname, routeData) => {
const routes = routeData.slice(); // clone const routes = routeData.slice(); // clone
@ -166,7 +178,7 @@ class BasicLayout extends React.Component {
/> />
<Content className={styles.content} style={contentStyle}> <Content className={styles.content} style={contentStyle}>
<Authorized authority={routerConfig} noMatch={<Exception403 />}> <Authorized authority={routerConfig} noMatch={<Exception403 />}>
{children} <UrlsContext.Provider values={this.getUrlsContext()}>{children}</UrlsContext.Provider>
</Authorized> </Authorized>
</Content> </Content>
<Footer /> <Footer />
@ -194,6 +206,7 @@ export default connect(({ global, setting, menu: menuModel }) => ({
collapsed: global.collapsed, collapsed: global.collapsed,
layout: setting.layout, layout: setting.layout,
menuData: menuModel.menuData, menuData: menuModel.menuData,
urlsData: menuModel.urlsData,
breadcrumbNameMap: menuModel.breadcrumbNameMap, breadcrumbNameMap: menuModel.breadcrumbNameMap,
...setting, ...setting,
}))(props => ( }))(props => (

View File

@ -1,9 +0,0 @@
import React from 'react';
// 创建全局的权限控制 context方便在所有页面使用
const GlobalAuthorityContext = React.createContext({
theme: 'dark',
toggle: () => {},
});
export default GlobalAuthorityContext;

View File

@ -0,0 +1,6 @@
import React from 'react';
// 创建全局的权限控制 context方便在所有页面使用
const UrlsContext = React.createContext({});
export default UrlsContext;

View File

@ -3,6 +3,7 @@ import isEqual from 'lodash/isEqual';
import { formatMessage } from 'umi/locale'; import { formatMessage } from 'umi/locale';
import Authorized from '@/utils/Authorized'; import Authorized from '@/utils/Authorized';
import { menu } from '../defaultSettings'; import { menu } from '../defaultSettings';
import { getAdminMenus, getAdminUrls } from '../services/admin';
const { check } = Authorized; const { check } = Authorized;
@ -70,6 +71,26 @@ const filterMenuData = menuData => {
.map(item => check(item.authority, getSubMenu(item))) .map(item => check(item.authority, getSubMenu(item)))
.filter(item => item); .filter(item => item);
}; };
/**
* 递归构建服务端配置的菜单
* @param resultMenuData
*/
const recursionBuildResultMenu = resultMenuData => {
const res = {};
for (let i = 0; i < resultMenuData.length; i += 1) {
const menuItem = resultMenuData[i];
//
res[menuItem.handler] = {
...menuItem,
};
if (menuItem.children) {
res[menuItem.handler].children = recursionBuildResultMenu(menuItem.children);
}
}
return res;
};
/** /**
* 获取面包屑映射 * 获取面包屑映射
* @param {Object} menuData 菜单配置 * @param {Object} menuData 菜单配置
@ -97,26 +118,59 @@ export default {
state: { state: {
menuData: [], menuData: [],
urlsData: {},
breadcrumbNameMap: {}, breadcrumbNameMap: {},
}, },
effects: { effects: {
*getMenuData({ payload }, { put }) { *getMenuData({ payload }, { put, call }) {
const { data } = yield call(getAdminMenus);
const { routes, authority } = payload; const { routes, authority } = payload;
const menuData = filterMenuData(memoizeOneFormatter(routes, authority)); // authority
const antMenuData = filterMenuData(memoizeOneFormatter(routes, authority));
let menuData = antMenuData;
const resultMenuData = data;
if (data !== 'all') {
//
const buildResultMenu = recursionBuildResultMenu(resultMenuData);
//
menuData = antMenuData.filter(item => {
if (buildResultMenu[item.path]) {
return item;
}
return false;
});
}
// menu router mapping
const breadcrumbNameMap = memoizeOneGetBreadcrumbNameMap(menuData); const breadcrumbNameMap = memoizeOneGetBreadcrumbNameMap(menuData);
yield put({ yield put({
type: 'save', type: 'save',
payload: { menuData, breadcrumbNameMap }, payload: { menuData, breadcrumbNameMap },
}); });
}, },
*getUrlsData(state, { put, call }) {
const { data } = yield call(getAdminUrls);
// {'/user': true} map 便
const urlsData = {};
data.forEach(item => {
urlsData[item] = true;
});
yield put({
type: 'save',
payload: { urlsData },
});
},
}, },
reducers: { reducers: {
save(state, action) { save(state, { payload }) {
return { return {
...state, ...state,
...action.payload, ...payload,
}; };
}, },
}, },

View File

@ -1,7 +1,7 @@
import React, { Component } from 'react'; import React, { Component } from 'react';
import { Button } from 'antd'; import { Button } from 'antd';
import AuthorityControl from '../../components/AuthorityControl'; import AuthorityControl from '../../components/AuthorityControl';
import GlobalAuthority from '../../layouts/GlobalAuthorityContext'; import UrlsContext from '../../layouts/UrlsContext';
export default class Home extends Component { export default class Home extends Component {
state = {}; state = {};
@ -17,12 +17,12 @@ export default class Home extends Component {
}; };
return ( return (
<GlobalAuthority.Provider value={GlobalAuthorityProps}> <UrlsContext.Provider value={GlobalAuthorityProps}>
<AuthorityControl authKey="home.button"> <AuthorityControl authKey="home.button">
<Button type="primary">按钮 控制</Button> <Button type="primary">按钮 控制</Button>
</AuthorityControl> </AuthorityControl>
<h1>home...</h1> <h1>home...</h1>
</GlobalAuthority.Provider> </UrlsContext.Provider>
); );
} }
} }

View File

@ -0,0 +1,10 @@
import { stringify } from 'qs';
import request from '@/utils/request';
export async function getAdminMenus() {
return request('/admin-api/admin/resource/admin_menu_tree');
}
export async function getAdminUrls(params) {
return request(`/admin-api/admin/resource/admin_url_list?${stringify(params)}`);
}

View File

@ -22,20 +22,21 @@ const codeMessage = {
504: '网关超时。', 504: '网关超时。',
}; };
const checkStatus = response => { function checkStatus(response) {
if (response.status >= 200 && response.status < 300) { if (response.status >= 200 && response.status < 300) {
return response; return response;
} }
const errortext = codeMessage[response.status] || response.statusText; const errortext = codeMessage[response.status] || response.statusText;
notification.error({ notification.warning({
message: `请求错误 ${response.status}: ${response.url}`, message: `请求错误 ${response.status}: ${response.url}`,
description: errortext, description: errortext,
}); });
const error = new Error(errortext); const error = new Error(errortext);
error.name = response.status; error.name = response.status;
error.response = response; error.response = response;
throw error; throw error;
}; }
const cachedSave = (response, hashcode) => { const cachedSave = (response, hashcode) => {
/** /**

4
admin-web/笔记 Normal file
View File

@ -0,0 +1,4 @@
登陆账号
admin
nicai