fe-drone-ci/src/permission.js

64 lines
2.5 KiB
JavaScript
Raw Normal View History

2017-08-21 07:55:46 +00:00
import router from './router'
import store from './store'
2018-01-05 03:38:34 +00:00
import { Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css'// progress bar style
import { getToken } from '@/utils/auth' // getToken from cookie
2017-08-21 07:55:46 +00:00
2018-01-05 03:38:34 +00:00
NProgress.configure({ showSpinner: false })// NProgress Configuration
// permissiom judge function
2017-08-21 07:55:46 +00:00
function hasPermission(roles, permissionRoles) {
if (roles.indexOf('admin') >= 0) return true // admin permission passed directly
2017-08-21 07:55:46 +00:00
if (!permissionRoles) return true
return roles.some(role => permissionRoles.indexOf(role) >= 0)
}
const whiteList = ['/login', '/authredirect']// no redirect whitelist
2017-11-17 09:51:41 +00:00
2017-08-21 07:55:46 +00:00
router.beforeEach((to, from, next) => {
NProgress.start() // start progress bar
2018-01-05 03:38:34 +00:00
if (getToken()) { // determine if there has token
/* has token*/
2017-08-21 07:55:46 +00:00
if (to.path === '/login') {
next({ path: '/' })
2018-01-05 03:38:34 +00:00
NProgress.done() // if current page is dashboard will not trigger afterEach hook, so manually handle it
2017-08-21 07:55:46 +00:00
} else {
if (store.getters.roles.length === 0) { // 判断当前用户是否已拉取完user_info信息
2017-08-23 03:39:16 +00:00
store.dispatch('GetUserInfo').then(res => { // 拉取user_info
2018-01-05 03:38:34 +00:00
const roles = res.data.roles // note: roles must be a array! such as: ['editor','develop']
store.dispatch('GenerateRoutes', { roles }).then(() => { // 根据roles权限生成可访问的路由表
2017-08-21 07:55:46 +00:00
router.addRoutes(store.getters.addRouters) // 动态添加可访问路由表
next({ ...to, replace: true }) // hack方法 确保addRoutes已完成 ,set the replace: true so the navigation will not leave a history record
2017-08-21 07:55:46 +00:00
})
}).catch(() => {
store.dispatch('FedLogOut').then(() => {
Message.error('Verification failed, please login again')
2017-08-21 07:55:46 +00:00
next({ path: '/login' })
})
})
} else {
// 没有动态改变权限的需求可直接next() 删除下方权限判断 ↓
2018-01-05 03:38:34 +00:00
if (hasPermission(store.getters.roles, to.meta.roles)) {
2017-08-21 07:55:46 +00:00
next()//
} else {
2018-01-05 03:38:34 +00:00
next({ path: '/401', replace: true, query: { noGoBack: true }})
2017-08-21 07:55:46 +00:00
}
// 可删 ↑
}
}
} else {
2018-01-05 03:38:34 +00:00
/* has no token*/
2017-08-21 07:55:46 +00:00
if (whiteList.indexOf(to.path) !== -1) { // 在免登录白名单,直接进入
next()
} else {
next('/login') // 否则全部重定向到登录页
2018-01-05 03:38:34 +00:00
NProgress.done() // if current page is login will not trigger afterEach hook, so manually handle it
2017-08-21 07:55:46 +00:00
}
}
})
router.afterEach(() => {
NProgress.done() // finish progress bar
2017-08-21 07:55:46 +00:00
})