jun.zhang 3 years ago
parent
commit
daae604d6d

+ 8 - 0
src/api/modules/auser.js

@@ -97,3 +97,11 @@ export function getUserRole(data) {
     data: data
   })
 }
+// 点击编辑获取用户角色的接口
+export function getPermissions(userid) {
+  return request({
+    url: '/login/getUserMenu',
+    method: 'get',
+    params: {userid}
+  })
+}

+ 10 - 1
src/config/rules.js

@@ -504,7 +504,16 @@ const rules = {
     roomCode: [{
       required: true,
       trigger: 'blur',
-      message: '请输入接谈室叫号代字'
+      validator: (rule, value, callback) => {
+        const codeReg = /[^a-zA-Z]/
+        if (!value) {
+          return callback(new Error('请输入接谈室叫号代字'))
+        }
+        if (codeReg.test(value)) {
+          return callback(new Error('请输入字母格式'))
+        }
+      }
+      // message: '请输入接谈室叫号代字'
     }],
   },
 }

+ 24 - 0
src/directive/permission.js

@@ -0,0 +1,24 @@
+import store from "@/store/index";
+
+const permission = {
+  inserted(el, binding, vnode) {
+    const { value } = binding;
+    const permissions = store.getters.permissions.map(
+      permission => permission.path
+    );
+    if (value && value instanceof Array && value.length > 0) {
+      const needPermissions = value;
+      const hasPermission = needPermissions.every(item => {
+        return permissions.includes(item);
+      });
+      if (!hasPermission) {
+        el.parentNode && el.parentNode.removeChild(el);
+      }
+    } else {
+      throw new Error(
+        `need roles! Like v-permission="['user:add','user:edit']"`
+      );
+    }
+  }
+};
+export default permission;

+ 64 - 54
src/permission.js

@@ -1,79 +1,89 @@
-import router from './router'
-import store from './store'
-// import { Message } from 'element-ui'
-import NProgress from 'nprogress' // progress bar
-import 'nprogress/nprogress.css' // progress bar style
-import { getToken } from '@/utils/auth' // get token from cookie
-import getPageTitle from '@/utils/get-page-title'
+import router from "./router";
+import store from "./store";
+import { Message } from "element-ui";
+import NProgress from "nprogress"; // progress bar
+import "nprogress/nprogress.css"; // progress bar style
+import { getToken } from "@/utils/auth"; // get token from cookie
+import getPageTitle from "@/utils/get-page-title";
 
-NProgress.configure({ showSpinner: false }) // NProgress Configuration
+NProgress.configure({ showSpinner: false }); // NProgress Configuration
 
-const whiteList = ['/login', '/auth-redirect'] // no redirect whitelist
+const whiteList = ["/login"]; // no redirect whitelist
 
-router.beforeEach(async(to, from, next) => {
+function initRedirect(routes,curPath){
+  for(let item of routes){
+    console.log(item.path);
+    if(item.redirect !==null){
+      if(item.children && item.children.length>0)
+        item.redirect = curPath === "" ? item.path+"/"+ item.children[0].path : curPath+"/"+item.path+"/"+ item.children[0].path;
+    }
+    if(item.children)
+      initRedirect(item.children,curPath === "" ? item.path : curPath+"/"+item.path);
+  }
+  return routes;
+}
+
+router.beforeEach(async (to, from, next) => {
   // start progress bar
-  NProgress.start()
+  NProgress.start();
 
   // set page title
-  document.title = getPageTitle(to.meta.title)
+  document.title = getPageTitle(to.meta.title);
 
   // determine whether the user has logged in
-  const hasToken = getToken()
+  const hasToken = getToken();
 
   if (hasToken) {
-    if (to.path === '/login') {
+    if (to.path === "/login") {
       // if is logged in, redirect to the home page
-      next({ path: '/' })
-      NProgress.done()
+      next({ path: "/" });
+      NProgress.done();
     } else {
-      // 这里敲重点
-      const accessRoutes = await store.dispatch('permission/generateRoutes', [])
-      router.addRoutes(accessRoutes)
-      next()
-      // determine whether the user has obtained his permission roles through getInfo
-      // const hasRoles = store.getters.roles && store.getters.roles.length > 0
-      // next()
-      // if (hasRoles) {
-      //   next()
-      // } else {
-      //   try {
-      //     // get user info
-      //     // note: roles must be a object array! such as: ['admin'] or ,['developer','editor']
-      //     const { roles } = await store.dispatch('user/getRoles')
+      // const hasUserId = store.getters.userId;
+      // const hasGetUserInfo = store.getters.name;
+      const hasPermissions =
+        store.getters.permissions && store.getters.permissions.length > 0;
+      if (hasPermissions) {
+        next();
+      } else {
+        try {
+          if (!hasPermissions) {
+            const permissions = await store.dispatch("user/getPermissions");
+            let accessRoutes = await store.dispatch(
+              "permission/generateRoutes",
+              permissions
+            );
+            router.addRoutes(accessRoutes);
+            next({ ...to, replace: true });
+          } else {
+            next();
+          }
 
-      //     // generate accessible routes map based on roles
-      //     const accessRoutes = await store.dispatch('permission/generateRoutes', roles)
-
-      //     // dynamically add accessible routes
-      //     router.addRoutes(accessRoutes)
-
-      //     // hack method to ensure that addRoutes is complete
-      //     // set the replace: true, so the navigation will not leave a history record
-      //     next({ ...to, replace: true })
-      //   } catch (error) {
-      //     // remove token and go to login page to re-login
-      //     await store.dispatch('user/resetToken')
-      //     Message.error(error || 'Has Error')
-      //     next(`/login?redirect=${to.path}`)
-      //     NProgress.done()
-      //   }
-      // }
+          NProgress.done();
+        } catch (error) {
+          // remove token and go to login page to re-login
+          await store.dispatch("user/resetToken");
+          Message.error(error || "Has Error");
+          next(`/login?redirect=${to.path}`);
+          NProgress.done();
+        }
+      }
     }
   } else {
     /* has no token*/
-
     if (whiteList.indexOf(to.path) !== -1) {
       // in the free login whitelist, go directly
-      next()
+      next();
     } else {
       // other pages that do not have permission to access are redirected to the login page.
-      next(`/login?redirect=${to.path}`)
-      NProgress.done()
+      next(`/login?redirect=${to.path}`);
+      // next();
+      NProgress.done();
     }
   }
-})
+});
 
 router.afterEach(() => {
   // finish progress bar
-  NProgress.done()
-})
+  NProgress.done();
+});

