guigu-oa-admin/src/permission.js

75 lines
2.3 KiB
JavaScript
Raw Normal View History

2017-08-30 17:42:06 +08:00
import router from './router'
import store from './store'
2019-04-19 20:41:52 +08:00
import { Message } from 'element-ui'
2019-02-20 13:31:27 +08:00
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
2019-04-19 20:41:52 +08:00
import { getToken } from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'
2019-02-20 13:31:27 +08:00
2019-04-19 20:41:52 +08:00
NProgress.configure({ showSpinner: false }) // NProgress Configuration
2017-08-30 17:42:06 +08:00
2019-04-19 20:41:52 +08:00
const whiteList = ['/login'] // no redirect whitelist
router.beforeEach(async(to, from, next) => {
// start progress bar
2017-08-30 17:42:06 +08:00
NProgress.start()
2019-04-19 20:41:52 +08:00
// set page title
document.title = getPageTitle(to.meta.title)
// determine whether the user has logged in
const hasToken = getToken()
if (hasToken) {
2017-08-30 17:42:06 +08:00
if (to.path === '/login') {
2019-04-19 20:41:52 +08:00
// if is logged in, redirect to the home page
2017-08-30 17:42:06 +08:00
next({ path: '/' })
2019-04-19 20:41:52 +08:00
NProgress.done()
2017-08-30 17:42:06 +08:00
} else {
2019-04-19 20:41:52 +08:00
// determine whether the user has obtained his permission roles through getInfo
const hasRoles = store.getters.roles && store.getters.roles.length > 0
if (hasRoles) {
2017-08-30 17:42:06 +08:00
next()
2019-04-19 20:41:52 +08:00
} else {
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()
}
2017-08-30 17:42:06 +08:00
}
}
} else {
2019-04-19 20:41:52 +08:00
/* has no token*/
2017-08-30 17:42:06 +08:00
if (whiteList.indexOf(to.path) !== -1) {
2019-04-19 20:41:52 +08:00
// in the free login whitelist, go directly
2017-08-30 17:42:06 +08:00
next()
} else {
2019-04-19 20:41:52 +08:00
// other pages that do not have permission to access are redirected to the login page.
next(`/login?redirect=${to.path}`)
2017-08-30 17:42:06 +08:00
NProgress.done()
}
}
})
router.afterEach(() => {
2019-04-19 20:41:52 +08:00
// finish progress bar
NProgress.done()
2017-08-30 17:42:06 +08:00
})