mt-ck-wms-ui/src/permission.js
2021-12-22 16:13:55 +08:00

76 lines
2.5 KiB
JavaScript

/*
* @Date: 2020-12-14 09:07:03
* @LastEditors: zwq
* @LastEditTime: 2021-12-22 16:13:30
* @FilePath: \basic-admin\src\permission.js
* @Description: 路由权限检查
*/
import router from './router'
import { Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { getToken } from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'
// import { usePermission } from './settings'
NProgress.configure({ showSpinner: true }) // NProgress Configuration
import store from '@/store'
const whiteList = ['/login', '/auth-redirect'] // no redirect whitelist
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 hasToken = getToken()
console.log('hasToken=' + hasToken)
console.log('to.path=' + to.path)
if (hasToken) {
if (to.path === '/login') {
// if is logged in, redirect to the home page
console.log('/login', store.getters.menus)
next({ path: '/' })
NProgress.done() // hack: https://github.com/PanJiaChen/vue-element-admin/pull/2939
} else {
// next()
NProgress.done()
try {
// // generate accessible routes map based on roles
// const accessRoutes = await store.dispatch('permission/generateRoutes')
// console.log(accessRoutes)
// router.addRoutes(accessRoutes)
next()
// 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
next(`/login?redirect=${to.path}`)
await store.dispatch('user/resetToken')
Message.error(error || 'Has Error')
NProgress.done()
}
}
} else {
/* has no token*/
console.log('to.path=' + to.path)
console.log('whiteList.indexOf(to.path)=' + whiteList.indexOf(to.path))
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.
// next()
next(`/login?redirect=${to.path}`)
NProgress.done()
}
}
})
router.afterEach(() => {
// finish progress bar
NProgress.done()
})