+ 2 - 3
src/router/index.js

@@ -37,7 +37,6 @@ import recordRouter from './modules/record'
     activeMenu: '/example/list'  if set path, the sidebar will highlight the path you set
   }
  */
-
 /**
  * constantRoutes
  * a base page that does not have permission requirements
@@ -104,7 +103,7 @@ newsRouter,
 labelRouter,
 messageRouter,
 rulesRouter,
-caseRouter,
+
 recordRouter,
 
 {
@@ -132,7 +131,7 @@ export const asyncRoutes = [
     component: () => import('@/views/pdf/download'),
     hidden: true
   },
-
+  // caseRouter,
   // {
   //   path: 'external-link',
   //   component: Layout,

+ 2 - 1
src/router/modules/cases.js

@@ -7,7 +7,8 @@ const rulesRouter = {
   name: 'Record',
   meta: {
     title: '短信记录',
-    icon: 'skill'
+    icon: 'skill',
+    permission:["/record"]
   },
   children: [{
     path: 'message',

+ 2 - 1
src/store/getters.js

@@ -17,7 +17,8 @@ const getters = {
   dictValue: state => state.user.dictValue, // 地区id
   type: state => state.user.type, // 层级
   orgID: state => state.user.orgID, // 机构id
-  orgName: state => state.user.orgName// 机构名字
+  orgName: state => state.user.orgName,// 机构名字
+  permissions: state => state.user.permissions// 机构名字
 
 }
 export default getters

+ 13 - 24
src/store/modules/permission.js

@@ -1,31 +1,22 @@
-import { asyncRoutes, constantRoutes } from '@/router'
+import { asyncRoutes, constantRoutes } from "@/router";
+// import * as Router from '@/router';
 
-/**
- * Use meta.role to determine if the current user has permission
- * @param roles
- * @param route
- */
-function hasPermission(roles, route) {
-  if (route.meta && route.meta.roles) {
-    return roles.some(role => route.meta.roles.includes(role))
+
+function hasPermission(permissions, route) {
+  if (route.meta && route.meta.permissions) {
+    return route.meta.permissions.every(permission=>permissions.include(permission));
   } else {
     return true
   }
 }
 
-/**
- * Filter asynchronous routing tables by recursion
- * @param routes asyncRoutes
- * @param roles
- */
-export function filterAsyncRoutes(routes, roles) {
+export function filterAsyncRoutes(routes, permissions) {
   const res = []
-
   routes.forEach(route => {
     const tmp = { ...route }
     if (hasPermission(roles, tmp)) {
       if (tmp.children) {
-        tmp.children = filterAsyncRoutes(tmp.children, roles)
+        tmp.children = filterAsyncRoutes(tmp.children, permissions)
       }
       res.push(tmp)
     }
@@ -47,14 +38,12 @@ const mutations = {
 }
 
 const actions = {
-  generateRoutes({ commit }, roles) {
+  generateRoutes({ commit }, permissions) {
     return new Promise(resolve => {
-      let accessedRoutes
-      if (roles.includes('admin')) {
-        accessedRoutes = asyncRoutes || []
-      } else {
-        accessedRoutes = filterAsyncRoutes(asyncRoutes, roles)
-      }
+      permissions = permissions.map(permission=>permission.path);
+      console.log(Router)
+      debugger;
+      let accessedRoutes = filterAsyncRoutes(asyncRoutes, permissions)
       commit('SET_ROUTES', accessedRoutes)
       resolve(accessedRoutes)
     })

+ 16 - 2
src/store/modules/user.js

@@ -4,6 +4,7 @@ import router, { resetRouter } from '@/router'
 import md5 from 'js-md5'
 // import api from '@/api'
 import * as LoginApi from '@/api/modules/auser.js'
+import permission from '@/directive/permission'
 
 const state = {
   orgID: sessionStorage.getItem('orgID') || '',
@@ -17,7 +18,8 @@ const state = {
   name: '',
   avatar: '',
   introduction: '',
-  roles: []
+  roles: [],
+  permissions:undefined,
 }
 
 const mutations = {
@@ -39,6 +41,9 @@ const mutations = {
   SET_USERID: (state, user_id) => {
     state.user_id = user_id
     localStorage.setItem('user_id', user_id)
+  },
+  SET_PERMISSIONS: (state,permissions)=>{
+    state.permissions = permissions;
   }
 
 }
@@ -63,7 +68,16 @@ const actions = {
       })
     })
   },
-
+  getPermissions({commit,state}){
+    return new Promise((resolve,reject)=>{
+      LoginApi.getPermissions(state.user_id).then(res=>{
+        commit("SET_PERMISSIONS",res.data);
+        resolve(res.data)
+      }).catch(err=>{
+        reject(err)
+      })
+    })
+  },
   // get user info
   // getInfo({ commit, state }) {
   //   return new Promise((resolve, reject) => {

BIN
归档.zip