permission.js 2.4 KB
Newer Older
P
Pan 已提交
1 2
import router from './router'
import store from './store'
P
Pan 已提交
3
import { Message } from 'element-ui'
花裤衩 已提交
4
import NProgress from 'nprogress' // progress bar
5 6
import 'nprogress/nprogress.css' // progress bar style
import { getToken } from '@/utils/auth' // get token from cookie
7
import getPageTitle from '@/utils/get-page-title'
P
Pan 已提交
8

9
NProgress.configure({ showSpinner: false }) // NProgress Configuration
P
Pan 已提交
10

11
const whiteList = ['/login', '/auth-redirect'] // no redirect whitelist
P
Pan 已提交
12

花裤衩 已提交
13 14 15 16
router.beforeEach(async(to, from, next) => {
  // start progress bar
  NProgress.start()

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

花裤衩 已提交
20 21
  // determine whether the user has logged in
  const hasToken = getToken()
22

花裤衩 已提交
23
  if (hasToken) {
P
Pan 已提交
24
    if (to.path === '/login') {
花裤衩 已提交
25
      // if is logged in, redirect to the home page
P
Pan 已提交
26
      next({ path: '/' })
花裤衩 已提交
27
      NProgress.done() // hack: https://github.com/PanJiaChen/vue-element-admin/pull/2939
P
Pan 已提交
28
    } else {
花裤衩 已提交
29 30 31 32
      // determine whether the user has obtained his permission roles through getInfo
      const hasRoles = store.getters.roles && store.getters.roles.length > 0
      if (hasRoles) {
        next()
P
Pan 已提交
33
      } else {
花裤衩 已提交
34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
        try {
          // get user info
          // note: roles must be a object array! such as: ['admin'] or ,['developer','editor']
          const { roles } = await store.dispatch('user/getInfo')

          // 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()
P
Pan 已提交
54 55 56 57
        }
      }
    }
  } else {
P
Pan 已提交
58
    /* has no token*/
花裤衩 已提交
59

60
    if (whiteList.indexOf(to.path) !== -1) {
花裤衩 已提交
61
      // in the free login whitelist, go directly
P
Pan 已提交
62 63
      next()
    } else {
花裤衩 已提交
64 65 66
      // other pages that do not have permission to access are redirected to the login page.
      next(`/login?redirect=${to.path}`)
      NProgress.done()
P
Pan 已提交
67 68 69 70 71
    }
  }
})

router.afterEach(() => {
花裤衩 已提交
72 73
  // finish progress bar
  NProgress.done()
P
Pan 已提交
74
})