003-pro ant design 前端权限处理-支持URL参数的页面

前天需要增加MD5引用

  https://www.bootcdn.cn/blueimp-md5/

1、修改权限文件(CheckPermissions.js)使用自定义权限

  

2、配置异常页面

2.1、创建异常页面

  /src/pages/Exception

import React from 'react';
import { formatMessage } from 'umi/locale';
import Link from 'umi/link';
import Exception from '@/components/Exception';

const Exception400 = () => (
  <Exception
    type="400"
    desc={formatMessage({ id: 'app.exception.description.400' })}
    linkElement={Link}
    backText={formatMessage({ id: 'app.exception.back' })}
  />
);

export default Exception400;

2.2、增加400页面配置项

  /src/components/Exception/typeConfig.js

const config = {
  400: {
    img: 'https://gw.alipayobjects.com/zos/rmsportal/wZcnGqRDyhPOEYFcZDnb.svg',
    title: '400',
    desc: '抱歉,你无权访问该页面或该页面不存在',
  },
   //......
}

2.3、添加中英文菜单对照

  /src/locales/zh-CN.js

'app.exception.description.400': '抱歉,你无权限访问该页面或该页面不存在',

 

2.4、将400页面引入(BasicLayout.js)

  /src/layouts/BasicLayout.js  

import Exception400 from '../pages/Exception/400';

 

3、权限菜单控制开发

3.1、获取远端服务器授权菜单

  /src/layouts/BasicLayout.js

  state中增加menuPermissionData参数 

  state = {
    rendering: true,
    isMobile: false,
    menuData: this.getMenuData(),
    menuPermissionData: '',
  }

  在componentWillMount中增加后端请求并赋值menuPermissionData

    dispatch({
      type: 'common/getMenuPermissionData',
      callback: res => {
        console.log(res);
        if (res && res.code == 20000) {
          this.setState({
            menuPermissionData: JSON.stringify(res.data),
          });
        }
      },
});

对于model,service请求需要自行开发

返回值格式:

{
    "code": 20000,
    "msg": "操作成功",
    "data": [
        {
            "menuList": [
                {
                    "menuList": [],
                    "url": "/data/#/menu1/son",
                },
                {
                    "menuList": [
                        {
                            "menuList": [],
                            "url": "/data/#/menu2/:id",
                        },
                        {
                            "menuList": [],
                            "url": "/data/#/menu3/:id/add",
                        }
                    ],
                    "id": 399,
                    "url": "/data/#/menu4",
                },
            ],
            "id": 384,
            "url": "",
        }
    ]
}

后端接口可以返回:/data/#/menu3/:id/add菜单

针对

/data/#/menu3/4/add
/data/#/menu3/5/add

可以通过

