前端的權(quán)限控制

一 路由文件里定義兩類路由

  1. 沒有權(quán)限要求的路由頁面 constantRoutes
//router/index.js
export const constantRoutes = [
  {
    path: '/login',
    component: () => import('@/views/login/index'),
    hidden: true
  },
  {
    path: '/404',
    component: () => import('@/views/404'),
    hidden: true
  }
]
  1. 用于權(quán)限動態(tài)生成的路由頁面 asyncRoutes
//router/index.js
/**
 * constantRoutes
 * 用于權(quán)限動態(tài)生成的頁面都在這里定義
 */
export const asyncRoutes = [
  {
    path: '/',
    component: Layout,
    redirect: '/dashboard',
    children: [
      {
        path: 'dashboard',
        name: 'Dashboard',
        component: () => import('@/views/dashboard/index'),
        meta: {
          title: 'Dashboard',
          icon: 'dashboard',
          affix: true,
          noCache: true
        }
      }
    ]
  },
  {
    path: '/chatbot', //法務(wù)咨詢AI助手
    component: Layout,
    redirect: '/chatbot/index',
    children: [
      {
        path: 'index',
        name: 'ChatBot',
        component: () => import('@/views/chatbot/index'),
        meta: {
          title: 'LegalChatbot'
        }
      }
    ]
  },
  {
    path: '/translation', //法務(wù)文檔翻譯
    component: Layout,
    redirect: '/translation/index',
    children: [
      {
        path: 'index',
        name: 'Translation',
        component: () => import('@/views/translation/index'),
        meta: {
          title: 'Translation'
        }
      }
    ]
  },
  {
    path: '/interpretation', // 法務(wù)文檔解讀
    component: Layout,
    redirect: '/interpretation/index',
    children: [
      {
        path: 'index',
        name: 'Interpretation',
        component: () => import('@/views/interpretation/index'),
        meta: {
          title: 'Interpretation'
        }
      }
    ]
  },
  {
    path: '/document', //合同 AI
    component: Layout,
    redirect: '/document/index',
    meta: {
      title: 'ContractAI'
    },
    children: [
      {
        path: 'index',
        name: 'ContractReview',
        component: () => import('@/views/document/index'),
        meta: {
          title: 'ContractReview'
        }
      },
      {
        path: 'ai-analysis',
        name: 'AiAnalysis',
        component: () => import('@/views/document/ai-analysis'),
        meta: {
          title: 'AiAnalysis'
        },
        hidden: true
      },
      {
        path: 'version-comparison',
        name: 'VersionComparison',
        component: () => import('@/views/document/version-comparison'),
        meta: {
          title: 'VersionComparison'
        }
      },
      {
        path: 'draft-contract',
        name: 'DraftContract',
        component: () => import('@/views/document/draft-contract'),
        meta: {
          title: 'DraftContract'
        }
      },
      {
        path: 'legal-letter',
        name: 'LegalLetter',
        component: () => import('@/views/document/legal-letter'),
        meta: {
          title: 'LegalLetter'
        }
      },
      {
        path: 'ai-analysis-onlyoffice',
        name: 'AiAnalysisOnlyoffice',
        component: () => import('@/views/document/ai-analysis-onlyoffice'),
        meta: {
          title: 'AiAnalysisOnlyoffice'
        }
      },
    ]
  },
  {
    path: '/tradeCompliance',
    component: Layout,
    redirect: '/tradeCompliance/index',
    children: [
      {
        path: 'index',
        name: 'TradeCompliance',
        component: () => import('@/views/tradeCompliance/index'),
        meta: {
          title: 'TradeCompliance'
        }
      }
    ]
  },
  {
    path: '/esg',
    component: Layout,
    redirect: '/esg/index',
    children: [
      {
        path: 'index',
        name: 'ESG',
        component: () => import('@/views/esg/index'),
        meta: {
          title: 'ESG AI'
        }
      }
    ]
  },
  {
    path: '/dataSecurity',
    component: Layout,
    redirect: '/dataSecurity/index',
    children: [
      {
        path: 'index',
        name: 'DataSecurity',
        component: () => import('@/views/dataSecurity/index'),
        meta: {
          title: 'DataSecurity'
        }
      }
    ]
  },
  {
    path: '/litigation',
    component: Layout,
    redirect: '/litigation/doc-drafting',
    name: 'LitigationAI',
    meta: {
      title: 'LitigationAI'
    },
    children: [
      {
        path: 'case-analysis',
        name: 'CaseAnalysis',
        component: () => import('@/views/litigation/case-analysis'),
        meta: {
          title: 'CaseAnalysis'
        }
      },
      {
        path: 'doc-drafting',
        name: 'DocDrafting',
        component: () => import('@/views/litigation/doc-drafting'),
        meta: {
          title: 'DocDrafting'
        }
      },
      {
        path: 'trial-report-summary',
        name: 'TrialReportSummary',
        component: () => import('@/views/litigation/trial-report-summary'),
        meta: {
          title: 'TrialReportSummary'
        }
      },
      {
        path: 'business-execution-strategy',
        name: 'BusinessExecutionStrategy',
        component: () =>
          import('@/views/litigation/business-execution-strategy'),
        meta: {
          title: 'BusinessExecutionStrategy'
        }
      },
      {
        path: 'similar-litigation-prevention',
        name: 'SimilarLitigationPrevention',
        component: () =>
          import('@/views/litigation/similar-litigation-prevention'),
        meta: {
          title: 'SimilarLitigationPrevention'
        }
      },
      {
        path: 'dispute-alternatives',
        name: 'DisputeAlternatives',
        component: () => import('@/views/litigation/dispute-alternatives'),
        meta: {
          title: 'DisputeAlternatives'
        }
      },
      {
        path: 'foreign-lawyer-expert-matching',
        name: 'ForeignLawyerExpertMatching',
        component: () =>
          import('@/views/litigation/foreign-lawyer-expert-matching'),
        meta: {
          title: 'ForeignLawyerExpertMatching'
        }
      }
    ]
  },
  {
    path: '/knowledge',
    component: Layout,
    redirect: '/knowledge/check-rules',
    name: 'Knowledge',
    meta: {
      title: 'AIConfig'
    },
    children: [
      {
        path: 'check-rules',
        name: 'CheckRules',
        component: () => import('@/views/knowledge/check-rules'),
        meta: {
          title: 'ReviewRules'
        }
      },
      {
        path: 'professional-knowledge',
        name: 'ProfessionalKnowledge',
        component: () => import('@/views/knowledge/professional-knowledge'),
        meta: {
          title: 'Knowledge'
        }
      },
      {
        path: 'professional-knowledge2',
        name: 'ProfessionalKnowledge2',
        component: () => import('@/views/knowledge/professional-knowledge'),
        meta: {
          title: 'Knowledge2'
        }
      }
    ]
  },
  {
    path: '/systemsetting',
    component: Layout,
    redirect: '/systemsetting/role-management',
    name: 'SystemSetting',
    meta: {
      title: 'SystemSetting'
    },
    children: [
      {
        path: 'role-management',
        name: 'RoleManagement',
        component: () => import('@/views/systemsetting/role-management'),
        meta: {
          title: 'RoleManagement'
        }
      },
      {
        path: 'log-management',
        name: 'LogManagement',
        component: () => import('@/views/systemsetting/log-management'),
        meta: {
          title: 'LogManagement'
        }
      }
    ]
  },
  // 404 page must be placed at the end !!!
  {
    path: '*',
    redirect: '/404',
    hidden: true
  }
]

