permission.js 2.08 KB
Newer Older
Pan's avatar
Pan committed
1 2
import router from './router'
import store from './store'
花裤衩's avatar
花裤衩 committed
3
import { Message } from 'element-ui'
4 5 6 7
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { getToken } from '@/utils/auth'
import { isRelogin } from '@/utils/request'
8

9
NProgress.configure({ showSpinner: false })
Pan's avatar
Pan committed
10

11
const whiteList = ['/login', '/register']
花裤衩's avatar
花裤衩 committed
12

13 14
router.beforeEach((to, from, next) => {
  console.log('console.log(to)',to)
Pan's avatar
Pan committed
15
  NProgress.start()
16 17 18
  if (getToken()) {
    to.meta.title && store.dispatch('settings/setTitle', to.meta.title)
    /* has token*/
Pan's avatar
Pan committed
19 20
    if (to.path === '/login') {
      next({ path: '/' })
花裤衩's avatar
花裤衩 committed
21
      NProgress.done()
22 23
    } else if (whiteList.indexOf(to.path) !== -1) {
      next()
Pan's avatar
Pan committed
24
    } else {
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
      if (store.getters.roles.length === 0) {
        console.log('console.log(store.getters.roles.length)',store.getters.roles)
        isRelogin.show = true
        // 判断当前用户是否已拉取完user_info信息
        store.dispatch('user/getInfo').then(() => {
          isRelogin.show = false
          store.dispatch('GenerateRoutes').then(accessRoutes => {
            console.log('accessRoutes',accessRoutes)
            // 根据roles权限生成可访问的路由表
            router.addRoutes(accessRoutes) // 动态添加可访问路由表
            if (to.path == '/') {
              var path = accessRoutes[0].path == '/' ? '' : accessRoutes[0].path + '/' + accessRoutes[0].children[0].path
              next({ path: path })
            } else {
              next({ ...to, replace: true }) // hack方法 确保addRoutes已完成
            }
          })
        }).catch(err => {
          store.dispatch('LogOut').then(() => {
            Message.error(err)
            next({ path: '/' })
          })
        })
花裤衩's avatar
花裤衩 committed
48
      } else {
49
        next()
Pan's avatar
Pan committed
50 51 52
      }
    }
  } else {
53
    // 没有token
Pan's avatar
Pan committed
54
    if (whiteList.indexOf(to.path) !== -1) {
55
      // 在免登录白名单,直接进入
Pan's avatar
Pan committed
56 57
      next()
    } else {
58
      next(`/login?redirect=${encodeURIComponent(to.fullPath)}`) // 否则全部重定向到登录页
Pan's avatar
Pan committed
59 60 61 62 63 64
      NProgress.done()
    }
  }
})

router.afterEach(() => {
花裤衩's avatar
花裤衩 committed
65
  NProgress.done()
Pan's avatar
Pan committed
66
})