3.2、控制逻辑,增加两个方法

  validMatchUrl =(menuPermissionDataStr, currentHashUrl) =>{
    // currentHashUrl = '/operate/skuFormField/6';
    let fullMatch = [];//完全匹配地址
    let ruleMatch = [];//规则匹配地址
    const regRule2 = /\//g;
    let menuPermissionData =JSON.parse(menuPermissionDataStr);
    const menuPermissionDataMd5 = localStorage.getItem('menuPermissionData');
    const currentMenuMd5 = md5(JSON.stringify(menuPermissionData));
    if (menuPermissionDataMd5 && menuPermissionDataMd5 === currentMenuMd5) {
      console.log('----cache-----',menuPermissionData);
      fullMatch = JSON.parse(localStorage.getItem('menuPermissionData_fullMatch'));
      ruleMatch = JSON.parse(localStorage.getItem('menuPermissionData_ruleMatch'));
    } else {
      console.log('----no cache-----',menuPermissionData);
      fullMatch.push("/");
      fullMatch.push("/index");
      menuPermissionData.map(t => {
        this.iterMenuList(fullMatch,ruleMatch,t.menuList);
      });
      localStorage.setItem('menuPermissionData_fullMatch', JSON.stringify(fullMatch));
      localStorage.setItem('menuPermissionData_ruleMatch', JSON.stringify(ruleMatch));
      localStorage.setItem('menuPermissionData', currentMenuMd5);
    }
    //全匹配地址
    console.log('using fullMatch route start');
    if (fullMatch.indexOf(currentHashUrl) != -1) {
      //匹配成功
      console.log('using fullMatch route result:true');
      console.log('using fullMatch route end');
      return true;
    }
    console.log('using fullMatch route end');
    //规则匹配地址
    // 原始URL分解
    //路由个数
    console.log('using ruleMatch route start');
    const routkeyNum = currentHashUrl.match(regRule2).length;
    const matchRouteObj=ruleMatch.find(e => e && e.key === routkeyNum);
    if(matchRouteObj && matchRouteObj.value && matchRouteObj.value.length>0){
      const tmpRuleMatchArr = matchRouteObj.value;
      for (let i = 0; i < tmpRuleMatchArr.length; i++) {
        const f = tmpRuleMatchArr[i];
        let tmpFlag = true;
        for (let i = 0; i < f.length; i++) {
          if (f[i] === '/:') {
            tmpFlag = true;
            continue;
          } else if (f[i] !== ('/' + currentHashUrl.split('/').filter(d => d && d.length > 0)[i])) {
            tmpFlag = false;
            break;
          }
        }
        if (tmpFlag){
          console.log('using ruleMatch route result:true');
          console.log('using ruleMatch route end');
          return true;
        }
      }
    }
    console.log('using ruleMatch route result:false');
    console.log('using ruleMatch route end');
    return false;
  }

  iterMenuList=(fullMatch,ruleMatch,menuList)=>{
    const regRule2 = /\//g;
    if(menuList && menuList.length>0){
      menuList.map(a => {
        const url = a.url.indexOf('#') != -1 ? a.url.split('#')[1] : a.url;
        if (url.indexOf('/:') == -1) {
          fullMatch.push(url);//完全匹配地址
        } else {
          //    获取map是否有对应的路由个数
          const routkey = url.match(regRule2).length;
          const tmpMapValue = ruleMatch.find(c => {
            return c && c.key === routkey;
          });
          //构建当前URL
          const tmpRuleRuleArr = url.split('/').filter(c => {
            return c && c.length > 0;
          });
          const tmpRuleRuleArr2 = tmpRuleRuleArr.map(b => {
            if (b && b.length > 0) {
              return b = b.startsWith(':') ? '/:' : ('/' + b);
            }
          });
          if (tmpMapValue && tmpMapValue.value && tmpMapValue.value.length > 0) {
            tmpMapValue.value.push(tmpRuleRuleArr2);
          } else {
            // 没有的话添加
            const a = [];
            a.push(tmpRuleRuleArr2);
            ruleMatch.push({ key: routkey, value: a });
          }
        }

        this.iterMenuList(fullMatch,ruleMatch,a.menuList);
      });
    }else{
      return ;
    }
  }
View Code

3.3、render增加权限控制

数据引入

    const { isMobile, menuData, menuPermissionData, openLocalConfig, isShowChildren } = this.state;

在Content中增加

          <Content style={this.getContentStyle()}>
            <Authorized
              authority={routerConfig && routerConfig.authority}
              noMatch={<Exception403 />}
            >
              {
                (menuPermissionData != '') ?
                  (
                    this.validMatchUrl(menuPermissionData,location.hash.split('?')[0].replace(new RegExp('#', 'g'), ''))
                      ? children:<Exception400 />
                  )
                  :''
                  
              }
            </Authorized>
          </Content>

 

 

 

 

 

 

 

  

 

posted @ 2019-03-07 11:13  bjlhx15  阅读(2310)  评论(0编辑  收藏  举报
Copyright ©2011~2020 JD-李宏旭