permission.js 5.77 KB
import router from '@/router'
import store from '@/store'
import HtProgress from 'nprogress'
import { Message } from 'element-ui'
import 'nprogress/nprogress.css'
import getPageTitle from '@/utils/pageTitle'
import {
  loginInterception,
  progressBar,
  fullScreenKey,
  tokenName,
  strictRouterMode,
  casTokenName,
  oauthTokenName,
} from '@/config'
import { ridUrlParam } from '@/utils'
import ssoLogin from './ssoLogin.js'
import removeTooltip from '@/services/removeTooltip.js'

import { getLongUrlByShortUrl, fileUrl } from '@/api/portal'
import { getTenantInfo } from '@/api/uc'

HtProgress.configure({
  easing: 'ease',
  speed: 500,
  trickleSpeed: 200,
  showSpinner: false,
})

const handelShortUrl = (to, from, next) => {
  getLongUrlByShortUrl(to.fullPath.substr(1))
    .then((res) => {
      if (res.state) {
        const { value } = res
        if (value.guestToken) {
          next({
            path: `${value.url}&isShortUrl=true&token=${value.guestToken}&__isFull__=true`,
          })
        } else {
          next({ path: '/login' })
        }
      } else {
        next({ path: '/login' })
      }
    })
    .catch(() => {})
}

const handleApplication = (to, from) => {
  if (from.fullPath.startsWith('/app/')) {
    // 自己跳自己时,不打开新页签
    if (to.fullPath.startsWith('/app/')) {
      return false
    }
    // 退出时,跳转路由
    if (to.fullPath === '/login') {
      return false
    }
    if (to.fullPath === '/') {
      return true
    }
    store.dispatch('app/addVisitedMenuByObject', {
      id: 'ht' + to.fullPath,
      type: 11,
      name: to.meta.title,
      content: to.fullPath,
    })
    return true
  }
  return false
}

router.beforeResolve(async (to, from, next) => {
  if (to.fullPath.startsWith('/surl/')) {
    handelShortUrl(to, from, next)
    return
  }
  if (handleApplication(to, from)) {
    return
  }

  if (progressBar) HtProgress.start()
  // 是否已经获取到token
  let hasToken = store.getters['user/accessToken']

  if (!loginInterception) hasToken = true

  if (hasToken) {
    // 有token时还请求login时重定向到默认路由
    if (to.path === '/login') {
      next({ path: '/' })
      if (progressBar) HtProgress.done()
    } else {
      if (loginInterception) {
        await store.dispatch('user/getUserInfo')
      }
      const tenant =
        from.query?.tenant || store.getters['user/tenantCode'] || 'platform'
      getTenantInfo(tenant)
        .then((res) => {
          const { frontLogo } = res.value || {}
          let logoImgURL = ''
          if (frontLogo) {
            const logoImgInfo = JSON.parse(frontLogo)
            logoImgURL = fileUrl(logoImgInfo[0].id)
          }
          localStorage.setItem('frontLogo', logoImgURL)
        })
        .catch((e) => {
          console.error(e)
        })
      const routes = store.getters['routes/routes']
      let accessRoutes = []
      // 是否已经加载了routes
      if (routes && routes.length > 0) {
        next()
      } else {
        try {
          // 加载路由
          accessRoutes = await store.dispatch('routes/setAllRoutes')
          accessRoutes.forEach((route) => {
            router.addRoute(route)
          })
          if (to.fullPath.includes('/loading')) {
            next({ path: '/', replace: true })
          } else next({ ...to, replace: true })
        } catch (e) {
          if (strictRouterMode) {
            await store.dispatch('user/resetAccessToken')
            throw e
          } else {
            next({ ...to, replace: true })
          }
          if (progressBar) HtProgress.done()
        }
      }
      // 若重定向过来的页面不在授权内,则提示缺陷
      if(to.redirectedFrom){
        let isExist = false
        if(to.redirectedFrom.includes('/index')){
          // 管理端通过用户跳转问题
          isExist = true
        }
        if([...routes, ...accessRoutes]
          .map((item) => item.path)
          .includes(to.redirectedFrom)){
            isExist=true
        }
        if(!isExist){
          for (const i in routes){
            if(isExist){
              break
            }
            if(routes[i].children){
              for (const j in routes[i].children){
                let r = routes[i].children[j]
                if(r.path && r.path.replace('//', '/').includes(to.redirectedFrom)){
                  isExist=true
                  break;
                }
              }
            }
          }
        }
        if (!isExist) {
          Message.warning('您无菜单权限,请联系管理员授权!')
        }
      }
    }
  } else {
    ssoLogin(to, from, next)
  }
  document.title = getPageTitle(to.meta.title)
})

router.afterEach((to) => {
  // 是否有全屏显示页面的url参数
  if (to.query && to.query.hasOwnProperty(fullScreenKey)) {
    if (to.query[fullScreenKey] === 'true') {
      // 有则更新到vuex中
      store.dispatch('routes/setFullScreenState', true)
    }
    // const ridUrl = ridUrlParam(to.fullPath, [fullScreenKey])
    // // 地址栏中移除该参数
    // router.replace(ridUrl)
  }
  if (to.query && to.query.hasOwnProperty(tokenName)) {
    const tidUrl = ridUrlParam(to.fullPath, [tokenName])
    router.replace(tidUrl)
  }
  // 登录成功后cas单点登录模式下清除票据参数
  if (
    window.ssoConfig.mode == 'cas' &&
    to.query &&
    to.query.hasOwnProperty(casTokenName)
  ) {
    const tidUrl = ridUrlParam(to.fullPath, [casTokenName])
    router.replace(tidUrl)
  }
  // 登录成功后oauth单点登录模式下清除票据参数
  if (
    window.ssoConfig.mode == 'oauth' &&
    to.query &&
    to.query.hasOwnProperty(oauthTokenName)
  ) {
    const tidUrl = ridUrlParam(to.fullPath, [oauthTokenName])
    router.replace(tidUrl)
  }
  // 切换时隐藏tooltip
  removeTooltip()
  if (progressBar) HtProgress.done()
})