二 在全局前置守衛(wèi)通過接口user/getMenus獲取用戶有權(quán)限的路由頁面 userRouterList

router.beforeEach(async (to, from, next) => {
  // start progress bar
  NProgress.start()

  // set page title
  document.title = getPageTitle(to.meta.title)

  // determine whether the user has logged in
  // const searchParams = new URLSearchParams(window.location.href)
  // const urlToken = searchParams.get('token')
  // urlToken && setToken(urlToken)
  // searchParams.delete('token')
  const hasToken = getToken()
  if (hasToken) {
    if (to.path === '/login') {
      // if is logged in, redirect to the home page
      next({ path: '/' })
      NProgress.done()
    } else {
      const hasGetUserInfo = store.getters.name
      if (hasGetUserInfo) {
        next()
      } else {
        try {
          // get user info
          await store.dispatch('user/getInfo')
          // 獲取權(quán)限列表
          store.dispatch('user/getMenus').then(roles => {
            // 根據(jù)拿到的權(quán)限列表尼摹,獲取動態(tài)路由
            store.dispatch('permission/recursiveRouter', roles).then(res => {
              // 解決下方第七步中的報錯 需要在上方引入該方法 import { resetRouter } from '@/router'
              resetRouter()
              // 解決路由name重復(fù)警告,如果報Router undefined需要在上面引入import Router from 'vue-router'
              router.matcher = new Router().matcher
              // 添加路由
              router.addRoutes(res)
            })
          })
          next()
        } 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=${window.location.href}`)
          NProgress.done()
        }
      }
    }
  } else {
    /* has no token*/

    if (whiteList.indexOf(to.path) !== -1) {
      // in the free login whitelist, go directly
      next()
    } else {
      // other pages that do not have permission to access are redirected to the login page.
      // await store.dispatch('user/loginByAdfs')
      next(`/login?redirect=${window.location.href}`)
      NProgress.done()
    }
  }
})

三 通過循環(huán)遞歸 asyncRoutes 和 userRouterList 出符合用戶權(quán)限的路由表

const actions = {
  /**
   * 根據(jù)用戶路由權(quán)限遞歸路由表
   * @param commit
   * @param userRouterList 用戶路由權(quán)限表
   * @returns {Promise}
   */
  recursiveRouter ({ commit }, userRouterList) {
    return new Promise(resolve => {
      let accessedRoutes = recursiveAsyncRoutes(asyncRoutes, userRouterList)
      commit('SET_ROUTES', accessedRoutes)
      commit('SET_ROUTER_STATE', true)
      resolve(accessedRoutes)
    })
  },
}
/**
 * 通過循環(huán)遞歸出符合用戶權(quán)限的路由表
 * @param asyncRouterList
 * @param userRouterList
 * @returns {*[]}
 */
export function recursiveAsyncRoutes (asyncRouterList, userRouterList) {
  let res = []
  asyncRouterList.forEach(route => {
    const tmp = { ...route }
    if (tmp.path === '*' && !tmp.hasOwnProperty('children')) {
      res.push(tmp)
    } else {
      userRouterList.forEach(uRoute => {
        if (uRoute.menuType != 2) {
          if (hasPath(tmp, uRoute)) {
            if (tmp.children && uRoute.subMenus) {
              tmp.children = recursiveAsyncRoutes(tmp.children, uRoute.subMenus)
            }
            res.push(tmp)
          }
        }
      })
    }
  })
  return res
}

四 通過router.addRoutes(res) 把符合用戶權(quán)限的頁面添加到路由中

五 把最終生成的路由頁面(包括 constantRoutes 和第三部中循環(huán)遍歷出來的符合用戶權(quán)限的頁面)數(shù)組保存在store中

const mutations = {
  /**
   * 設(shè)置路由表
   * @param state 數(shù)據(jù)
   * @param routes 路由
   * @constructor
   */
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  }
}

六 通過store中的路由信息生成導(dǎo)航欄

<template>
      <el-menu
        :default-active="activeMenu"
        :collapse="isCollapse"
        :background-color="variables.menuBg"
        :text-color="variables.menuText"
        :unique-opened="false"
        :active-text-color="variables.menuActiveText"
        :collapse-transition="false"
        mode="vertical"
        v-if="isShow"
      >
        <sidebar-item
          v-for="route in routes"
          :key="route.path"
          :item="route"
          :base-path="route.path"
        />
      </el-menu>
</template>

<script>
export default {
  computed: {
    routes () {
      return this.$store.state.permission.routes
    }
  }
}
</script>

參考文獻

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末领迈,一起剝皮案震驚了整個濱河市脚仔,隨后出現(xiàn)的幾起案子债热,更是在濱河造成了極大的恐慌借嗽,老刑警劉巖乱凿,帶你破解...
    沈念sama閱讀 219,366評論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件获列,死亡現(xiàn)場離奇詭異讯屈,居然都是意外死亡绑蔫,警方通過查閱死者的電腦和手機运沦,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,521評論 3 395
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來配深,“玉大人携添,你說我怎么就攤上這事÷ㄒ叮” “怎么了烈掠?”我有些...
    開封第一講書人閱讀 165,689評論 0 356
  • 文/不壞的土叔 我叫張陵,是天一觀的道長缸托。 經(jīng)常有香客問我左敌,道長,這世上最難降的妖魔是什么嗦董? 我笑而不...
    開封第一講書人閱讀 58,925評論 1 295
  • 正文 為了忘掉前任母谎,我火速辦了婚禮,結(jié)果婚禮上京革,老公的妹妹穿的比我還像新娘奇唤。我一直安慰自己,他們只是感情好匹摇,可當(dāng)我...
    茶點故事閱讀 67,942評論 6 392
  • 文/花漫 我一把揭開白布咬扇。 她就那樣靜靜地躺著,像睡著了一般廊勃。 火紅的嫁衣襯著肌膚如雪懈贺。 梳的紋絲不亂的頭發(fā)上经窖,一...
    開封第一講書人閱讀 51,727評論 1 305
  • 那天,我揣著相機與錄音梭灿,去河邊找鬼画侣。 笑死,一個胖子當(dāng)著我的面吹牛堡妒,可吹牛的內(nèi)容都是我干的配乱。 我是一名探鬼主播,決...
    沈念sama閱讀 40,447評論 3 420
  • 文/蒼蘭香墨 我猛地睜開眼皮迟,長吁一口氣:“原來是場噩夢啊……” “哼搬泥!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起伏尼,我...
    開封第一講書人閱讀 39,349評論 0 276
  • 序言:老撾萬榮一對情侶失蹤忿檩,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后爆阶,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體燥透,經(jīng)...
    沈念sama閱讀 45,820評論 1 317
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,990評論 3 337
  • 正文 我和宋清朗相戀三年扰她,在試婚紗的時候發(fā)現(xiàn)自己被綠了兽掰。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 40,127評論 1 351
  • 序言:一個原本活蹦亂跳的男人離奇死亡徒役,死狀恐怖孽尽,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情忧勿,我是刑警寧澤杉女,帶...
    沈念sama閱讀 35,812評論 5 346
  • 正文 年R本政府宣布,位于F島的核電站鸳吸,受9級特大地震影響熏挎,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜晌砾,卻給世界環(huán)境...
    茶點故事閱讀 41,471評論 3 331
  • 文/蒙蒙 一坎拐、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧养匈,春花似錦哼勇、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,017評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至猬仁,卻和暖如春帝璧,著一層夾襖步出監(jiān)牢的瞬間先誉,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,142評論 1 272
  • 我被黑心中介騙來泰國打工的烁, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留褐耳,地道東北人。 一個月前我還...
    沈念sama閱讀 48,388評論 3 373
  • 正文 我出身青樓渴庆,卻偏偏與公主長得像漱病,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子把曼,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 45,066評論 2 355

推薦閱讀更多精彩內(nèi)容